text
stringlengths
5
1.04M
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include "opencv2/imgproc/imgproc_c.h" #include "calib3d_c_api.h" #include <vector> #include <algorithm> using namespace cv; using namespace std; static void icvGetQuadrangleHypotheses(const std::vector<std::vector< cv::Point > > & contours, const std::vector< cv::Vec4i > & hierarchy, std::vector<std::pair<float, int> >& quads, int class_id) { const float min_aspect_ratio = 0.3f; const float max_aspect_ratio = 3.0f; const float min_box_size = 10.0f; typedef std::vector< std::vector< cv::Point > >::const_iterator iter_t; iter_t i; for (i = contours.begin(); i != contours.end(); ++i) { const iter_t::difference_type idx = i - contours.begin(); if (hierarchy.at(idx)[3] != -1) continue; // skip holes const std::vector< cv::Point > & c = *i; cv::RotatedRect box = cv::minAreaRect(c); float box_size = MAX(box.size.width, box.size.height); if(box_size < min_box_size) { continue; } float aspect_ratio = box.size.width/MAX(box.size.height, 1); if(aspect_ratio < min_aspect_ratio || aspect_ratio > max_aspect_ratio) { continue; } quads.emplace_back(box_size, class_id); } } static void countClasses(const std::vector<std::pair<float, int> >& pairs, size_t idx1, size_t idx2, std::vector<int>& counts) { counts.assign(2, 0); for(size_t i = idx1; i != idx2; i++) { counts[pairs[i].second]++; } } inline bool less_pred(const std::pair<float, int>& p1, const std::pair<float, int>& p2) { return p1.first < p2.first; } static void fillQuads(Mat & white, Mat & black, double white_thresh, double black_thresh, vector<pair<float, int> > & quads) { Mat thresh; { vector< vector<Point> > contours; vector< Vec4i > hierarchy; threshold(white, thresh, white_thresh, 255, THRESH_BINARY); findContours(thresh, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE); icvGetQuadrangleHypotheses(contours, hierarchy, quads, 1); } { vector< vector<Point> > contours; vector< Vec4i > hierarchy; threshold(black, thresh, black_thresh, 255, THRESH_BINARY_INV); findContours(thresh, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE); icvGetQuadrangleHypotheses(contours, hierarchy, quads, 0); } } static bool checkQuads(vector<pair<float, int> > & quads, const cv::Size & size) { const size_t min_quads_count = size.width*size.height/2; std::sort(quads.begin(), quads.end(), less_pred); // now check if there are many hypotheses with similar sizes // do this by floodfill-style algorithm const float size_rel_dev = 0.4f; for(size_t i = 0; i < quads.size(); i++) { size_t j = i + 1; for(; j < quads.size(); j++) { if(quads[j].first/quads[i].first > 1.0f + size_rel_dev) { break; } } if(j + 1 > min_quads_count + i) { // check the number of black and white squares std::vector<int> counts; countClasses(quads, i, j, counts); const int black_count = cvRound(ceil(size.width/2.0)*ceil(size.height/2.0)); const int white_count = cvRound(floor(size.width/2.0)*floor(size.height/2.0)); if(counts[0] < black_count*0.75 || counts[1] < white_count*0.75) { continue; } return true; } } return false; } // does a fast check if a chessboard is in the input image. This is a workaround to // a problem of cvFindChessboardCorners being slow on images with no chessboard // - src: input image // - size: chessboard size // Returns 1 if a chessboard can be in this image and findChessboardCorners should be called, // 0 if there is no chessboard, -1 in case of error int cvCheckChessboard(IplImage* src, CvSize size) { cv::Mat img = cv::cvarrToMat(src); return (int)cv::checkChessboard(img, size); } bool cv::checkChessboard(InputArray _img, Size size) { Mat img = _img.getMat(); CV_Assert(img.channels() == 1 && img.depth() == CV_8U); const int erosion_count = 1; const float black_level = 20.f; const float white_level = 130.f; const float black_white_gap = 70.f; Mat white; Mat black; erode(img, white, Mat(), Point(-1, -1), erosion_count); dilate(img, black, Mat(), Point(-1, -1), erosion_count); bool result = false; for(float thresh_level = black_level; thresh_level < white_level && !result; thresh_level += 20.0f) { vector<pair<float, int> > quads; fillQuads(white, black, thresh_level + black_white_gap, thresh_level, quads); if (checkQuads(quads, size)) result = true; } return result; } // does a fast check if a chessboard is in the input image. This is a workaround to // a problem of cvFindChessboardCorners being slow on images with no chessboard // - src: input binary image // - size: chessboard size // Returns 1 if a chessboard can be in this image and findChessboardCorners should be called, // 0 if there is no chessboard, -1 in case of error int checkChessboardBinary(const cv::Mat & img, const cv::Size & size) { CV_Assert(img.channels() == 1 && img.depth() == CV_8U); Mat white = img.clone(); Mat black = img.clone(); int result = 0; for ( int erosion_count = 0; erosion_count <= 3; erosion_count++ ) { if ( 1 == result ) break; if ( 0 != erosion_count ) // first iteration keeps original images { erode(white, white, Mat(), Point(-1, -1), 1); dilate(black, black, Mat(), Point(-1, -1), 1); } vector<pair<float, int> > quads; fillQuads(white, black, 128, 128, quads); if (checkQuads(quads, size)) result = 1; } return result; }
#include "Classes/Qt/Scene/Validation/ValidationProgress.h" #include "Classes/Qt/Scene/Validation/ValidationProgressConsumer.h" #include <Debug/DVAssert.h> void ValidationProgress::Started(const DAVA::String& title) { DVASSERT(consumer != nullptr); result = DAVA::Result::RESULT_SUCCESS; consumer->ValidationStarted(title); } void ValidationProgress::Alerted(const DAVA::String& msg) { DVASSERT(consumer != nullptr); result = DAVA::Result::RESULT_ERROR; consumer->ValidationAlert(msg); } void ValidationProgress::Finished() { DVASSERT(consumer != nullptr); consumer->ValidationDone(); }
//------------------------------------------------------------------------------ /// \file ErrorHandling.cpp /// \author Ernest Yeung /// \email ernestyalumni@gmail.com /// \brief Source file for error handling C++ functors to check POSIX Linux /// system call results. /// \ref /// \details /// \copyright If you find this code useful, feel free to donate directly /// (username ernestyalumni or email address above), going directly to: /// /// paypal.me/ernestyalumni /// /// which won't go through a 3rd. party like indiegogo, kickstarter, patreon. /// Otherwise, I receive emails and messages on how all my (free) material on /// physics, math, and engineering have helped students with their studies, and /// I know what it's like to not have money as a student, but love physics (or /// math, sciences, etc.), so I am committed to keeping all my material /// open-source and free, whether or not sufficiently crowdfunded, under the /// open-source MIT license: feel free to copy, edit, paste, make your own /// versions, share, use as you wish. /// Peace out, never give up! -EY //------------------------------------------------------------------------------ /// COMPILATION TIPS: /// g++ -std=c++17 Errno.cpp ErrorHandling.cpp ErrorHandling_main.cpp -o \ /// ErrorHandling_main //------------------------------------------------------------------------------ #include "ErrorHandling.h" #include "ErrorNumber.h" // ErrorNumber #include <iostream> #include <optional> #include <string> #include <system_error> // std::system_error, std::system_category namespace Utilities { namespace ErrorHandling { HandleReturnValue::HandleReturnValue() : error_number_{} {} HandleReturnValue::HandleReturnValue(const int error_number) : error_number_{error_number} {} void HandleReturnValue::operator()( const int result, const std::string& custom_error_string) { if (result < 0) { get_error_number(); throw std::system_error( errno, std::system_category(), "Failed to " + custom_error_string + " with errno : " + error_number_.as_string() + " and error number " + std::to_string(error_number().error_number()) + '\n'); } } void HandleReturnValue::operator()(const int result) { this->operator()( result, "Integer return value to check was less than 0, and so,"); } void HandleReturnValue::get_error_number() { error_number_ = ErrorNumber{}; } HandleReturnValuePassively::HandleReturnValuePassively(): error_number_{} {} std::optional<ErrorNumber> HandleReturnValuePassively::optional()( const int return_value) { if (return_value < 0) { get_error_number(); return std::make_optional<ErrorNumber>(error_number_); } else { return std::nullopt; } } void HandleReturnValuePassively::get_error_number() { error_number_ = ErrorNumber{}; } std::optional<ErrorNumber> HandleClose::operator()(const int return_value) { if (return_value < 0) { get_error_number(); std::cerr << "Failed to close fd (::close()) with errno: " << error_number_.as_string() << " and error number " << std::to_string(error_number_.error_number()) << "\n"; return std::make_optional<ErrorNumber>(error_number_); } return std::nullopt; } void HandleRead::operator()(const ssize_t number_of_bytes) { if (number_of_bytes < 0) { get_error_number(); throw std::system_error( errno, std::system_category(), "Failed to ::read from fd with errno : " + error_number().as_string() + '\n'); } else if (number_of_bytes == 0) { std::cout << "End of file reached for fd\n"; } } } // namespace ErrorHandling } // namespace Utilities
#include <iostream> #include <string> #include "dais_exc.h" #include "tensor.h" #include "libbmp.h" #include "DAISGram.h" using namespace std; /* TEMPLATE PER SCORRERE L'ARRAY for(int i = 0; i<r; i++ ){ for (int j = 0; j<c; j++){ for (int k = 0; k<d; k++){ data[i][j][k]; } } } */ /** * Load a bitmap from file * * @param filename String containing the path of the file */ void DAISGram::load_image(string filename){ BmpImg img = BmpImg(); img.read(filename.c_str()); const int h = img.get_height(); const int w = img.get_width(); data = Tensor(h, w, 3, 0.0); for(int i=0;i<img.get_height();i++){ for(int j=0;j<img.get_width();j++){ data(i,j,0) = (float) img.red_at(j,i); data(i,j,1) = (float) img.green_at(j,i); data(i,j,2) = (float) img.blue_at(j,i); } } } /** * Save a DAISGram object to a bitmap file. * * Data is clamped to 0,255 before saving it. * * @param filename String containing the path where to store the image. */ void DAISGram::save_image(string filename){ data.clamp(0,255); BmpImg img = BmpImg(getCols(), getRows()); img.init(getCols(), getRows()); for(int i=0;i<getRows();i++){ for(int j=0;j<getCols();j++){ img.set_pixel(j,i,(unsigned char) data(i,j,0),(unsigned char) data(i,j,1),(unsigned char) data(i,j,2)); } } img.write(filename); } /** * Generate Random Image * * Generate a random image from nois * * @param h height of the image * @param w width of the image * @param d number of channels * @return returns a new DAISGram containing the generated image. */ void DAISGram::generate_random(int h, int w, int d){ data = Tensor(h,w,d,0.0); data.init_random(128,50); data.rescale(255); } DAISGram::DAISGram(){ } DAISGram::~DAISGram(){ } /** * Get rows * * @return returns the number of rows in the image */ int DAISGram::getRows(){ return data.rows(); } /** * Get columns * * @return returns the number of columns in the image */ int DAISGram::getCols(){ return data.cols(); } /** * Get depth * * @return returns the number of channels in the image */ int DAISGram::getDepth(){ return data.depth(); } /** * Brighten the image * * It sums the bright variable to all the values in the image. * * Before returning the image, the corresponding tensor should be clamped in [0,255] * * @param bright the amount of bright to add (if negative the image gets darker) * @return returns a new DAISGram containing the modified object */ DAISGram DAISGram::brighten(float bright){ DAISGram new_tensor; new_tensor.data = data; for(int i = 0; i<data.rows(); i++ ){ for (int j = 0; j<data.cols(); j++){ for (int k = 0; k<data.depth(); k++){ new_tensor.data(i,j,k)= data(i,j,k) + bright; } } } return new_tensor; } /** * Create a grayscale version of the object * * A grayscale image is produced by substituting each pixel with its average on all the channel * * @return returns a new DAISGram containing the modified object */ DAISGram DAISGram::grayscale(){ DAISGram result; result.data = data; for (int i = 0; i <data.rows(); i++){ for (int j = 0; j<data.cols(); j++){ float average; for (int k = 0; k<data.depth(); k++){ average += result.data(i,j,k); } average /= data.depth(); for (int k = 0; k<data.depth(); k++){ result.data(i,j,k) = average; } } } return result; } void DAISGram::swap(int k1, int k2){ DAISGram supp; supp.data = Tensor(data.rows(), data.cols(), 0, 0.0); for(int i = 0; i<data.rows(); i++ ){ for (int j = 0; j<data.cols(); j++){ supp.data(i,j,0)= data(i,j,k1); } } for(int i = 0; i<data.rows(); i++ ){ for (int j = 0; j<data.cols(); j++){ data(i,j,k1) = data(i,j,k2); } } for(int i = 0; i<data.rows(); i++ ){ for (int j = 0; j<data.cols(); j++){ data(i,j,k2) = supp.data(i,j,0); } } } /** * Create a Warhol effect on the image * * This function returns a composition of 4 different images in which the: * - top left is the original image * - top right is the original image in which the Red and Green channel are swapped * - bottom left is the original image in which the Blue and Green channel are swapped * - bottom right is the original image in which the Red and Blue channel are swapped * * The output image is twice the dimensions of the original one. * * @return returns a new DAISGram containing the modified object */ DAISGram DAISGram::warhol(){ DAISGram new_tensor; new_tensor.data = Tensor(data.rows()*2, data.cols()*2, data.depth()*2, 0.0); for(int i = 0; i<data.rows(); i++){ //in alto a sinistra for (int j = 0; j<data.cols(); j++){ for (int k = 0; k<data.depth(); k++){ new_tensor.data(i,j,k) = data(i,j,k); } } } swap(0,1); for(int i = 0; i<data.rows(); i++){ //in alto a destra for (int j = data.cols() ; j<data.cols()*2; j++){ for (int k = 0; k<data.depth(); k++){ new_tensor.data(i,j,k) = data(i, j - data.cols(),k); } } } swap(0,1); swap(1,2); for(int i = data.rows(); i<data.rows()*2; i++){ //in basso a sinistra for (int j = 0; j<data.cols(); j++){ for (int k = 0; k<data.depth(); k++){ new_tensor.data(i,j,k) = data( i - data.rows(), j, k); } } } swap(1,2); swap(0,2); for(int i = data.rows(); i<data.rows()*2; i++){ //in basso a destra for (int j = data.cols(); j<data.cols()*2; j++){ for (int k = 0; k<data.depth(); k++){ new_tensor.data(i,j,k) = data(i - data.rows(), j - data.cols(),k); } } } return new_tensor; } /** * Sharpen the image * * This function makes the image sharper by convolving it with a sharp filter * * filter[3][3] * 0 -1 0 * -1 5 -1 * 0 -1 0 * * Before returning the image, the corresponding tensor should be clamped in [0,255] * * @return returns a new DAISGram containing the modified object */ /* DAISGram DAISGram::sharpen(){ DAISGram new_tensor; new_tensor.data = Tensor(data.rows(), data.cols(), data.depth(), 0.0); DAISGram filter; filter.data = Tensor(3,3,1, 0.0); for(int k=0; k<data.depth(); k++){ filter.data(0,0,k) = 0.0; filter.data(0,1,k) = -1.0; filter.data(1,0,k) = -1.0; filter.data(1,1,k) = 5.0; filter.data(2,1,k) = -1.0; filter.data(1,2,k) = -1.0; filter.data(0,2,k) = 0.0; filter.data(2,0,k) = 0.0; filter.data(2,2,k) = 0.0; } new_tensor.data = data.convolve(filter.data); new_tensor.data.clamp(0,255); return new_tensor; } */ DAISGram DAISGram::sharpen(){ DAISGram new_tensor; new_tensor.data = Tensor(data.rows(), data.cols(), data.depth(), 0.0); DAISGram filter; filter.data = Tensor(3,3,data.depth(), 0.0); for(int k=0; k<data.depth(); k++){ filter.data(0,0,k) = 0; filter.data(0,1,k) = -1.0; filter.data(1,0,k) = -1.0; filter.data(1,1,k) = 5.0; filter.data(2,1,k) = -1.0; filter.data(1,2,k) = -1.0; filter.data(0,2,k) = 0.0; filter.data(2,0,k) = 0.0; filter.data(2,2,k) = 0.0; } new_tensor.data = data.convolve(filter.data); new_tensor.data.clamp(0,255); new_tensor.data.rescale(255); return new_tensor; } /** * Emboss the image * * This function makes the image embossed (a light 3D effect) by convolving it with an * embossing filter * * filter[3][3] * -2 -1 0 * -1 1 1 * 0 1 2 * * Before returning the image, the corresponding tensor should be clamped in [0,255] * * @return returns a new DAISGram containing the modified object */ DAISGram DAISGram::emboss(){ DAISGram new_tensor; new_tensor.data = Tensor(data.rows(), data.cols(), data.depth(), 0.0); DAISGram filter; filter.data = Tensor(3,3,data.depth(), 0.0); for(int k=0; k<data.depth(); k++){ filter.data(0,0,k) = -2.0; filter.data(0,1,k) = -1.0; filter.data(1,0,k) = -1.0; filter.data(1,1,k) = 1.0; filter.data(2,1,k) = 1.0; filter.data(1,2,k) = 1.0; filter.data(0,2,k) = 0.0; filter.data(2,0,k) = 0.0; filter.data(2,2,k) = 2.0; } new_tensor.data = data.convolve(filter.data); new_tensor.data.clamp(0,255); new_tensor.data.rescale(255); return new_tensor; } /** * Smooth the image * * This function remove the noise in an image using convolution and an average filter * of size h*h: * * c = 1/(h*h) * * filter[3][3] * c c c * c c c * c c c * * @param h the size of the filter * @return returns a new DAISGram containing the object */ DAISGram DAISGram::smooth(int h){ DAISGram new_tensor; new_tensor.data = data; DAISGram filter; filter.data = Tensor(3,3,data.depth(), 0.0); float c = 1.0 / (float) (h*h); for(int k=0; k<data.depth(); k++){ filter.data(0,0,k) = c; filter.data(0,1,k) = c; filter.data(1,0,k) = c; filter.data(1,1,k) = c; filter.data(2,1,k) = c; filter.data(1,2,k) = c; filter.data(0,2,k) = c; filter.data(2,0,k) = c; filter.data(2,2,k) = c; } new_tensor.data = data.convolve(filter.data); new_tensor.data.rescale(255); new_tensor.data.clamp(0,255); return new_tensor; } /** * Edges of an image * * This function extract the edges of an image by using the convolution * operator and the following filter * * * filter[3][3] * -1 -1 -1 * -1 8 -1 * -1 -1 -1 * * Remeber to convert the image to grayscale before running the convolution. * * Before returning the image, the corresponding tensor should be clamped in [0,255] * * @return returns a new DAISGram containing the modified object */ DAISGram DAISGram::edge(){ DAISGram new_tensor; new_tensor.data = Tensor(data.rows(), data.cols(), data.depth(), 0.0); DAISGram filter; filter.data = Tensor(3,3,data.depth(), 0.0); for(int k=0; k<data.depth(); k++){ filter.data(0,0,k) = -1.0; filter.data(0,1,k) = -1.0; filter.data(1,0,k) = -1.0; filter.data(1,1,k) = 8.0; filter.data(2,1,k) = -1.0; filter.data(1,2,k) = -1.0; filter.data(0,2,k) = -1.0; filter.data(2,0,k) = -1.0; filter.data(2,2,k) = -1.0; } data = grayscale().data; new_tensor.data = data.convolve(filter.data); new_tensor.data.clamp(0,255); new_tensor.data.rescale(255); return new_tensor; } /** * Blend with anoter image * * This function generate a new DAISGram which is the composition * of the object and another DAISGram object * * The composition follows this convex combination: * results = alpha*this + (1-alpha)*rhs * * rhs and this obejct MUST have the same dimensions. * * @param rhs The second image involved in the blending * @param alpha The parameter of the convex combination * @return returns a new DAISGram containing the blending of the two images. */ DAISGram DAISGram::blend(const DAISGram & rhs, float alpha){ DAISGram new_tensor; new_tensor.data = Tensor(rhs.data.rows(), rhs.data.cols(), rhs.data.depth(), 0.0); for(int i = 0; i<rhs.data.rows(); i++ ){ for (int j = 0; j<rhs.data.cols(); j++){ for (int k = 0; k<rhs.data.depth(); k++){ new_tensor.data(i,j,k) = rhs.data(i,j,k); } } } if(data.rows() == rhs.data.rows() && data.cols() == rhs.data.cols() && data.depth() == rhs.data.depth()){ for(int i = 0; i<rhs.data.rows(); i++ ){ for (int j = 0; j<rhs.data.cols(); j++){ for (int k = 0; k<rhs.data.depth(); k++){ new_tensor.data(i,j,k) = ((data(i,j,k)*alpha)+(new_tensor.data(i,j,k))*(1-alpha)); } } } } return new_tensor; } /** * Green Screen * * This function substitutes a pixel with the corresponding one in a background image * if its colors are in the surrounding (+- threshold) of a given color (rgb). * * (rgb - threshold) <= pixel <= (rgb + threshold) * * * @param bkg The second image used as background * @param rgb[] The color to substitute (rgb[0] = RED, rgb[1]=GREEN, rgb[2]=BLUE) * @param threshold[] The threshold to add/remove for each color (threshold[0] = RED, threshold[1]=GREEN, threshold[2]=BLUE) * @return returns a new DAISGram containing the result. */ DAISGram DAISGram::greenscreen(DAISGram & bkg, int rgb[], float threshold[]){ DAISGram result; result.data = data; for (int i = 0; i<result.data.rows(); i++){ for (int j = 0; j<result.data.cols(); j++){ bool in_threshold = true; for (int k = 0; k<result.data.depth(); k++){ in_threshold = result.data(i, j, k) <= rgb[k]+threshold[k] ? in_threshold : false; in_threshold = result.data(i, j, k) >= rgb[k]-threshold[k] ? in_threshold : false; } if (in_threshold){ for (int k = 0; k < result.data.depth(); k++){ result.data(i, j, k) = bkg.data(i, j, k); } } } } return result; } /** * Equalize * * Stretch the distribution of colors of the image in order to use the full range of intesities. * * See https://it.wikipedia.org/wiki/Equalizzazione_dell%27istogramma * * @return returns a new DAISGram containing the equalized image. */ DAISGram DAISGram::equalize(){ /*DAISGram result; result.data = data; for (int k= 0; k<data.depth(); k++){ int intensity[256]; for (int i = 0; i<256; i++){ intensity[i] = 0; } for (int i = 0; i<data.rows(); i++){ for (int j = 0; j<data.cols(); j++){ ++intensity[data(i, j, k)]; } } }*/ }
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:33 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: System.Enum #include "System/Enum.hpp" // Including type: UnityEngine.TextEditor #include "UnityEngine/TextEditor.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: UnityEngine namespace UnityEngine { // Autogenerated type: UnityEngine.TextEditor/Direction struct TextEditor::Direction : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public UnityEngine.TextEditor/Direction Forward static constexpr const int Forward = 0; // Get static field: static public UnityEngine.TextEditor/Direction Forward static UnityEngine::TextEditor::Direction _get_Forward(); // Set static field: static public UnityEngine.TextEditor/Direction Forward static void _set_Forward(UnityEngine::TextEditor::Direction value); // static field const value: static public UnityEngine.TextEditor/Direction Backward static constexpr const int Backward = 1; // Get static field: static public UnityEngine.TextEditor/Direction Backward static UnityEngine::TextEditor::Direction _get_Backward(); // Set static field: static public UnityEngine.TextEditor/Direction Backward static void _set_Backward(UnityEngine::TextEditor::Direction value); // Creating value type constructor for type: Direction Direction(int value_ = {}) : value{value_} {} }; // UnityEngine.TextEditor/Direction } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TextEditor::Direction, "UnityEngine", "TextEditor/Direction"); #pragma pack(pop)
//////////////////////////////////////////////////////////////////////////////// // Filename: graphicsclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "graphicsclass.h" GraphicsClass::GraphicsClass() { m_D3D = 0; m_Camera = 0; m_TextureShader = 0; m_Bitmap = 0; m_RenderTexture = 0; m_DownSampleTexure = 0; m_SmallWindow = 0; m_HorizontalBlurTexture = 0; m_HorizontalBlurShader = 0; m_VerticalBlurTexture = 0; m_VerticalBlurShader = 0; m_UpSampleTexure = 0; m_FullScreenWindow = 0; m_GlowMapShader = 0; m_GlowShader = 0; } GraphicsClass::GraphicsClass(const GraphicsClass& other) { } GraphicsClass::~GraphicsClass() { } bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd) { bool result; // Create the Direct3D object. m_D3D = new D3DClass; if(!m_D3D) { return false; } // Initialize the Direct3D object. result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR); if(!result) { MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK); return false; } // Create the camera object. m_Camera = new CameraClass; if(!m_Camera) { return false; } // Set the initial position of the camera. m_Camera->SetPosition(0.0f, 0.0f, -10.0f); // Create the texture shader object. m_TextureShader = new TextureShaderClass; if(!m_TextureShader) { return false; } // Initialize the texture shader object. result = m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the texture shader object.", L"Error", MB_OK); return false; } // Create the bitmap object. m_Bitmap = new BitmapClass; if(!m_Bitmap) { return false; } // Initialize the bitmap object. result = m_Bitmap->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, L"../Engine/data/test.dds", L"../Engine/data/glowmap.dds", 256, 32); if(!result) { MessageBox(hwnd, L"Could not initialize the bitmap object.", L"Error", MB_OK); return false; } // Create the render to texture object. m_RenderTexture = new RenderTextureClass; if(!m_RenderTexture) { return false; } // Initialize the render to texture object. result = m_RenderTexture->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, SCREEN_DEPTH, SCREEN_NEAR); if(!result) { MessageBox(hwnd, L"Could not initialize the render to texture object.", L"Error", MB_OK); return false; } // Create the down sample render to texture object. m_DownSampleTexure = new RenderTextureClass; if(!m_DownSampleTexure) { return false; } // Initialize the down sample render to texture object. result = m_DownSampleTexure->Initialize(m_D3D->GetDevice(), (screenWidth / 2), (screenHeight / 2), SCREEN_DEPTH, SCREEN_NEAR); if(!result) { MessageBox(hwnd, L"Could not initialize the down sample render to texture object.", L"Error", MB_OK); return false; } // Create the small ortho window object. m_SmallWindow = new OrthoWindowClass; if(!m_SmallWindow) { return false; } // Initialize the small ortho window object. result = m_SmallWindow->Initialize(m_D3D->GetDevice(), (screenWidth / 2), (screenHeight / 2)); if(!result) { MessageBox(hwnd, L"Could not initialize the small ortho window object.", L"Error", MB_OK); return false; } // Create the horizontal blur render to texture object. m_HorizontalBlurTexture = new RenderTextureClass; if(!m_HorizontalBlurTexture) { return false; } // Initialize the horizontal blur render to texture object. result = m_HorizontalBlurTexture->Initialize(m_D3D->GetDevice(), (screenWidth / 2), (screenHeight / 2), SCREEN_DEPTH, SCREEN_NEAR); if(!result) { MessageBox(hwnd, L"Could not initialize the horizontal blur render to texture object.", L"Error", MB_OK); return false; } // Create the horizontal blur shader object. m_HorizontalBlurShader = new HorizontalBlurShaderClass; if(!m_HorizontalBlurShader) { return false; } // Initialize the horizontal blur shader object. result = m_HorizontalBlurShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the horizontal blur shader object.", L"Error", MB_OK); return false; } // Create the vertical blur render to texture object. m_VerticalBlurTexture = new RenderTextureClass; if(!m_VerticalBlurTexture) { return false; } // Initialize the vertical blur render to texture object. result = m_VerticalBlurTexture->Initialize(m_D3D->GetDevice(), (screenWidth / 2), (screenHeight / 2), SCREEN_DEPTH, SCREEN_NEAR); if(!result) { MessageBox(hwnd, L"Could not initialize the vertical blur render to texture object.", L"Error", MB_OK); return false; } // Create the vertical blur shader object. m_VerticalBlurShader = new VerticalBlurShaderClass; if(!m_VerticalBlurShader) { return false; } // Initialize the vertical blur shader object. result = m_VerticalBlurShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the vertical blur shader object.", L"Error", MB_OK); return false; } // Create the up sample render to texture object. m_UpSampleTexure = new RenderTextureClass; if(!m_UpSampleTexure) { return false; } // Initialize the up sample render to texture object. result = m_UpSampleTexure->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, SCREEN_DEPTH, SCREEN_NEAR); if(!result) { MessageBox(hwnd, L"Could not initialize the up sample render to texture object.", L"Error", MB_OK); return false; } // Create the full screen ortho window object. m_FullScreenWindow = new OrthoWindowClass; if(!m_FullScreenWindow) { return false; } // Initialize the full screen ortho window object. result = m_FullScreenWindow->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight); if(!result) { MessageBox(hwnd, L"Could not initialize the full screen ortho window object.", L"Error", MB_OK); return false; } // Create the glow map shader object. m_GlowMapShader = new GlowMapShaderClass; if(!m_GlowMapShader) { return false; } // Initialize the glow map shader object. result = m_GlowMapShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the glow map shader object.", L"Error", MB_OK); return false; } // Create the glow shader object. m_GlowShader = new GlowShaderClass; if(!m_GlowShader) { return false; } // Initialize the glow shader object. result = m_GlowShader->Initialize(m_D3D->GetDevice(), hwnd); if(!result) { MessageBox(hwnd, L"Could not initialize the glow shader object.", L"Error", MB_OK); return false; } return true; } void GraphicsClass::Shutdown() { // Release the glow shader object. if(m_GlowShader) { m_GlowShader->Shutdown(); delete m_GlowShader; m_GlowShader = 0; } // Release the glow map shader object. if(m_GlowMapShader) { m_GlowMapShader->Shutdown(); delete m_GlowMapShader; m_GlowMapShader = 0; } // Release the full screen ortho window object. if(m_FullScreenWindow) { m_FullScreenWindow->Shutdown(); delete m_FullScreenWindow; m_FullScreenWindow = 0; } // Release the up sample render to texture object. if(m_UpSampleTexure) { m_UpSampleTexure->Shutdown(); delete m_UpSampleTexure; m_UpSampleTexure = 0; } // Release the vertical blur shader object. if(m_VerticalBlurShader) { m_VerticalBlurShader->Shutdown(); delete m_VerticalBlurShader; m_VerticalBlurShader = 0; } // Release the vertical blur render to texture object. if(m_VerticalBlurTexture) { m_VerticalBlurTexture->Shutdown(); delete m_VerticalBlurTexture; m_VerticalBlurTexture = 0; } // Release the horizontal blur shader object. if(m_HorizontalBlurShader) { m_HorizontalBlurShader->Shutdown(); delete m_HorizontalBlurShader; m_HorizontalBlurShader = 0; } // Release the horizontal blur render to texture object. if(m_HorizontalBlurTexture) { m_HorizontalBlurTexture->Shutdown(); delete m_HorizontalBlurTexture; m_HorizontalBlurTexture = 0; } // Release the small ortho window object. if(m_SmallWindow) { m_SmallWindow->Shutdown(); delete m_SmallWindow; m_SmallWindow = 0; } // Release the down sample render to texture object. if(m_DownSampleTexure) { m_DownSampleTexure->Shutdown(); delete m_DownSampleTexure; m_DownSampleTexure = 0; } // Release the render to texture object. if(m_RenderTexture) { m_RenderTexture->Shutdown(); delete m_RenderTexture; m_RenderTexture = 0; } // Release the bitmap object. if(m_Bitmap) { m_Bitmap->Shutdown(); delete m_Bitmap; m_Bitmap = 0; } // Release the texture shader object. if(m_TextureShader) { m_TextureShader->Shutdown(); delete m_TextureShader; m_TextureShader = 0; } // Release the camera object. if(m_Camera) { delete m_Camera; m_Camera = 0; } // Release the D3D object. if(m_D3D) { m_D3D->Shutdown(); delete m_D3D; m_D3D = 0; } return; } bool GraphicsClass::Frame() { bool result; // Render the graphics scene. result = Render(); if(!result) { return false; } return true; } bool GraphicsClass::Render() { bool result; // First render the glow maps to a render texture. result = RenderGlowMapToTexture(); if(!result) { return false; } // Next down sample the render texture to a smaller sized texture. result = DownSampleTexture(); if(!result) { return false; } // Perform a horizontal blur on the down sampled render texture. result = RenderHorizontalBlurToTexture(); if(!result) { return false; } // Now perform a vertical blur on the horizontal blur render texture. result = RenderVerticalBlurToTexture(); if(!result) { return false; } // Up sample the final blurred render texture to screen size again. result = UpSampleTexture(); if(!result) { return false; } // Render the regular UI elements to a full screen texture. result = RenderUIElementsToTexture(); if(!result) { return false; } // Render the final scene combining the UI elements with the glowing UI elements. RenderGlowScene(); return true; } bool GraphicsClass::RenderGlowMapToTexture() { D3DXMATRIX worldMatrix, viewMatrix, orthoMatrix; bool result; // Set the render target to be the render to texture. m_RenderTexture->SetRenderTarget(m_D3D->GetDeviceContext()); // Clear the render to texture. m_RenderTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world, view, and projection matrices from the camera and d3d objects. m_D3D->GetWorldMatrix(worldMatrix); m_Camera->GetViewMatrix(viewMatrix); m_D3D->GetOrthoMatrix(orthoMatrix); // Turn off the Z buffer to begin all 2D rendering. m_D3D->TurnZBufferOff(); // Put the bitmap vertex and index buffers on the graphics pipeline to prepare them for drawing. result = m_Bitmap->Render(m_D3D->GetDeviceContext(), 100, 100); if(!result) { return false; } // Render the bitmap using the glow map shader. m_GlowMapShader->Render(m_D3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_Bitmap->GetTexture(), m_Bitmap->GetGlowMap()); // Turn the Z buffer back on now that all 2D rendering has completed. m_D3D->TurnZBufferOn(); // Reset the render target back to the original back buffer and not the render to texture anymore. m_D3D->SetBackBufferRenderTarget(); // Reset the viewport back to the original. m_D3D->ResetViewport(); return true; } bool GraphicsClass::DownSampleTexture() { D3DXMATRIX worldMatrix, viewMatrix, orthoMatrix; bool result; // Set the render target to be the render to texture. m_DownSampleTexure->SetRenderTarget(m_D3D->GetDeviceContext()); // Clear the render to texture. m_DownSampleTexure->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 1.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world and view matrices from the camera and d3d objects. m_D3D->GetWorldMatrix(worldMatrix); m_Camera->GetViewMatrix(viewMatrix); // Get the ortho matrix from the render to texture since texture has different dimensions being that it is smaller. m_DownSampleTexure->GetOrthoMatrix(orthoMatrix); // Turn off the Z buffer to begin all 2D rendering. m_D3D->TurnZBufferOff(); // Put the small ortho window vertex and index buffers on the graphics pipeline to prepare them for drawing. m_SmallWindow->Render(m_D3D->GetDeviceContext()); // Render the small ortho window using the texture shader and the render to texture of the scene as the texture resource. result = m_TextureShader->Render(m_D3D->GetDeviceContext(), m_SmallWindow->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_RenderTexture->GetShaderResourceView()); if(!result) { return false; } // Turn the Z buffer back on now that all 2D rendering has completed. m_D3D->TurnZBufferOn(); // Reset the render target back to the original back buffer and not the render to texture anymore. m_D3D->SetBackBufferRenderTarget(); // Reset the viewport back to the original. m_D3D->ResetViewport(); return true; } bool GraphicsClass::RenderHorizontalBlurToTexture() { D3DXMATRIX worldMatrix, viewMatrix, orthoMatrix; float screenSizeX; bool result; // Set the render target to be the render to texture. m_HorizontalBlurTexture->SetRenderTarget(m_D3D->GetDeviceContext()); // Clear the render to texture. m_HorizontalBlurTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world and view matrices from the camera and d3d objects. m_Camera->GetViewMatrix(viewMatrix); m_D3D->GetWorldMatrix(worldMatrix); // Get the ortho matrix from the render to texture since texture has different dimensions. m_HorizontalBlurTexture->GetOrthoMatrix(orthoMatrix); // Turn off the Z buffer to begin all 2D rendering. m_D3D->TurnZBufferOff(); // Store the screen width in a float that will be used in the horizontal blur shader. screenSizeX = (float)m_HorizontalBlurTexture->GetTextureWidth(); // Put the small ortho window vertex and index buffers on the graphics pipeline to prepare them for drawing. m_SmallWindow->Render(m_D3D->GetDeviceContext()); // Render the small ortho window using the horizontal blur shader and the down sampled render to texture resource. result = m_HorizontalBlurShader->Render(m_D3D->GetDeviceContext(), m_SmallWindow->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_DownSampleTexure->GetShaderResourceView(), screenSizeX); if(!result) { return false; } // Turn the Z buffer back on now that all 2D rendering has completed. m_D3D->TurnZBufferOn(); // Reset the render target back to the original back buffer and not the render to texture anymore. m_D3D->SetBackBufferRenderTarget(); // Reset the viewport back to the original. m_D3D->ResetViewport(); return true; } bool GraphicsClass::RenderVerticalBlurToTexture() { D3DXMATRIX worldMatrix, viewMatrix, orthoMatrix; float screenSizeY; bool result; // Set the render target to be the render to texture. m_VerticalBlurTexture->SetRenderTarget(m_D3D->GetDeviceContext()); // Clear the render to texture. m_VerticalBlurTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world and view matrices from the camera and d3d objects. m_Camera->GetViewMatrix(viewMatrix); m_D3D->GetWorldMatrix(worldMatrix); // Get the ortho matrix from the render to texture since texture has different dimensions. m_VerticalBlurTexture->GetOrthoMatrix(orthoMatrix); // Turn off the Z buffer to begin all 2D rendering. m_D3D->TurnZBufferOff(); // Store the screen height in a float that will be used in the vertical blur shader. screenSizeY = (float)m_VerticalBlurTexture->GetTextureHeight(); // Put the small ortho window vertex and index buffers on the graphics pipeline to prepare them for drawing. m_SmallWindow->Render(m_D3D->GetDeviceContext()); // Render the small ortho window using the vertical blur shader and the horizontal blurred render to texture resource. result = m_VerticalBlurShader->Render(m_D3D->GetDeviceContext(), m_SmallWindow->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_HorizontalBlurTexture->GetShaderResourceView(), screenSizeY); if(!result) { return false; } // Turn the Z buffer back on now that all 2D rendering has completed. m_D3D->TurnZBufferOn(); // Reset the render target back to the original back buffer and not the render to texture anymore. m_D3D->SetBackBufferRenderTarget(); // Reset the viewport back to the original. m_D3D->ResetViewport(); return true; } bool GraphicsClass::UpSampleTexture() { D3DXMATRIX worldMatrix, viewMatrix, orthoMatrix; bool result; // Set the render target to be the render to texture. m_UpSampleTexure->SetRenderTarget(m_D3D->GetDeviceContext()); // Clear the render to texture. m_UpSampleTexure->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world and view matrices from the camera and d3d objects. m_D3D->GetWorldMatrix(worldMatrix); m_Camera->GetViewMatrix(viewMatrix); // Get the ortho matrix from the render to texture since texture has different dimensions. m_UpSampleTexure->GetOrthoMatrix(orthoMatrix); // Turn off the Z buffer to begin all 2D rendering. m_D3D->TurnZBufferOff(); // Put the full screen ortho window vertex and index buffers on the graphics pipeline to prepare them for drawing. m_FullScreenWindow->Render(m_D3D->GetDeviceContext()); // Render the full screen ortho window using the texture shader and the small sized final blurred render to texture resource. result = m_TextureShader->Render(m_D3D->GetDeviceContext(), m_FullScreenWindow->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_VerticalBlurTexture->GetShaderResourceView()); if(!result) { return false; } // Turn the Z buffer back on now that all 2D rendering has completed. m_D3D->TurnZBufferOn(); // Reset the render target back to the original back buffer and not the render to texture anymore. m_D3D->SetBackBufferRenderTarget(); // Reset the viewport back to the original. m_D3D->ResetViewport(); return true; } bool GraphicsClass::RenderUIElementsToTexture() { D3DXMATRIX worldMatrix, viewMatrix, orthoMatrix; bool result; // Set the render target to be the render to texture. m_RenderTexture->SetRenderTarget(m_D3D->GetDeviceContext()); // Clear the render to texture. m_RenderTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world, view, and ortho matrices from the camera and d3d objects. m_D3D->GetWorldMatrix(worldMatrix); m_Camera->GetViewMatrix(viewMatrix); m_D3D->GetOrthoMatrix(orthoMatrix); // Turn off the Z buffer to begin all 2D rendering. m_D3D->TurnZBufferOff(); // Put the bitmap vertex and index buffers on the graphics pipeline to prepare them for drawing. result = m_Bitmap->Render(m_D3D->GetDeviceContext(), 100, 100); if(!result) { return false; } // Render the bitmap using the texture shader. result = m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_Bitmap->GetTexture()); if(!result) { return false; } // Turn the Z buffer back on now that all 2D rendering has completed. m_D3D->TurnZBufferOn(); // Reset the render target back to the original back buffer and not the render to texture anymore. m_D3D->SetBackBufferRenderTarget(); // Reset the viewport back to the original. m_D3D->ResetViewport(); return true; } bool GraphicsClass::RenderGlowScene() { D3DXMATRIX worldMatrix, viewMatrix, orthoMatrix; // Clear the buffers to begin the scene. m_D3D->BeginScene(1.0f, 0.0f, 0.0f, 0.0f); // Generate the view matrix based on the camera's position. m_Camera->Render(); // Get the world, view, and ortho matrices from the camera and d3d objects. m_Camera->GetViewMatrix(viewMatrix); m_D3D->GetWorldMatrix(worldMatrix); m_D3D->GetOrthoMatrix(orthoMatrix); // Turn off the Z buffer to begin all 2D rendering. m_D3D->TurnZBufferOff(); // Put the full screen ortho window vertex and index buffers on the graphics pipeline to prepare them for drawing. m_FullScreenWindow->Render(m_D3D->GetDeviceContext()); // Render the full screen ortho window using the texture shader and the full screen sized blurred render to texture resource. m_GlowShader->Render(m_D3D->GetDeviceContext(), m_FullScreenWindow->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix, m_RenderTexture->GetShaderResourceView(), m_UpSampleTexure->GetShaderResourceView(), 3.0f); // Turn the Z buffer back on now that all 2D rendering has completed. m_D3D->TurnZBufferOn(); // Present the rendered scene to the screen. m_D3D->EndScene(); return true; }
/* * Implementation file for the rigid body class. * * Part of the Cyclone physics system. * * Copyright (c) Icosagon 2003. All Rights Reserved. * * This software is distributed under licence. Use of this software * implies agreement with all terms and conditions of the accompanying * software licence. */ #include <cyclone/body.h> #include <memory.h> #include <assert.h> using namespace cyclone; /* * -------------------------------------------------------------------------- * INTERNAL OR HELPER FUNCTIONS: * -------------------------------------------------------------------------- */ /** * Internal function that checks the validity of an inverse inertia tensor. */ static inline void _checkInverseInertiaTensor(const Matrix3 &iitWorld) { // TODO: Perform a validity check in an assert. } /** * Internal function to do an intertia tensor transform by a quaternion. * Note that the implementation of this function was created by an * automated code-generator and optimizer. */ static inline void _transformInertiaTensor(Matrix3 &iitWorld, const Quaternion &q, const Matrix3 &iitBody, const Matrix4 &rotmat) { real t4 = rotmat.data[0]*iitBody.data[0]+ rotmat.data[1]*iitBody.data[3]+ rotmat.data[2]*iitBody.data[6]; real t9 = rotmat.data[0]*iitBody.data[1]+ rotmat.data[1]*iitBody.data[4]+ rotmat.data[2]*iitBody.data[7]; real t14 = rotmat.data[0]*iitBody.data[2]+ rotmat.data[1]*iitBody.data[5]+ rotmat.data[2]*iitBody.data[8]; real t28 = rotmat.data[4]*iitBody.data[0]+ rotmat.data[5]*iitBody.data[3]+ rotmat.data[6]*iitBody.data[6]; real t33 = rotmat.data[4]*iitBody.data[1]+ rotmat.data[5]*iitBody.data[4]+ rotmat.data[6]*iitBody.data[7]; real t38 = rotmat.data[4]*iitBody.data[2]+ rotmat.data[5]*iitBody.data[5]+ rotmat.data[6]*iitBody.data[8]; real t52 = rotmat.data[8]*iitBody.data[0]+ rotmat.data[9]*iitBody.data[3]+ rotmat.data[10]*iitBody.data[6]; real t57 = rotmat.data[8]*iitBody.data[1]+ rotmat.data[9]*iitBody.data[4]+ rotmat.data[10]*iitBody.data[7]; real t62 = rotmat.data[8]*iitBody.data[2]+ rotmat.data[9]*iitBody.data[5]+ rotmat.data[10]*iitBody.data[8]; iitWorld.data[0] = t4*rotmat.data[0]+ t9*rotmat.data[1]+ t14*rotmat.data[2]; iitWorld.data[1] = t4*rotmat.data[4]+ t9*rotmat.data[5]+ t14*rotmat.data[6]; iitWorld.data[2] = t4*rotmat.data[8]+ t9*rotmat.data[9]+ t14*rotmat.data[10]; iitWorld.data[3] = t28*rotmat.data[0]+ t33*rotmat.data[1]+ t38*rotmat.data[2]; iitWorld.data[4] = t28*rotmat.data[4]+ t33*rotmat.data[5]+ t38*rotmat.data[6]; iitWorld.data[5] = t28*rotmat.data[8]+ t33*rotmat.data[9]+ t38*rotmat.data[10]; iitWorld.data[6] = t52*rotmat.data[0]+ t57*rotmat.data[1]+ t62*rotmat.data[2]; iitWorld.data[7] = t52*rotmat.data[4]+ t57*rotmat.data[5]+ t62*rotmat.data[6]; iitWorld.data[8] = t52*rotmat.data[8]+ t57*rotmat.data[9]+ t62*rotmat.data[10]; } /** * Inline function that creates a transform matrix from a * position and orientation. */ static inline void _calculateTransformMatrix(Matrix4 &transformMatrix, const Vector3 &position, const Quaternion &orientation) { transformMatrix.data[0] = 1-2*orientation.j*orientation.j- 2*orientation.k*orientation.k; transformMatrix.data[1] = 2*orientation.i*orientation.j - 2*orientation.r*orientation.k; transformMatrix.data[2] = 2*orientation.i*orientation.k + 2*orientation.r*orientation.j; transformMatrix.data[3] = position.x; transformMatrix.data[4] = 2*orientation.i*orientation.j + 2*orientation.r*orientation.k; transformMatrix.data[5] = 1-2*orientation.i*orientation.i- 2*orientation.k*orientation.k; transformMatrix.data[6] = 2*orientation.j*orientation.k - 2*orientation.r*orientation.i; transformMatrix.data[7] = position.y; transformMatrix.data[8] = 2*orientation.i*orientation.k - 2*orientation.r*orientation.j; transformMatrix.data[9] = 2*orientation.j*orientation.k + 2*orientation.r*orientation.i; transformMatrix.data[10] = 1-2*orientation.i*orientation.i- 2*orientation.j*orientation.j; transformMatrix.data[11] = position.z; } /* * -------------------------------------------------------------------------- * FUNCTIONS DECLARED IN HEADER: * -------------------------------------------------------------------------- */ void RigidBody::calculateDerivedData() { orientation.normalise(); // Calculate the transform matrix for the body. _calculateTransformMatrix(transformMatrix, position, orientation); // Calculate the inertiaTensor in world space. _transformInertiaTensor(inverseInertiaTensorWorld, orientation, inverseInertiaTensor, transformMatrix); } void RigidBody::integrate(real duration) { if (!isAwake) return; // Calculate linear acceleration from force inputs. lastFrameAcceleration = acceleration; lastFrameAcceleration.addScaledVector(forceAccum, inverseMass); // Calculate angular acceleration from torque inputs. Vector3 angularAcceleration = inverseInertiaTensorWorld.transform(torqueAccum); // Adjust velocities // Update linear velocity from both acceleration and impulse. velocity.addScaledVector(lastFrameAcceleration, duration); // Update angular velocity from both acceleration and impulse. rotation.addScaledVector(angularAcceleration, duration); // Impose drag. velocity *= real_pow(linearDamping, duration); rotation *= real_pow(angularDamping, duration); // Adjust positions // Update linear position. position.addScaledVector(velocity, duration); // Update angular position. orientation.addScaledVector(rotation, duration); // Normalise the orientation, and update the matrices with the new // position and orientation calculateDerivedData(); // Clear accumulators. clearAccumulators(); // Update the kinetic energy store, and possibly put the body to // sleep. if (canSleep) { real currentMotion = velocity.scalarProduct(velocity) + rotation.scalarProduct(rotation); real bias = real_pow(0.5, duration); motion = bias*motion + (1-bias)*currentMotion; if (motion < sleepEpsilon) setAwake(false); else if (motion > 10 * sleepEpsilon) motion = 10 * sleepEpsilon; } } void RigidBody::setMass(const real mass) { assert(mass != 0); RigidBody::inverseMass = ((real)1.0)/mass; } real RigidBody::getMass() const { if (inverseMass == 0) { return REAL_MAX; } else { return ((real)1.0)/inverseMass; } } void RigidBody::setInverseMass(const real inverseMass) { RigidBody::inverseMass = inverseMass; } real RigidBody::getInverseMass() const { return inverseMass; } bool RigidBody::hasFiniteMass() const { return inverseMass >= 0.0f; } void RigidBody::setInertiaTensor(const Matrix3 &inertiaTensor) { inverseInertiaTensor.setInverse(inertiaTensor); _checkInverseInertiaTensor(inverseInertiaTensor); } void RigidBody::getInertiaTensor(Matrix3 *inertiaTensor) const { inertiaTensor->setInverse(inverseInertiaTensor); } Matrix3 RigidBody::getInertiaTensor() const { Matrix3 it; getInertiaTensor(&it); return it; } void RigidBody::getInertiaTensorWorld(Matrix3 *inertiaTensor) const { inertiaTensor->setInverse(inverseInertiaTensorWorld); } Matrix3 RigidBody::getInertiaTensorWorld() const { Matrix3 it; getInertiaTensorWorld(&it); return it; } void RigidBody::setInverseInertiaTensor(const Matrix3 &inverseInertiaTensor) { _checkInverseInertiaTensor(inverseInertiaTensor); RigidBody::inverseInertiaTensor = inverseInertiaTensor; } void RigidBody::getInverseInertiaTensor(Matrix3 *inverseInertiaTensor) const { *inverseInertiaTensor = RigidBody::inverseInertiaTensor; } Matrix3 RigidBody::getInverseInertiaTensor() const { return inverseInertiaTensor; } void RigidBody::getInverseInertiaTensorWorld(Matrix3 *inverseInertiaTensor) const { *inverseInertiaTensor = inverseInertiaTensorWorld; } Matrix3 RigidBody::getInverseInertiaTensorWorld() const { return inverseInertiaTensorWorld; } void RigidBody::setDamping(const real linearDamping, const real angularDamping) { RigidBody::linearDamping = linearDamping; RigidBody::angularDamping = angularDamping; } void RigidBody::setLinearDamping(const real linearDamping) { RigidBody::linearDamping = linearDamping; } real RigidBody::getLinearDamping() const { return linearDamping; } void RigidBody::setAngularDamping(const real angularDamping) { RigidBody::angularDamping = angularDamping; } real RigidBody::getAngularDamping() const { return angularDamping; } void RigidBody::setPosition(const Vector3 &position) { RigidBody::position = position; } void RigidBody::setPosition(const real x, const real y, const real z) { position.x = x; position.y = y; position.z = z; } void RigidBody::getPosition(Vector3 *position) const { *position = RigidBody::position; } Vector3 RigidBody::getPosition() const { return position; } void RigidBody::setOrientation(const Quaternion &orientation) { RigidBody::orientation = orientation; RigidBody::orientation.normalise(); } void RigidBody::setOrientation(const real r, const real i, const real j, const real k) { orientation.r = r; orientation.i = i; orientation.j = j; orientation.k = k; orientation.normalise(); } void RigidBody::getOrientation(Quaternion *orientation) const { *orientation = RigidBody::orientation; } Quaternion RigidBody::getOrientation() const { return orientation; } void RigidBody::getOrientation(Matrix3 *matrix) const { getOrientation(matrix->data); } void RigidBody::getOrientation(real matrix[9]) const { matrix[0] = transformMatrix.data[0]; matrix[1] = transformMatrix.data[1]; matrix[2] = transformMatrix.data[2]; matrix[3] = transformMatrix.data[4]; matrix[4] = transformMatrix.data[5]; matrix[5] = transformMatrix.data[6]; matrix[6] = transformMatrix.data[8]; matrix[7] = transformMatrix.data[9]; matrix[8] = transformMatrix.data[10]; } void RigidBody::getTransform(Matrix4 *transform) const { memcpy(transform, &transformMatrix.data, sizeof(Matrix4)); } void RigidBody::getTransform(real matrix[16]) const { memcpy(matrix, transformMatrix.data, sizeof(real)*12); matrix[12] = matrix[13] = matrix[14] = 0; matrix[15] = 1; } void RigidBody::getGLTransform(float matrix[16]) const { matrix[0] = (float)transformMatrix.data[0]; matrix[1] = (float)transformMatrix.data[4]; matrix[2] = (float)transformMatrix.data[8]; matrix[3] = 0; matrix[4] = (float)transformMatrix.data[1]; matrix[5] = (float)transformMatrix.data[5]; matrix[6] = (float)transformMatrix.data[9]; matrix[7] = 0; matrix[8] = (float)transformMatrix.data[2]; matrix[9] = (float)transformMatrix.data[6]; matrix[10] = (float)transformMatrix.data[10]; matrix[11] = 0; matrix[12] = (float)transformMatrix.data[3]; matrix[13] = (float)transformMatrix.data[7]; matrix[14] = (float)transformMatrix.data[11]; matrix[15] = 1; } Matrix4 RigidBody::getTransform() const { return transformMatrix; } Vector3 RigidBody::getPointInLocalSpace(const Vector3 &point) const { return transformMatrix.transformInverse(point); } Vector3 RigidBody::getPointInWorldSpace(const Vector3 &point) const { return transformMatrix.transform(point); } Vector3 RigidBody::getDirectionInLocalSpace(const Vector3 &direction) const { return transformMatrix.transformInverseDirection(direction); } Vector3 RigidBody::getDirectionInWorldSpace(const Vector3 &direction) const { return transformMatrix.transformDirection(direction); } void RigidBody::setVelocity(const Vector3 &velocity) { RigidBody::velocity = velocity; } void RigidBody::setVelocity(const real x, const real y, const real z) { velocity.x = x; velocity.y = y; velocity.z = z; } void RigidBody::getVelocity(Vector3 *velocity) const { *velocity = RigidBody::velocity; } Vector3 RigidBody::getVelocity() const { return velocity; } void RigidBody::addVelocity(const Vector3 &deltaVelocity) { velocity += deltaVelocity; } void RigidBody::setRotation(const Vector3 &rotation) { RigidBody::rotation = rotation; } void RigidBody::setRotation(const real x, const real y, const real z) { rotation.x = x; rotation.y = y; rotation.z = z; } void RigidBody::getRotation(Vector3 *rotation) const { *rotation = RigidBody::rotation; } Vector3 RigidBody::getRotation() const { return rotation; } void RigidBody::addRotation(const Vector3 &deltaRotation) { rotation += deltaRotation; } void RigidBody::setAwake(const bool awake) { if (awake) { isAwake= true; // Add a bit of motion to avoid it falling asleep immediately. motion = sleepEpsilon*2.0f; } else { isAwake = false; velocity.clear(); rotation.clear(); } } void RigidBody::setCanSleep(const bool canSleep) { RigidBody::canSleep = canSleep; if (!canSleep && !isAwake) setAwake(); } void RigidBody::getLastFrameAcceleration(Vector3 *acceleration) const { *acceleration = lastFrameAcceleration; } Vector3 RigidBody::getLastFrameAcceleration() const { return lastFrameAcceleration; } void RigidBody::clearAccumulators() { forceAccum.clear(); torqueAccum.clear(); } void RigidBody::addForce(const Vector3 &force) { forceAccum += force; isAwake = true; } void RigidBody::addForceAtBodyPoint(const Vector3 &force, const Vector3 &point) { // Convert to coordinates relative to center of mass. Vector3 pt = getPointInWorldSpace(point); addForceAtPoint(force, pt); } void RigidBody::addForceAtPoint(const Vector3 &force, const Vector3 &point) { // Convert to coordinates relative to center of mass. Vector3 pt = point; pt -= position; forceAccum += force; torqueAccum += pt % force; isAwake = true; } void RigidBody::addTorque(const Vector3 &torque) { torqueAccum += torque; isAwake = true; } void RigidBody::setAcceleration(const Vector3 &acceleration) { RigidBody::acceleration = acceleration; } void RigidBody::setAcceleration(const real x, const real y, const real z) { acceleration.x = x; acceleration.y = y; acceleration.z = z; } void RigidBody::getAcceleration(Vector3 *acceleration) const { *acceleration = RigidBody::acceleration; } Vector3 RigidBody::getAcceleration() const { return acceleration; }
BEGIN_MESSAGE_MAP(CMyView, CFormView) ON_WM_MOUSEACTIVATE() ON_COMMAND(ID_EDIT_CUT, &CMyView::OnEditCut) ON_UPDATE_COMMAND_UI(ID_EDIT_CUT, &CMyView::OnUpdateEditCut) ON_BN_CLICKED(IDC_MYBUTTON, &CMyView::OnBnClickedMybutton) ON_WM_CREATE() END_MESSAGE_MAP()
//===-- PPCMachObjectWriter.cpp - PPC Mach-O Writer -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCTargetDesc/PPCFixupKinds.h" #include "MCTargetDesc/PPCMCTargetDesc.h" #include "llvm/ADT/Twine.h" #include "llvm/BinaryFormat/MachO.h" #include "llvm/MC/MCAsmLayout.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCMachObjectWriter.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/MC/MCValue.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" using namespace llvm; namespace { class PPCMachObjectWriter : public MCMachObjectTargetWriter { bool recordScatteredRelocation(MachObjectWriter *Writer, const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, unsigned Log2Size, uint64_t &FixedValue); void RecordPPCRelocation(MachObjectWriter *Writer, const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue); public: PPCMachObjectWriter(bool Is64Bit, uint32_t CPUType, uint32_t CPUSubtype) : MCMachObjectTargetWriter(Is64Bit, CPUType, CPUSubtype) {} void recordRelocation(MachObjectWriter *Writer, MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) override { if (Writer->is64Bit()) { report_fatal_error("Relocation emission for MachO/PPC64 unimplemented."); } else RecordPPCRelocation(Writer, Asm, Layout, Fragment, Fixup, Target, FixedValue); } }; } /// computes the log2 of the size of the relocation, /// used for relocation_info::r_length. static unsigned getFixupKindLog2Size(unsigned Kind) { switch (Kind) { default: report_fatal_error("log2size(FixupKind): Unhandled fixup kind!"); case FK_PCRel_1: case FK_Data_1: return 0; case FK_PCRel_2: case FK_Data_2: return 1; case FK_PCRel_4: case PPC::fixup_ppc_brcond14: case PPC::fixup_ppc_half16: case PPC::fixup_ppc_br24: case FK_Data_4: return 2; case FK_PCRel_8: case FK_Data_8: return 3; } return 0; } /// Translates generic PPC fixup kind to Mach-O/PPC relocation type enum. /// Outline based on PPCELFObjectWriter::getRelocType(). static unsigned getRelocType(const MCValue &Target, const MCFixupKind FixupKind, // from // Fixup.getKind() const bool IsPCRel) { const MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ? MCSymbolRefExpr::VK_None : Target.getSymA()->getKind(); // determine the type of the relocation unsigned Type = MachO::GENERIC_RELOC_VANILLA; if (IsPCRel) { // relative to PC switch ((unsigned)FixupKind) { default: report_fatal_error("Unimplemented fixup kind (relative)"); case PPC::fixup_ppc_br24: Type = MachO::PPC_RELOC_BR24; // R_PPC_REL24 break; case PPC::fixup_ppc_brcond14: Type = MachO::PPC_RELOC_BR14; break; case PPC::fixup_ppc_half16: switch (Modifier) { default: llvm_unreachable("Unsupported modifier for half16 fixup"); case MCSymbolRefExpr::VK_PPC_HA: Type = MachO::PPC_RELOC_HA16; break; case MCSymbolRefExpr::VK_PPC_LO: Type = MachO::PPC_RELOC_LO16; break; case MCSymbolRefExpr::VK_PPC_HI: Type = MachO::PPC_RELOC_HI16; break; } break; } } else { switch ((unsigned)FixupKind) { default: report_fatal_error("Unimplemented fixup kind (absolute)!"); case PPC::fixup_ppc_half16: switch (Modifier) { default: llvm_unreachable("Unsupported modifier for half16 fixup"); case MCSymbolRefExpr::VK_PPC_HA: Type = MachO::PPC_RELOC_HA16_SECTDIFF; break; case MCSymbolRefExpr::VK_PPC_LO: Type = MachO::PPC_RELOC_LO16_SECTDIFF; break; case MCSymbolRefExpr::VK_PPC_HI: Type = MachO::PPC_RELOC_HI16_SECTDIFF; break; } break; case FK_Data_4: break; case FK_Data_2: break; } } return Type; } static void makeRelocationInfo(MachO::any_relocation_info &MRE, const uint32_t FixupOffset, const uint32_t Index, const unsigned IsPCRel, const unsigned Log2Size, const unsigned IsExtern, const unsigned Type) { MRE.r_word0 = FixupOffset; // The bitfield offsets that work (as determined by trial-and-error) // are different than what is documented in the mach-o manuals. // This appears to be an endianness issue; reversing the order of the // documented bitfields in <llvm/BinaryFormat/MachO.h> fixes this (but // breaks x86/ARM assembly). MRE.r_word1 = ((Index << 8) | // was << 0 (IsPCRel << 7) | // was << 24 (Log2Size << 5) | // was << 25 (IsExtern << 4) | // was << 27 (Type << 0)); // was << 28 } static void makeScatteredRelocationInfo(MachO::any_relocation_info &MRE, const uint32_t Addr, const unsigned Type, const unsigned Log2Size, const unsigned IsPCRel, const uint32_t Value2) { // For notes on bitfield positions and endianness, see: // https://developer.apple.com/library/mac/documentation/developertools/conceptual/MachORuntime/Reference/reference.html#//apple_ref/doc/uid/20001298-scattered_relocation_entry MRE.r_word0 = ((Addr << 0) | (Type << 24) | (Log2Size << 28) | (IsPCRel << 30) | MachO::R_SCATTERED); MRE.r_word1 = Value2; } /// Compute fixup offset (address). static uint32_t getFixupOffset(const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup) { uint32_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); // On Mach-O, ppc_fixup_half16 relocations must refer to the // start of the instruction, not the second halfword, as ELF does if (unsigned(Fixup.getKind()) == PPC::fixup_ppc_half16) FixupOffset &= ~uint32_t(3); return FixupOffset; } /// \return false if falling back to using non-scattered relocation, /// otherwise true for normal scattered relocation. /// based on X86MachObjectWriter::recordScatteredRelocation /// and ARMMachObjectWriter::recordScatteredRelocation bool PPCMachObjectWriter::recordScatteredRelocation( MachObjectWriter *Writer, const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, unsigned Log2Size, uint64_t &FixedValue) { // caller already computes these, can we just pass and reuse? const uint32_t FixupOffset = getFixupOffset(Layout, Fragment, Fixup); const MCFixupKind FK = Fixup.getKind(); const unsigned IsPCRel = Writer->isFixupKindPCRel(Asm, FK); const unsigned Type = getRelocType(Target, FK, IsPCRel); // Is this a local or SECTDIFF relocation entry? // SECTDIFF relocation entries have symbol subtractions, // and require two entries, the first for the add-symbol value, // the second for the subtract-symbol value. // See <reloc.h>. const MCSymbol *A = &Target.getSymA()->getSymbol(); if (!A->getFragment()) report_fatal_error("symbol '" + A->getName() + "' can not be undefined in a subtraction expression"); uint32_t Value = Writer->getSymbolAddress(*A, Layout); uint64_t SecAddr = Writer->getSectionAddress(A->getFragment()->getParent()); FixedValue += SecAddr; uint32_t Value2 = 0; if (const MCSymbolRefExpr *B = Target.getSymB()) { const MCSymbol *SB = &B->getSymbol(); if (!SB->getFragment()) report_fatal_error("symbol '" + SB->getName() + "' can not be undefined in a subtraction expression"); // FIXME: is Type correct? see include/llvm/BinaryFormat/MachO.h Value2 = Writer->getSymbolAddress(*SB, Layout); FixedValue -= Writer->getSectionAddress(SB->getFragment()->getParent()); } // FIXME: does FixedValue get used?? // Relocations are written out in reverse order, so the PAIR comes first. if (Type == MachO::PPC_RELOC_SECTDIFF || Type == MachO::PPC_RELOC_HI16_SECTDIFF || Type == MachO::PPC_RELOC_LO16_SECTDIFF || Type == MachO::PPC_RELOC_HA16_SECTDIFF || Type == MachO::PPC_RELOC_LO14_SECTDIFF || Type == MachO::PPC_RELOC_LOCAL_SECTDIFF) { // X86 had this piece, but ARM does not // If the offset is too large to fit in a scattered relocation, // we're hosed. It's an unfortunate limitation of the MachO format. if (FixupOffset > 0xffffff) { char Buffer[32]; format("0x%x", FixupOffset).print(Buffer, sizeof(Buffer)); Asm.getContext().reportError(Fixup.getLoc(), Twine("Section too large, can't encode " "r_address (") + Buffer + ") into 24 bits of scattered " "relocation entry."); return false; } // Is this supposed to follow MCTarget/PPCAsmBackend.cpp:adjustFixupValue()? // see PPCMCExpr::evaluateAsRelocatableImpl() uint32_t other_half = 0; switch (Type) { case MachO::PPC_RELOC_LO16_SECTDIFF: other_half = (FixedValue >> 16) & 0xffff; // applyFixupOffset longer extracts the high part because it now assumes // this was already done. // It looks like this is not true for the FixedValue needed with Mach-O // relocs. // So we need to adjust FixedValue again here. FixedValue &= 0xffff; break; case MachO::PPC_RELOC_HA16_SECTDIFF: other_half = FixedValue & 0xffff; FixedValue = ((FixedValue >> 16) + ((FixedValue & 0x8000) ? 1 : 0)) & 0xffff; break; case MachO::PPC_RELOC_HI16_SECTDIFF: other_half = FixedValue & 0xffff; FixedValue = (FixedValue >> 16) & 0xffff; break; default: llvm_unreachable("Invalid PPC scattered relocation type."); break; } MachO::any_relocation_info MRE; makeScatteredRelocationInfo(MRE, other_half, MachO::GENERIC_RELOC_PAIR, Log2Size, IsPCRel, Value2); Writer->addRelocation(nullptr, Fragment->getParent(), MRE); } else { // If the offset is more than 24-bits, it won't fit in a scattered // relocation offset field, so we fall back to using a non-scattered // relocation. This is a bit risky, as if the offset reaches out of // the block and the linker is doing scattered loading on this // symbol, things can go badly. // // Required for 'as' compatibility. if (FixupOffset > 0xffffff) return false; } MachO::any_relocation_info MRE; makeScatteredRelocationInfo(MRE, FixupOffset, Type, Log2Size, IsPCRel, Value); Writer->addRelocation(nullptr, Fragment->getParent(), MRE); return true; } // see PPCELFObjectWriter for a general outline of cases void PPCMachObjectWriter::RecordPPCRelocation( MachObjectWriter *Writer, const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) { const MCFixupKind FK = Fixup.getKind(); // unsigned const unsigned Log2Size = getFixupKindLog2Size(FK); const bool IsPCRel = Writer->isFixupKindPCRel(Asm, FK); const unsigned RelocType = getRelocType(Target, FK, IsPCRel); // If this is a difference or a defined symbol plus an offset, then we need a // scattered relocation entry. Differences always require scattered // relocations. if (Target.getSymB() && // Q: are branch targets ever scattered? RelocType != MachO::PPC_RELOC_BR24 && RelocType != MachO::PPC_RELOC_BR14) { recordScatteredRelocation(Writer, Asm, Layout, Fragment, Fixup, Target, Log2Size, FixedValue); return; } // this doesn't seem right for RIT_PPC_BR24 // Get the symbol data, if any. const MCSymbol *A = nullptr; if (Target.getSymA()) A = &Target.getSymA()->getSymbol(); // See <reloc.h>. const uint32_t FixupOffset = getFixupOffset(Layout, Fragment, Fixup); unsigned Index = 0; unsigned Type = RelocType; const MCSymbol *RelSymbol = nullptr; if (Target.isAbsolute()) { // constant // SymbolNum of 0 indicates the absolute section. // // FIXME: Currently, these are never generated (see code below). I cannot // find a case where they are actually emitted. report_fatal_error("FIXME: relocations to absolute targets " "not yet implemented"); // the above line stolen from ARM, not sure } else { // Resolve constant variables. if (A->isVariable()) { int64_t Res; if (A->getVariableValue()->evaluateAsAbsolute( Res, Layout, Writer->getSectionAddressMap())) { FixedValue = Res; return; } } // Check whether we need an external or internal relocation. if (Writer->doesSymbolRequireExternRelocation(*A)) { RelSymbol = A; // For external relocations, make sure to offset the fixup value to // compensate for the addend of the symbol address, if it was // undefined. This occurs with weak definitions, for example. if (!A->isUndefined()) FixedValue -= Layout.getSymbolOffset(*A); } else { // The index is the section ordinal (1-based). const MCSection &Sec = A->getSection(); Index = Sec.getOrdinal() + 1; FixedValue += Writer->getSectionAddress(&Sec); } if (IsPCRel) FixedValue -= Writer->getSectionAddress(Fragment->getParent()); } // struct relocation_info (8 bytes) MachO::any_relocation_info MRE; makeRelocationInfo(MRE, FixupOffset, Index, IsPCRel, Log2Size, false, Type); Writer->addRelocation(RelSymbol, Fragment->getParent(), MRE); } std::unique_ptr<MCObjectTargetWriter> llvm::createPPCMachObjectWriter(bool Is64Bit, uint32_t CPUType, uint32_t CPUSubtype) { return llvm::make_unique<PPCMachObjectWriter>(Is64Bit, CPUType, CPUSubtype); }
// $Id: SL2_SecurityManager.cpp 2179 2013-05-28 22:16:51Z mesnierp $ #include "orbsvcs/Log_Macros.h" #include "orbsvcs/Log_Macros.h" #include "orbsvcs/Security/SL2_SecurityManager.h" #include "tao/ORB_Constants.h" #include "ace/Functor.h" #include "tao/Object_KeyC.h" #include "tao/PortableServer/Root_POA.h" #include "tao/PortableServer/Object_Adapter.h" #include "tao/PortableServer/Creation_Time.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO::Security::SecurityManager::SecurityManager (/* unknown */) : principal_authenticator_ (SecurityLevel2::PrincipalAuthenticator::_nil ()) { // this needs to change to access decision SecurityLevel2::AccessDecision_ptr ad; ACE_NEW_THROW_EX (ad, TAO::Security::AccessDecision, CORBA::NO_MEMORY ( CORBA::SystemException::_tao_minor_code ( TAO::VMCID, ENOMEM), CORBA::COMPLETED_NO)); this->access_decision_ = ad; } TAO::Security::SecurityManager::~SecurityManager (void) { } Security::MechandOptionsList* TAO::Security::SecurityManager::supported_mechanisms () { throw CORBA::NO_IMPLEMENT (); } SecurityLevel2::CredentialsList* TAO::Security::SecurityManager::own_credentials () { throw CORBA::NO_IMPLEMENT (); } SecurityLevel2::RequiredRights_ptr TAO::Security::SecurityManager::required_rights_object () { throw CORBA::NO_IMPLEMENT (); } SecurityLevel2::PrincipalAuthenticator_ptr TAO::Security::SecurityManager::principal_authenticator () { return SecurityLevel2::PrincipalAuthenticator::_duplicate (this->principal_authenticator_.in () ); } SecurityLevel2::AccessDecision_ptr TAO::Security::SecurityManager::access_decision () { return SecurityLevel2::AccessDecision::_duplicate (this->access_decision_.in () ); } SecurityLevel2::AuditDecision_ptr TAO::Security::SecurityManager::audit_decision () { throw CORBA::NO_IMPLEMENT (); } SecurityLevel2::TargetCredentials_ptr TAO::Security::SecurityManager::get_target_credentials (CORBA::Object_ptr /*o*/) { throw CORBA::NO_IMPLEMENT (); } void TAO::Security::SecurityManager::remove_own_credentials (SecurityLevel2::Credentials_ptr /*creds*/) { throw CORBA::NO_IMPLEMENT (); } CORBA::Policy_ptr TAO::Security::SecurityManager::get_security_policy (CORBA::PolicyType /*policy_type */) { throw CORBA::NO_IMPLEMENT (); } /* * AccessDecision stuff below here */ bool TAO::Security::AccessDecision::ReferenceKeyType::operator== (const ReferenceKeyType& other) const { ::CORBA::ULong olen = this->oid_->length(); ::CORBA::ULong alen = this->adapter_id_->length(); if (olen == other.oid_->length() && alen == other.adapter_id_->length()) return (ACE_OS::memcmp (this->oid_->get_buffer(), other.oid_->get_buffer(),olen) == 0 && ACE_OS::memcmp (this->adapter_id_->get_buffer(), other.adapter_id_->get_buffer(),alen) == 0 && ACE_OS_String::strcmp (this->orbid_.in(), other.orbid_.in()) == 0); return false; } CORBA::ULong TAO::Security::AccessDecision::ReferenceKeyType::hash () const { return 0; } TAO::Security::AccessDecision::ReferenceKeyType::operator const char* () const { return "<hardcoded refkey>"; } TAO::Security::AccessDecision::AccessDecision () : default_allowance_decision_ (false) { } TAO::Security::AccessDecision::~AccessDecision () { } TAO::Security::AccessDecision::OBJECT_KEY TAO::Security::AccessDecision::map_key_from_objref (CORBA::Object_ptr /*obj */) { ORBSVCS_ERROR ((LM_ERROR, "map_key_from_objref is currently not implemented\n")); throw CORBA::NO_IMPLEMENT(); #if defined (__HP_aCC) OBJECT_KEY key; return key; #endif /* __HP_aCC */ } CORBA::Boolean TAO::Security::AccessDecision::access_allowed_i (OBJECT_KEY &key, const char *operation_name) { // LOCK THE MAP! ACE_GUARD_RETURN (TAO_SYNCH_MUTEX, guard, this->map_lock_, this->default_allowance_decision_); ACE_Hash<OBJECT_KEY> hash; // Look up the target in access_map_; if there, return the value, // otherwise return the default value. CORBA::Boolean access_decision = false; if (this->access_map_.find (key, access_decision) == -1) { // Couldn't find the IOR in the map, so we use the default access_decision = this->default_allowance_decision_; if (TAO_debug_level >= 3) ORBSVCS_DEBUG ((LM_DEBUG, "TAO (%P|%t) SL2_AccessDecision::access_decision(%x,%s)" " NOT FOUND using default %d\n", hash.operator()(key), operation_name, access_decision)); } else if (TAO_debug_level >= 3) { ORBSVCS_DEBUG ((LM_DEBUG, "TAO (%P|%t) SL2_AccessDecision::access_decision(%x,%s)" " found with decision %d\n", hash.operator()(key), operation_name, access_decision)); } // For now we just return the default. return access_decision; } CORBA::Boolean TAO::Security::AccessDecision::access_allowed_ex ( const char * orb_id, const ::CORBA::OctetSeq & adapter_id, const ::CORBA::OctetSeq & object_id, const ::SecurityLevel2::CredentialsList & /*cred_list */, const char * operation_name) { OBJECT_KEY key; key.orbid_ = orb_id; key.adapter_id_ = adapter_id; key.oid_ = object_id; return this->access_allowed_i (key, operation_name); } CORBA::Boolean TAO::Security::AccessDecision::access_allowed (const ::SecurityLevel2::CredentialsList & /*cred_list */, ::CORBA::Object_ptr target, const char * operation_name, const char * /*target_interface_name */) { // @@ I still don't know what we do with the cred_list in here... // Do we inspect it? // Turn the target into what we'll use as a key into the map. OBJECT_KEY key = this->map_key_from_objref (target); return this->access_allowed_i (key, operation_name); } void TAO::Security::AccessDecision::add_object (const char * orb_id, const ::CORBA::OctetSeq & adapter_id, const ::CORBA::OctetSeq & object_id, CORBA::Boolean allow_insecure_access) { // make a key from 'obj' OBJECT_KEY key; key.orbid_ = orb_id; key.adapter_id_ = adapter_id; key.oid_ = object_id; // bind it into the access_map_, replacing anything that's there. // LOCK THE MAP! ACE_GUARD (TAO_SYNCH_MUTEX, guard, this->map_lock_); ACE_Hash<OBJECT_KEY> hash; // Since we want to replace any existing entry in the map, we just // use rebind. errno = 0; // Not sure if this gets set if rebind fails...it only // appears to fail when an allocation thru the allocator's // malloc() fails. Depending on the malloc() implementation, // errno could get set OR an exception thrown. int ret = this->access_map_.rebind (key, allow_insecure_access); if (ret == -1) { // rebind shouldn't fail under normal circumstances if (TAO_debug_level > 1) ORBSVCS_DEBUG ((LM_DEBUG, "TAO (%P|%t): SL2_AccessDecision::add_object(%x,%d) " "unexpectedly failed (errno=%d)\n", hash.operator()(key), allow_insecure_access, ACE_ERRNO_GET)); throw CORBA::NO_MEMORY(CORBA::SystemException::_tao_minor_code (TAO::VMCID, errno), CORBA::COMPLETED_NO); } else { if (TAO_debug_level >= 3) ORBSVCS_DEBUG ((LM_DEBUG, "TAO (%P|%t): SL2_AccessDecision::add_object(%x,%d) okay\n", hash.operator()(key), allow_insecure_access)); } } void TAO::Security::AccessDecision::remove_object (const char * orb_id, const ::CORBA::OctetSeq & adapter_id, const ::CORBA::OctetSeq & object_id) { OBJECT_KEY key; key.orbid_ = orb_id; key.adapter_id_ = adapter_id; key.oid_ = object_id; ACE_Hash<OBJECT_KEY> hash; // unbind it from access_map_, no matter if it's not in there... // LOCK THE MAP! ACE_GUARD (TAO_SYNCH_MUTEX, guard, this->map_lock_); errno = 0; int ret = this->access_map_.unbind (key); if (ret == -1) { if (errno == ENOENT) { // ignore b/c we don't care...maybe log a debug message for info if (TAO_debug_level >= 3) ORBSVCS_DEBUG ((LM_DEBUG, "TAO (%P|%t): SL2_AccessDecision::remove_object(%x) " "object not found in access map\n", hash.operator()(key))); } else { if (TAO_debug_level > 0) ORBSVCS_DEBUG ((LM_DEBUG, "TAO (%P|%t): SL2_AccessDecision::remove_object(%x) " " unexpected error during unbind from map (errno=%d\n)", hash.operator()(key), ACE_ERRNO_GET)); throw CORBA::UNKNOWN (CORBA::SystemException::_tao_minor_code (TAO::VMCID, errno), CORBA::COMPLETED_NO); } } } CORBA::Boolean TAO::Security::AccessDecision::default_decision (void) { return this->default_allowance_decision_; } void TAO::Security::AccessDecision::default_decision (CORBA::Boolean d) { this->default_allowance_decision_ = d; } TAO_END_VERSIONED_NAMESPACE_DECL
/** \author Yucheng Low (ylow), Joseph Gonzalez Interface for Scope Factories */ #ifndef GRAPHLAB_ISCOPE_FACTORY_HPP #define GRAPHLAB_ISCOPE_FACTORY_HPP #include <graphlab/scope/iscope.hpp> #include <graphlab/macros_def.hpp> namespace graphlab { template<typename Graph> class iscope_factory { public: typedef Graph graph_type; typedef iscope<Graph> iscope_type; /** \note This constructor here does not actually do anything. It just exists to force the derived class constructors to look like this */ iscope_factory(Graph& graph, size_t ncpus) {} virtual ~iscope_factory() {} //! Returns a scope around a particular vertex virtual iscope_type* get_scope(size_t cpuid, vertex_id_t vertex, scope_range::scope_range_enum s = scope_range::USE_DEFAULT) = 0; //! Set the default scope type virtual void set_default_scope(scope_range::scope_range_enum default_scope_range) = 0; //! Destroys a scope virtual void release_scope(iscope<Graph>* scope) = 0; //! Get the number of vertices virtual size_t num_vertices() const = 0; }; } #include <graphlab/macros_undef.hpp> #endif
/** * @author Andrew Robert Owens, Philmo Gu * @date 2019-10-15. * @details Organization: Biological Modeling and Visualization research group * University of Calgary, Calgary, AB, Canada * * Contact: arowens [at] ucalgary.ca * @copyright Copyright (c) 2019 ___ALGORITHMIC_BOTANY___. All rights reserved. * * @brief */ #include "triangle.hpp" namespace geometry { template<typename T> Triangle_<T>::Triangle_(T a, T b, T c) : m_vertices{a, b, c} {} template<typename T> T const &Triangle_<T>::a() const { return m_vertices[Index::A]; } template<typename T> T const &Triangle_<T>::b() const { return m_vertices[Index::B]; } template<typename T> T const &Triangle_<T>::c() const { return m_vertices[Index::C]; } template<typename T> T const &Triangle_<T>::operator[](int index) const { return m_vertices[index]; } template<typename T> T &Triangle_<T>::a() { return m_vertices[Index::A]; }; template<typename T> T &Triangle_<T>::b() { return m_vertices[Index::B]; }; template<typename T> T &Triangle_<T>::c() { return m_vertices[Index::C]; }; template<typename T> T &Triangle_<T>::operator[](int index) { return m_vertices[index]; } } // namespace geometry
#include <util/types.hxx> namespace util { void fillTriggerInfo(TriggerBank& bank, uint8_t const channel, uint32_t const threshold, bool const rising) { bank.triggerChannel.raw = 0; bank.triggerChannel.bits.no = channel; bank.triggerThreshold = static_cast<uint16_t>(threshold); bank.triggerInfo.raw = 0; bank.triggerInfo.bits.rising = rising ? 1 : 0; bank.reserved = static_cast<uint16_t>(threshold >> 16); } void fillSignalInfo(SignalInfoBank& bank, uint32_t const length, uint32_t const frontLength, uint8_t const timeTriggers, uint8_t const disabledTriggers, int16_t const threshold, bool const rising, uint32_t const maxTime) { bank.length = length; bank.frontLength = frontLength; bank.pattern.raw = 0; bank.pattern.bits.timeTriggers = timeTriggers; bank.pattern.bits.disabledTriggers = disabledTriggers; bank.pattern.bits.threshold = threshold; bank.pattern2.bits.rising = rising ? 1 : 0; bank.maxTime = maxTime; } }
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/layout_assignment.h" #include <memory> #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/errors.h" namespace xla { namespace gpu { Status GpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { for (auto& instruction : constraints->computation()->instructions()) { // cuDNN is called with specific layouts on the input, output, and filter: // // input: DataLayout::kBatchDepthYX // output: DataLayout::kBatchDepthYX // filter: FilterLayout::kOutputInputYX // // The order dimensions in the constant name is major-to-minor (eg, the // most-major dimension of the input is batch, most-minor is X). The // specific dimension numbers these named dimensions correspond to is // determined by the ConvolutionDimensionNumbers argument. Y is spatial // dimension 0, and X is spatial dimension 1. // // TODO(b/29399649): Be more flexible about handling layouts of cuDNN calls. if (ImplementedAsDnnConvolution(*instruction)) { HloInstruction* input = nullptr; HloInstruction* filter = nullptr; HloInstruction* output = nullptr; if (instruction->opcode() == HloOpcode::kConvolution) { input = instruction->mutable_operand(0); filter = instruction->mutable_operand(1); output = instruction.get(); } else { CHECK_EQ(HloOpcode::kFusion, instruction->opcode()); switch (instruction->fusion_kind()) { case HloInstruction::FusionKind::kConvBackwardFilter: // filter = BackwardFilterConvolve(input, output) input = instruction->mutable_operand(0); filter = instruction.get(); output = instruction->mutable_operand(1); break; case HloInstruction::FusionKind::kConvBackwardInput: // input = BackwardInputConvolve(output, filter) input = instruction.get(); filter = instruction->mutable_operand(1); output = instruction->mutable_operand(0); break; default: LOG(FATAL) << "Not a convolution-fusion"; } } // Construct minor-to-major dimension orders for operands and result. // cuDNN's convolution APIs support the BDYX layout for activations/output // and the OIYX layout for weights. // TODO(b/29399649): Be more flexible about handling layouts of cuDNN // calls after we switch to cuDNN v5. const ConvolutionDimensionNumbers& dimension_numbers = instruction->convolution_dimension_numbers(); Shape input_shape(input->shape()); *input_shape.mutable_layout() = LayoutUtil::MakeLayout({dimension_numbers.spatial_dimensions(1), dimension_numbers.spatial_dimensions(0), dimension_numbers.feature_dimension(), dimension_numbers.batch_dimension()}); Shape filter_shape(filter->shape()); *filter_shape.mutable_layout() = LayoutUtil::MakeLayout( {dimension_numbers.kernel_spatial_dimensions(1), dimension_numbers.kernel_spatial_dimensions(0), dimension_numbers.kernel_input_feature_dimension(), dimension_numbers.kernel_output_feature_dimension()}); Shape output_shape(output->shape()); *output_shape.mutable_layout() = LayoutUtil::MakeLayout({dimension_numbers.spatial_dimensions(1), dimension_numbers.spatial_dimensions(0), dimension_numbers.feature_dimension(), dimension_numbers.batch_dimension()}); // Set layouts of the instructions' shapes. if (instruction->opcode() == HloOpcode::kConvolution) { TF_RETURN_IF_ERROR( constraints->SetOperandLayout(input_shape, output, 0)); TF_RETURN_IF_ERROR( constraints->SetOperandLayout(filter_shape, output, 1)); TF_RETURN_IF_ERROR( constraints->SetInstructionLayout(output_shape, output)); } else { CHECK_EQ(HloOpcode::kFusion, instruction->opcode()); switch (instruction->fusion_kind()) { case HloInstruction::FusionKind::kConvBackwardFilter: // filter = BackwardFilterConvolve(input, output) TF_RETURN_IF_ERROR( constraints->SetOperandLayout(input_shape, filter, 0)); TF_RETURN_IF_ERROR( constraints->SetInstructionLayout(filter_shape, filter)); TF_RETURN_IF_ERROR( constraints->SetOperandLayout(output_shape, filter, 1)); break; case HloInstruction::FusionKind::kConvBackwardInput: // input = BackwardInputConvolve(output, filter) TF_RETURN_IF_ERROR( constraints->SetInstructionLayout(input_shape, input)); TF_RETURN_IF_ERROR( constraints->SetOperandLayout(output_shape, input, 0)); TF_RETURN_IF_ERROR( constraints->SetOperandLayout(filter_shape, input, 1)); break; default: LOG(FATAL) << "Not a convolution-fusion"; } } } } return Status::OK(); } } // namespace gpu } // namespace xla
#include <QMap> #include "transactionrecord.h" #include "wallet.h" #include "base58.h" /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx &wtx) { if (wtx.IsCoinBase()) { // Don't show generated coin until confirmed by at least one block after it // so we don't get the user's hopes up until it looks like it's probably accepted. // // It is not an error when generated blocks are not accepted. By design, // some percentage of blocks, like 10% or more, will end up not accepted. // This is the normal mechanism by which the network copes with latency. // // We display regular transactions right away before any confirmation // because they can always get into some block eventually. Generated coins // are special because if their block is not accepted, they are not valid. // if (wtx.GetDepthInMainChain() < 2) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<TransactionRecord> parts; int64 nTime = wtx.GetTxTime(); int64 nCredit = wtx.GetCredit(true); int64 nDebit = wtx.GetDebit(); int64 nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; const bool combineOutputs = (wtx.cUnit == '8'); if (showTransaction(wtx)) { if (wtx.IsCoinStake()) // ppcoin: coinstake transaction { parts.append(TransactionRecord(hash, nTime, TransactionRecord::StakeMint, "", -nDebit, wtx.GetValueOut())); } else if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // QMap<CScript, TransactionRecord*> outputParts; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if(wallet->IsMine(txout)) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = parts.size(); // sequence number sub.credit = txout.nValue; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { if (wtx.IsUnpark()) { sub.type = TransactionRecord::Unpark; } else // Received by Bitcoin Address sub.type = TransactionRecord::RecvWithAddress; sub.address = CBitcoinAddress(address, wtx.cUnit).ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } if (combineOutputs) { QMap<CScript, TransactionRecord*>::const_iterator it = outputParts.find(txout.scriptPubKey); if (it != outputParts.end()) { TransactionRecord& previous = *it.value(); previous.credit += sub.credit; continue; } } parts.append(sub); if (combineOutputs) outputParts[txout.scriptPubKey] = &parts.back(); } } } else { bool fAllFromMe = true; BOOST_FOREACH(const CTxIn& txin, wtx.vin) fAllFromMe = fAllFromMe && wallet->IsMine(txin); bool fAllToMe = true; BOOST_FOREACH(const CTxOut& txout, wtx.vout) fAllToMe = fAllToMe && wallet->IsMine(txout); bool fPark = false; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { int64 nParkDuration; CTxDestination unparkAddress; if (ExtractPark(txout.scriptPubKey, nParkDuration, unparkAddress)) { fPark = true; if (nDebit == 0) // if the parking was not done by me, do not list the transaction continue; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); sub.type = TransactionRecord::Park; sub.address = CBitcoinAddress(unparkAddress, wtx.cUnit).ToString(); sub.debit = -txout.nValue; if (parts.size() == 0) { int64 nTxFee = nDebit - wtx.GetValueOut(); sub.debit -= nTxFee; } parts.append(sub); } } if (fPark) { // do nothing, all other outputs should be change } else if (fAllFromMe && fAllToMe) { // Payment to self int64 nChange = wtx.GetChange(); parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "", -(nDebit - nChange), nCredit - nChange)); } else if (fAllFromMe) { // // Debit // int64 nTxFee = nDebit - wtx.GetValueOut(); QMap<CScript, TransactionRecord*> outputParts; for (int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); if(wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { // Sent to Bitcoin Address sub.type = TransactionRecord::SendToAddress; sub.address = CBitcoinAddress(address, wtx.cUnit).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } int64 nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; if (combineOutputs) { QMap<CScript, TransactionRecord*>::const_iterator it = outputParts.find(txout.scriptPubKey); if (it != outputParts.end()) { TransactionRecord& previous = *it.value(); previous.debit += sub.debit; continue; } } parts.append(sub); if (combineOutputs) outputParts[txout.scriptPubKey] = &parts.back(); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); } } } return parts; } void TransactionRecord::updateStatus(const CWalletTx &wtx) { // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.confirmed = wtx.IsConfirmed(); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = nBestHeight; if (!wtx.IsFinal()) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = nBestHeight - wtx.nLockTime; } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } else { if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth < NumConfirmations) { status.status = TransactionStatus::Unconfirmed; } else { status.status = TransactionStatus::HaveConfirmations; } } // For generated transactions, determine maturity if(type == TransactionRecord::Generated || type == TransactionRecord::StakeMint) { int64 nCredit = wtx.GetCredit(true); if (nCredit == 0) { status.maturity = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.maturity = TransactionStatus::MaturesWarning; } else { status.maturity = TransactionStatus::NotAccepted; } } else { status.maturity = TransactionStatus::Mature; } } } bool TransactionRecord::statusUpdateNeeded() { return status.cur_num_blocks != nBestHeight; } std::string TransactionRecord::getTxID() { return hash.ToString() + strprintf("-%03d", idx); }
/** * Insertion in heap * */ #include <iostream> #define MAX 100 using namespace std; void heapify(int a[], int i, int n) { int temp = a[i]; int j = 2 * i + 1; while (j < n) { if (j < n - 1 && a[j] < a[j + 1]) { j = j + 1; } if (temp > a[j]) { break; } i = j; a[(j - 1) / 2] = a[j]; j = 2 * i + 1; } a[(j - 1) / 2] = temp; } int parent(int i) { return (i - 1) / 2; } void shiftUp(int a[], int k) { while (k > 0 && a[k] > a[parent(k)]) { swap(a[k], a[parent(k)]); k = parent(k); } } void insertKey(int a[], int key, int &n) { n++; a[n - 1] = key; shiftUp(a, n - 1); } int main() { int a[MAX] = {1, 2, 3, 4, 5, 6}; int n = 6; for (int i = (n - 1) / 2; i >= 0; --i) heapify(a, i, n); cout << "Displaying the heap...\n"; for (int i = 0; i < n; i++) cout << a[i] << (i + 1 == n ? "\n" : " "); insertKey(a, 20, n); cout << "Displaying heap after insertion\n"; for (int i = 0; i < n; i++) cout << a[i] << (i + 1 == n ? "\n" : " "); return 0; }
#include <fstream> #include <sstream> #include <gtest/gtest-param-test.h> #include "thorin/error.h" #include "thorin/world.h" #include "thorin/be/ll/ll.h" #include "thorin/pass/fp/beta_red.h" #include "thorin/pass/fp/copy_prop.h" #include "thorin/pass/fp/eta_exp.h" #include "thorin/pass/fp/eta_red.h" #include "thorin/pass/pass.h" #include "thorin/pass/rw/lower_for.h" #include "thorin/util/sys.h" #include "helpers.h" using namespace thorin; class ForAxiomTest : public testing::TestWithParam<std::tuple<int, int, int>> {}; TEST_P(ForAxiomTest, for) { World w; auto mem_t = w.type_mem(); auto i32_t = w.type_int_width(32); auto i64_t = w.type_int_width(64); auto argv_t = w.type_ptr(w.type_ptr(i32_t)); const auto [cbegin, cend, cstep] = GetParam(); auto lit_begin = w.lit_int_width(32, cbegin); auto lit_end = w.lit_int_width(32, cend); auto lit_step = w.lit_int_width(32, cstep); // Cn [mem, i32, ptr(ptr(i32, 0), 0) Cn [mem, i32]] auto main_t = w.cn({mem_t, i32_t, argv_t, w.cn({mem_t, i32_t})}); auto main = w.nom_lam(main_t, w.dbg("main")); { auto accumulator_type = w.sigma({i32_t, i64_t}); auto yield_type = w.cn({mem_t, accumulator_type}); auto body_type = w.cn({mem_t, i32_t, accumulator_type, yield_type}); auto body = w.nom_lam(body_type, w.dbg("body")); { auto [mem, i, acctpl, yield] = body->vars<4>({w.dbg("mem"), w.dbg("i"), w.dbg("acctpl"), w.dbg("yield")}); auto add = w.op(Wrap::add, w.lit_nat(0), w.extract(acctpl, 0_s), i); auto mul = w.op(Wrap::mul, w.lit_nat(0), w.extract(acctpl, 1_s), w.op(Conv::u2u, i64_t, i)); body->app(false, yield, {mem, w.tuple({add, mul})}); } auto brk = w.nom_lam(w.cn({mem_t, accumulator_type}), w.dbg("break")); { auto [main_mem, argc, argv, ret] = main->vars<4>({w.dbg("mem"), w.dbg("argc"), w.dbg("argv"), w.dbg("exit")}); auto [mem, acctpl] = brk->vars<2>(); brk->app(false, ret, {mem, w.extract(acctpl, 0_s)}); main->set_filter(false); main->set_body( w.op_for(main_mem, lit_begin, lit_end, lit_step, {w.lit_int(0), w.lit_int(i64_t, 5)}, body, brk)); } } main->make_external(); PassMan opt{w}; opt.add<LowerFor>(); auto br = opt.add<BetaRed>(); auto er = opt.add<EtaRed>(); auto ee = opt.add<EtaExp>(er); opt.add<CopyProp>(br, ee); opt.run(); unsigned gt = 0; for (int i = cbegin; i < cend; i += cstep) { gt += i; } EXPECT_EQ(gt % 256, ll::compile_and_run(w, gtest::test_name())); } TEST_P(ForAxiomTest, for_dynamic_iters) { World w; auto mem_t = w.type_mem(); auto i8_t = w.type_int_width(8); auto i32_t = w.type_int_width(32); auto i64_t = w.type_int_width(64); auto argv_t = w.type_ptr(w.arr(w.top_nat(), w.type_ptr(w.arr(w.top_nat(), i8_t)))); const auto [cbegin, cend, cstep] = GetParam(); // Cn [mem, i32, ptr(ptr(i32, 0), 0) Cn [mem, i32]] auto main_t = w.cn({mem_t, i32_t, argv_t, w.cn({mem_t, i32_t})}); auto main = w.nom_lam(main_t, w.dbg("main")); auto atoi_ret_t = w.cn({mem_t, i32_t}); // Cn [:mem, :ptr («⊤∷nat; i8», 0∷nat), Cn [:mem, i32]] auto atoi_t = w.cn({mem_t, w.type_ptr(w.arr(w.top_nat(), i8_t)), atoi_ret_t}); auto atoi = w.nom_lam(atoi_t, w.dbg("atoi")); auto atoi_begin = w.nom_lam(atoi_ret_t, w.dbg("atoi_cont_begin")); auto atoi_end = w.nom_lam(atoi_ret_t, w.dbg("atoi_cont_end")); auto atoi_step = w.nom_lam(atoi_ret_t, w.dbg("atoi_cont_step")); { auto [main_mem, argc, argv, ret] = main->vars<4>(); { auto [load_mem, arg_begin] = w.op_load(main_mem, w.op_lea(argv, w.lit_int(i32_t, 1)))->projs<2>(); main->app(false, atoi, {load_mem, arg_begin, atoi_begin}); } { auto [mem, begin] = atoi_begin->vars<2>(); auto [load_mem, arg_end] = w.op_load(mem, w.op_lea(argv, w.lit_int(i32_t, 2)))->projs<2>(); atoi_begin->app(false, atoi, {load_mem, arg_end, atoi_end}); } { auto [mem, end] = atoi_end->vars<2>(); auto [load_mem, arg_step] = w.op_load(mem, w.op_lea(argv, w.lit_int(i32_t, 3)))->projs<2>(); atoi_end->app(false, atoi, {load_mem, arg_step, atoi_step}); } } { auto accumulator_type = w.sigma({i32_t, i64_t}); auto yield_type = w.cn({mem_t, accumulator_type}); auto body_type = w.cn({mem_t, i32_t, accumulator_type, yield_type}); auto body = w.nom_lam(body_type, w.dbg("body")); { auto [mem, i, acctpl, yield] = body->vars<4>({w.dbg("mem"), w.dbg("i"), w.dbg("acctpl"), w.dbg("yield")}); auto add = w.op(Wrap::add, w.lit_nat(0), w.extract(acctpl, 0_s), i); auto mul = w.op(Wrap::mul, w.lit_nat(0), w.extract(acctpl, 1_s), w.op(Conv::u2u, i64_t, i)); body->app(false, yield, {mem, w.tuple({add, mul})}); } auto brk = w.nom_lam(w.cn({mem_t, accumulator_type}), w.dbg("break")); { auto [main_mem, argc, argv, ret] = main->vars<4>({w.dbg("mem"), w.dbg("argc"), w.dbg("argv"), w.dbg("exit")}); auto [mem, acctpl] = brk->vars<2>(); brk->app(false, ret, {mem, w.extract(acctpl, 0_s)}); auto begin = atoi_begin->var(1, w.dbg("begin")); auto end = atoi_end->var(1, w.dbg("end")); auto [step_mem, step] = atoi_step->vars<2>({w.dbg("mem"), w.dbg("step")}); atoi_step->set_filter(false); atoi_step->set_body(w.op_for(step_mem, begin, end, step, {w.lit_int(0), w.lit_int(i64_t, 5)}, body, brk)); } } main->make_external(); PassMan opt{w}; opt.add<LowerFor>(); auto br = opt.add<BetaRed>(); auto er = opt.add<EtaRed>(); auto ee = opt.add<EtaExp>(er); opt.add<CopyProp>(br, ee); opt.run(); unsigned gt = 0; for (int i = cbegin; i < cend; i += cstep) { gt += i; } EXPECT_EQ(gt % 256, ll::compile_and_run(w, gtest::test_name(), fmt("{} {} {}", cbegin, cend, cstep))); } // test with these begin, end, step combinations: INSTANTIATE_TEST_SUITE_P(ForSteps, ForAxiomTest, testing::Combine(testing::Values(0, 2), testing::Values(0, 4, 8), testing::Values(1, 2, 5)));
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ut/tools/converter/parser/tflite/tflite_parsers_test_utils.h" #include <iostream> #include "common/common_test.h" namespace mindspore { class TestTfliteParserStack : public TestTfliteParser { public: TestTfliteParserStack() = default; void SetUp() override { meta_graph = LoadAndConvert("./stack.tflite"); } }; TEST_F(TestTfliteParserStack, OpType) { ASSERT_NE(meta_graph, nullptr); ASSERT_GT(meta_graph->nodes.size(), 0); ASSERT_NE(meta_graph->nodes.front()->primitive.get(), nullptr); ASSERT_EQ(meta_graph->nodes.front()->primitive->value.type, schema::PrimitiveType_Stack) << "wrong Op Type"; } TEST_F(TestTfliteParserStack, AttrValue) { ASSERT_NE(meta_graph->nodes.front()->primitive->value.AsStack(), nullptr); auto val = meta_graph->nodes.front()->primitive->value.AsStack(); ASSERT_EQ(val->axis, 1); ASSERT_EQ(val->n, 2); const std::vector<int> isScale = {3, 2, 3}; ASSERT_EQ(val->isScale, isScale); } } // namespace mindspore
// Copyright (c) 2015-2018 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@webmail.co.za) // Distributed under the GULDEN software license, see the accompanying // file COPYING #if defined(HAVE_CONFIG_H) #include "config/gulden-config.h" #endif #include "GuldenGUI.h" #include "gui.h" #include "units.h" #include "clickablelabel.h" #include "receivecoinsdialog.h" #include "validation/validation.h" #include "validation/witnessvalidation.h" #include "guiutil.h" #include "init.h" #include "unity/appmanager.h" #include "alert.h" #include <QAction> #include <QApplication> #include <QDateTime> #include <QDesktopWidget> #include <QDragEnterEvent> #include <QListWidget> #include <QMenuBar> #include <QMessageBox> #include <QMimeData> #include <QProgressBar> #include <QProgressDialog> #include <QSettings> #include <QShortcut> #include <QStackedWidget> #include <QStatusBar> #include <QStyle> #include <QTimer> #include <QToolBar> #include <QToolButton> #include <QVBoxLayout> #include <QPushButton> #include <QDesktopServices> #include <QUrl> #include <QDialogButtonBox> #include <QScrollArea> #include <QProxyStyle> #include <QLineEdit> #include <QTextEdit> #include <QCollator> #include <_Gulden/accountsummarywidget.h> #include <_Gulden/newaccountdialog.h> #include <_Gulden/importprivkeydialog.h> #include <_Gulden/importwitnessdialog.h> #include <_Gulden/exchangeratedialog.h> #include <_Gulden/accountsettingsdialog.h> #include <_Gulden/witnessdialog.h> #include <Gulden/util.h> #include <consensus/consensus.h> #include "sendcoinsdialog.h" #include "wallet/wallet.h" #include "walletframe.h" #include "walletview.h" #include "utilmoneystr.h" #include "passwordmodifydialog.h" #include "backupdialog.h" #include "welcomedialog.h" #include "ticker.h" #include "nockssettings.h" #include "units.h" #include "optionsmodel.h" #include "askpassphrasedialog.h" #include "transactiontablemodel.h" #include "transactionrecord.h" #include "viewaddressdialog.h" //Font sizes - NB! We specifically use 'px' and not 'pt' for all font sizes, as qt scales 'pt' dynamically in a way that makes our fonts unacceptably small on OSX etc. it doesn't do this with px so we use px instead. //QString CURRENCY_DECIMAL_FONT_SIZE = "11px"; // For .00 in currency and PND text. //QString BODY_FONT_SIZE = "12px"; // Standard body font size used in 'most places'. //QString CURRENCY_FONT_SIZE = "13px"; // For currency //QString TOTAL_FONT_SIZE = "15px"; // For totals and account names //QString HEADER_FONT_SIZE = "16px"; // For large headings const char* LOGO_FONT_SIZE = "28px"; const char* TOOLBAR_FONT_SIZE = "15px"; const char* BUTTON_FONT_SIZE = "15px"; const char* SMALL_BUTTON_FONT_SIZE = "14px"; const char* MINOR_LABEL_FONT_SIZE = "12px"; //Colors const char* ACCENT_COLOR_1 = "#111444"; const char* ACCENT_COLOR_2 = "#080a28"; const char* TEXT_COLOR_1 = "#999"; const char* COLOR_VALIDATION_FAILED = "#FF8080"; //Toolbar constants unsigned int sideBarWidthNormal = 300; unsigned int sideBarWidth = sideBarWidthNormal; const unsigned int horizontalBarHeight = 60; const char* SIDE_BAR_WIDTH = "300px"; //Extended width for large balances. unsigned int sideBarWidthExtended = 340; const char* SIDE_BAR_WIDTH_EXTENDED = "340px"; void setValid(QWidget* control, bool validity) { control->setProperty("valid", validity); control->style()->unpolish(control); control->style()->polish(control); } void burnLineEditMemory(QLineEdit* edit) { // Attempt to overwrite text so that they do not linger around in memory edit->setText(QString(" ").repeated(edit->text().size())); edit->clear(); } void burnTextEditMemory(QTextEdit* edit) { // Attempt to overwrite text so that they do not linger around in memory edit->setText(QString(" ").repeated(edit->toPlainText().length())); edit->clear(); } static void setAccountLabelSelected(ClickableLabel* checkLabel) { checkLabel->setChecked(true); checkLabel->setCursor ( Qt::ArrowCursor ); } static void setAccountLabelUnselected(ClickableLabel* checkLabel) { checkLabel->setChecked(false); checkLabel->setCursor ( Qt::PointingHandCursor ); } bool requestUnlockDialogAlreadyShowing=false; void GUI::NotifyRequestUnlock(void* wallet, QString reason) { if (!requestUnlockDialogAlreadyShowing) { requestUnlockDialogAlreadyShowing = true; LogPrint(BCLog::QT, "NotifyRequestUnlock\n"); AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this, reason); dlg.setModel(new WalletModel(NULL, (CWallet*)wallet, NULL, NULL)); dlg.exec(); requestUnlockDialogAlreadyShowing = false; } } void GUI::NotifyRequestUnlockWithCallback(void* wallet, QString reason, std::function<void (void)> successCallback) { if (!requestUnlockDialogAlreadyShowing) { requestUnlockDialogAlreadyShowing = true; LogPrint(BCLog::QT, "NotifyRequestUnlockWithCallback\n"); AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this, reason); dlg.setModel(new WalletModel(NULL, (CWallet*)wallet, NULL, NULL)); int result = dlg.exec(); if(result == QDialog::Accepted) successCallback(); requestUnlockDialogAlreadyShowing = false; } } void GUI::handlePaymentAccepted() { LogPrint(BCLog::QT, "GUI::handlePaymentAccepted\n"); refreshTabVisibilities(); } void GUI::setBalance(const WalletBalances& balances, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { LogPrint(BCLog::QT, "GUI::setBalance\n"); if (ShutdownRequested()) return; cachedBalances = balances; watchOnlyBalanceCached = watchOnlyBalance; watchUnconfBalanceCached = watchUnconfBalance; watchImmatureBalanceCached = watchImmatureBalance; if (!labelBalance || !labelBalanceForex) return; CAmount displayBalanceAvailable = balances.availableExcludingLocked; CAmount displayBalanceLocked = balances.totalLocked; CAmount displayBalanceImmatureOrUnconfirmed = balances.immatureExcludingLocked + balances.unconfirmedExcludingLocked; CAmount displayBalanceTotal = displayBalanceLocked + displayBalanceAvailable + displayBalanceImmatureOrUnconfirmed; if (displayBalanceTotal < 0) displayBalanceTotal = 0; if (displayBalanceLocked < 0) displayBalanceLocked = 0; if (displayBalanceImmatureOrUnconfirmed < 0) displayBalanceImmatureOrUnconfirmed = 0; if (displayBalanceTotal < 0) displayBalanceTotal = 0; labelBalance->setText(GuldenUnits::format(GuldenUnits::NLG, displayBalanceTotal, false, GuldenUnits::separatorStandard, 2)); if (displayBalanceTotal > 0 && optionsModel) { QString forexLabel = QString::fromStdString(CurrencySymbolForCurrencyCode(optionsModel->guldenSettings->getLocalCurrency().toStdString())) + QString("\u2009") + GuldenUnits::format(GuldenUnits::NLG, ticker->convertGuldenToForex(displayBalanceTotal, optionsModel->guldenSettings->getLocalCurrency().toStdString()), false, GuldenUnits::separatorAlways, 2); labelBalanceForex->setText(QString("(") + forexLabel + QString(")")); QString forexToolTip; forexToolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\"><b>%1</b>&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Conversion estimate")).arg(""); forexToolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\"></td><td style=\"white-space: nowrap;\" align=\"right\"></td></tr>"); forexToolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\">%1&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Total")).arg(QString::fromStdString(CurrencySymbolForCurrencyCode(optionsModel->guldenSettings->getLocalCurrency().toStdString())) + QString("\u2009") + GuldenUnits::format(GuldenUnits::NLG, ticker->convertGuldenToForex(displayBalanceTotal, optionsModel->guldenSettings->getLocalCurrency().toStdString()), false, GuldenUnits::separatorAlways, 2)); forexToolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\">%1&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Locked")).arg(QString::fromStdString(CurrencySymbolForCurrencyCode(optionsModel->guldenSettings->getLocalCurrency().toStdString())) + QString("\u2009") + GuldenUnits::format(GuldenUnits::NLG, ticker->convertGuldenToForex(displayBalanceLocked, optionsModel->guldenSettings->getLocalCurrency().toStdString()), false, GuldenUnits::separatorAlways, 2)); forexToolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\">%1&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Pending")).arg(QString::fromStdString(CurrencySymbolForCurrencyCode(optionsModel->guldenSettings->getLocalCurrency().toStdString())) + QString("\u2009") + GuldenUnits::format(GuldenUnits::NLG, ticker->convertGuldenToForex(displayBalanceImmatureOrUnconfirmed, optionsModel->guldenSettings->getLocalCurrency().toStdString()), false, GuldenUnits::separatorAlways, 2)); forexToolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\">%1&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Spendable")).arg(QString::fromStdString(CurrencySymbolForCurrencyCode(optionsModel->guldenSettings->getLocalCurrency().toStdString())) + QString("\u2009") + GuldenUnits::format(GuldenUnits::NLG, ticker->convertGuldenToForex(displayBalanceAvailable, optionsModel->guldenSettings->getLocalCurrency().toStdString()), false, GuldenUnits::separatorAlways, 2)); labelBalanceForex->setToolTip(forexToolTip); if (labelBalance->isVisible()) labelBalanceForex->setVisible(true); } else { labelBalanceForex->setVisible(false); } if (accountScrollArea && displayBalanceTotal > 999999 * COIN && sideBarWidth != sideBarWidthExtended) { sideBarWidth = sideBarWidthExtended; doApplyStyleSheet(); resizeToolBarsGulden(); } else if (accountScrollArea && displayBalanceTotal < 999999 * COIN && sideBarWidth == sideBarWidthExtended) { sideBarWidth = sideBarWidthNormal; doApplyStyleSheet(); resizeToolBarsGulden(); } QString toolTip; toolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\"><b>%1</b>&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Wallet balances")).arg(""); toolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\"></td><td style=\"white-space: nowrap;\" align=\"right\"></td></tr>"); toolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\">%1&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Total")).arg(GuldenUnits::formatWithUnit(GuldenUnits::NLG, displayBalanceTotal, false, GuldenUnits::separatorStandard, 2)); toolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\">%1&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Locked")).arg(GuldenUnits::formatWithUnit(GuldenUnits::NLG, displayBalanceLocked, false, GuldenUnits::separatorStandard, 2)); toolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\">%1&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Pending")).arg(GuldenUnits::formatWithUnit(GuldenUnits::NLG, displayBalanceImmatureOrUnconfirmed, false, GuldenUnits::separatorStandard, 2)); toolTip += QString("<tr><td style=\"white-space: nowrap;\" align=\"left\">%1&nbsp;&nbsp;&nbsp;&nbsp;</td><td style=\"white-space: nowrap;\" align=\"right\">%2</td></tr>").arg(tr("Spendable")).arg(GuldenUnits::formatWithUnit(GuldenUnits::NLG, displayBalanceAvailable, false, GuldenUnits::separatorStandard, 2)); labelBalance->setToolTip(toolTip); } void GUI::updateExchangeRates() { LogPrint(BCLog::QT, "GUI::updateExchangeRates\n"); setBalance(cachedBalances, watchOnlyBalanceCached, watchUnconfBalanceCached, watchImmatureBalanceCached); } void GUI::doRequestRenewWitness(CAccount* funderAccount, CAccount* targetWitnessAccount) { LogPrint(BCLog::QT, "GUI::doRequestRenewWitness\n"); std::string strError; CMutableTransaction tx(CURRENT_TX_VERSION_POW2); CReserveKeyOrScript changeReserveKey(pactiveWallet, funderAccount, KEYCHAIN_EXTERNAL); CAmount txFee; if (!pactiveWallet->PrepareRenewWitnessAccountTransaction(funderAccount, targetWitnessAccount, changeReserveKey, tx, txFee, strError)) { std::string strAlert = "Failed to create witness renew transaction: " + strError; CAlert::Notify(strAlert, true, true); LogPrintf("%s", strAlert.c_str()); return; } QString questionString = tr("Renewing witness account will incur a transaction fee: "); questionString.append("<span style='color:#aa0000;'>"); questionString.append(GuldenUnits::formatHtmlWithUnit(optionsModel->getDisplayUnit(), txFee)); questionString.append("</span> "); QDialog* d = createDialog(this, questionString, tr("Send"), tr("Cancel"), 600, 360); int result = d->exec(); if(result != QDialog::Accepted) { return; } { LOCK2(cs_main, pactiveWallet->cs_wallet); if (!pactiveWallet->SignAndSubmitTransaction(changeReserveKey, tx, strError)) { std::string strAlert = "Failed to sign witness renewal transaction:" + strError; CAlert::Notify(strAlert, true, true); LogPrintf("%s", strAlert.c_str()); return; } } // Clear the failed flag in UI, and remove the 'renew' button for immediate user feedback. targetWitnessAccount->SetWarningState(AccountStatus::WitnessPending); static_cast<const CGuldenWallet*>(pactiveWallet)->NotifyAccountWarningChanged(pactiveWallet, targetWitnessAccount); walletFrame->currentWalletView()->witnessDialogPage->update(); } void GUI::requestRenewWitness(CAccount* funderAccount) { LogPrint(BCLog::QT, "GUI::requestRenewWitness\n"); CAccount* targetWitnessAccount = pactiveWallet->getActiveAccount(); if (!chainActive.Tip() || (IsArgSet("-testnet") && chainActive.Tip()->nHeight < 100) || (!IsArgSet("-testnet") && chainActive.Tip()->nHeight < 797000)) { QString message = tr("This feature is not yet available, please try again after block 797000."); QDialog* d = createDialog(this, message, tr("Okay"), QString(""), 400, 180); d->exec(); return; } std::function<void (void)> successCallback = [=](){doRequestRenewWitness(funderAccount, targetWitnessAccount);}; if (pactiveWallet->IsLocked()) { uiInterface.RequestUnlockWithCallback(pactiveWallet, _("Wallet unlock required to renew witness"), successCallback); } else { successCallback(); } } void GUI::requestFundWitness(CAccount* funderAccount) { LogPrint(BCLog::QT, "GUI::requestFundWitness\n"); CAccount* targetWitnessAccount = pactiveWallet->getActiveAccount(); pactiveWallet->setActiveAccount(funderAccount); gotoSendCoinsPage(); walletFrame->currentWalletView()->sendCoinsPage->gotoWitnessTab(targetWitnessAccount); } void GUI::requestEmptyWitness() { LogPrint(BCLog::QT, "GUI::requestEmptyWitness\n"); CAccount* fromWitnessAccount = pactiveWallet->getActiveAccount(); CAmount availableAmount = pactiveWallet->GetBalance(fromWitnessAccount, false, false, true); if (availableAmount > 0) { //fixme: (2.1) - Remove this when ready { CGetWitnessInfo witnessInfo; CBlock block; { LOCK(cs_main); // Required for ReadBlockFromDisk as well as GetWitnessInfo. if (!ReadBlockFromDisk(block, chainActive.Tip(), Params())) { std::string strErrorMessage = "Error in requestEmptyWitness, failed to read block from disk"; CAlert::Notify(strErrorMessage, true, true); LogPrintf("%s", strErrorMessage.c_str()); return; } if (!GetWitnessInfo(chainActive, Params(), nullptr, chainActive.Tip()->pprev, block, witnessInfo, chainActive.Tip()->nHeight)) { std::string strErrorMessage = "Error in requestEmptyWitness failed to retrieve witness info"; CAlert::Notify(strErrorMessage, true, true); LogPrintf("%s", strErrorMessage.c_str()); return; } for (const auto& witCoin : witnessInfo.witnessSelectionPoolUnfiltered) { if (IsMine(*fromWitnessAccount, witCoin.coin.out)) { CTxOutPoW2Witness witnessDetails; if ( (GetPow2WitnessOutput(witCoin.coin.out, witnessDetails)) && !IsPoW2WitnessLocked(witnessDetails, chainActive.Tip()->nHeight) ) { if (!chainActive.Tip() || (IsArgSet("-testnet") && chainActive.Tip()->nHeight < 100) || (!IsArgSet("-testnet") && chainActive.Tip()->nHeight < 797000)) { QString message = tr("This feature is not yet available, please try again after block 797000."); QDialog* d = createDialog(this, message, tr("Okay"), QString(""), 400, 180); d->exec(); return; } CTxDestination destIn; if (!ExtractDestination(witCoin.coin.out, destIn)) { std::string strErrorMessage = "Error in requestEmptyWitness failed to extract input address"; CAlert::Notify(strErrorMessage, true, true); LogPrintf("%s", strErrorMessage.c_str()); return; } std::string sDestIn = CGuldenAddress(destIn).ToString(); if (haveStaticFundingAddress(sDestIn, chainActive.Height()) > 0) { SendCoinsRecipient rcp; rcp.paymentType = SendCoinsRecipient::PaymentType::NormalPayment; rcp.fSubtractFeeFromAmount = true; rcp.amount = availableAmount; rcp.forexFailCode = ""; rcp.address = QString::fromStdString(getStaticFundingAddress(sDestIn, chainActive.Height())); walletFrame->currentWalletView()->sendCoinsPage->pendingRecipients.push_back(rcp); walletFrame->currentWalletView()->sendCoinsPage->on_sendButton_clicked(); return; } } } } } } walletFrame->gotoSendCoinsPage(); walletFrame->currentWalletView()->sendCoinsPage->setAmount(availableAmount); } else { QString message = tr("The funds in this account are currently locked for witnessing and cannot be transfered, please wait until lock expires or for earnings to accumulate before trying again."); QDialog* d = createDialog(this, message, tr("Okay"), QString(""), 400, 180); d->exec(); } } void GUI::setOptionsModel(OptionsModel* optionsModel_) { LogPrint(BCLog::QT, "GUI::setOptionsModel\n"); if (optionsModel_) { optionsModel = optionsModel_; optionsModel->setTicker(ticker); optionsModel->setNocksSettings(nocksSettings); if (accountSummaryWidget) accountSummaryWidget->setOptionsModel(optionsModel); connect( optionsModel->guldenSettings, SIGNAL( localCurrencyChanged(QString) ), this, SLOT( updateExchangeRates() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); updateExchangeRates(); } else { optionsModel = nullptr; if (accountSummaryWidget) accountSummaryWidget->setOptionsModel(nullptr); } } void GUI::createToolBars() { LogPrint(BCLog::QT, "GUI::createToolBars\n"); if (!walletFrame) return; QToolBar* toolbar = addToolBar(tr("Tabs toolbar")); toolbar->setMovable(false); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(witnessDialogAction); toolbar->addAction(overviewAction); toolbar->addAction(viewAddressAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); overviewAction->setChecked(true); //Filler for right of menu bar. #ifndef MAC_OSX menuBarSpaceFiller = new QFrame( this ); menuBarSpaceFiller->setObjectName( "menuBarSpaceFiller" ); menuBarSpaceFiller->move(sideBarWidth, 0); menuBarSpaceFiller->setFixedSize(20000, 21); #endif //Add the 'Account bar' - vertical bar on the left accountBar = new QToolBar( QCoreApplication::translate( "toolbar", "Account toolbar" ) ); accountBar->setObjectName( "account_bar" ); accountBar->setMovable( false ); accountBar->setFixedWidth( sideBarWidth ); accountBar->setMinimumWidth( sideBarWidth ); accountBar->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Expanding ); //Horizontally lay out 'My accounts' text and 'wallet settings' button side by side. { QFrame* myAccountsFrame = new QFrame( this ); myAccountsFrame->setObjectName( "frameMyAccounts" ); QHBoxLayout* layoutMyAccounts = new QHBoxLayout; layoutMyAccounts->setObjectName("my_accounts_layout"); myAccountsFrame->setLayout(layoutMyAccounts); myAccountsFrame->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); accountBar->addWidget( myAccountsFrame ); myAccountsFrame->setContentsMargins( 0, 0, 0, 0 ); layoutMyAccounts->setSpacing(0); layoutMyAccounts->setContentsMargins( 0, 0, 0, 0 ); ClickableLabel* myAccountLabel = new ClickableLabel( myAccountsFrame ); myAccountLabel->setObjectName( "labelMyAccounts" ); myAccountLabel->setText( tr("My accounts") ); layoutMyAccounts->addWidget( myAccountLabel ); myAccountLabel->setContentsMargins( 0, 0, 0, 0 ); //Spacer to fill width { QWidget* spacerMid = new QWidget( myAccountsFrame ); spacerMid->setObjectName("my_accounts_mid_spacer"); spacerMid->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); layoutMyAccounts->addWidget( spacerMid ); } ClickableLabel* labelWalletSettings = new ClickableLabel( myAccountsFrame ); labelWalletSettings->setTextFormat( Qt::RichText ); labelWalletSettings->setText( GUIUtil::fontAwesomeRegular("\uf013") ); labelWalletSettings->setObjectName( "labelWalletSettings" ); labelWalletSettings->setCursor ( Qt::PointingHandCursor ); layoutMyAccounts->addWidget( labelWalletSettings ); labelWalletSettings->setContentsMargins( 0, 0, 0, 0 ); connect( labelWalletSettings, SIGNAL( clicked() ), this, SLOT( gotoPasswordDialog() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); } //Spacer to fill height { QScrollArea* scrollArea = new QScrollArea ( this ); scrollArea->setObjectName("account_scroll_area"); accountScrollArea = new QFrame( scrollArea ); accountScrollArea->setObjectName("account_scroll_area_frame"); scrollArea->setContentsMargins( 0, 0, 0, 0); scrollArea->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); scrollArea->setWidget(accountScrollArea); scrollArea->setWidgetResizable(true); accountScrollArea->setContentsMargins( 0, 0, 0, 0); accountScrollArea->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Maximum ); accountBar->addWidget( scrollArea ); QVBoxLayout* vbox = new QVBoxLayout(accountScrollArea); vbox->setObjectName("account_scroll_area_frame"); vbox->setSpacing(0); vbox->setContentsMargins( 0, 0, 0, 0 ); accountScrollArea->setLayout( vbox ); } ClickableLabel* addAccButton = new ClickableLabel( this ); addAccButton->setTextFormat( Qt::RichText ); addAccButton->setObjectName( "add_account_button" ); addAccButton->setText( GUIUtil::fontAwesomeRegular("\uf067 ")+tr("Add account") ); addAccButton->setCursor( Qt::PointingHandCursor ); accountBar->addWidget( addAccButton ); addToolBar( Qt::LeftToolBarArea, accountBar ); connect( addAccButton, SIGNAL( clicked() ), this, SLOT( gotoNewAccountDialog() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); //Add the 'Gulden bar' - on the left with the Gulden sign and balance guldenBar = new QToolBar( QCoreApplication::translate( "toolbar", "Overview toolbar" ) ); guldenBar->setObjectName( "gulden_bar" ); guldenBar->setFixedHeight( horizontalBarHeight ); guldenBar->setFixedWidth( sideBarWidth ); guldenBar->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); guldenBar->setMinimumWidth( sideBarWidth ); guldenBar->setMovable( false ); guldenBar->setToolButtonStyle( Qt::ToolButtonIconOnly ); guldenBar->setIconSize( QSize( 18, 18 ) ); // We place all the widgets for this action bar inside a frame of fixed width - otherwise the sizing comes out wrong { balanceContainer = new QFrame(this); balanceContainer->setObjectName("balance_container"); QHBoxLayout* layoutBalance = new QHBoxLayout(balanceContainer); layoutBalance->setObjectName("balance_layout"); balanceContainer->setLayout(layoutBalance); balanceContainer->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); balanceContainer->setContentsMargins( 0, 0, 0, 0 ); layoutBalance->setContentsMargins( 0, 0, 0, 0 ); layoutBalance->setSpacing(0); guldenBar->addWidget( balanceContainer ); //Left margin { QWidget* spacerL = new QWidget(this); spacerL->setObjectName("gulden_bar_left_margin"); spacerL->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); layoutBalance->addWidget( spacerL ); } QLabel* homeIcon = new ClickableLabel( this ); homeIcon->setText("\u0120"); layoutBalance->addWidget( homeIcon ); homeIcon->setObjectName( "home_button" ); homeIcon->setCursor( Qt::PointingHandCursor ); connect( homeIcon, SIGNAL( clicked() ), this, SLOT( gotoWebsite() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); // Use spacer to push balance label to the right { QWidget* spacerMid = new QWidget(this); spacerMid->setObjectName("layout_balance_mid_spacer"); spacerMid->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); layoutBalance->addWidget( spacerMid ); } labelBalance = new ClickableLabel( balanceContainer ); labelBalance->setObjectName( "gulden_label_balance" ); labelBalance->setText(""); labelBalance->setToolTip(""); layoutBalance->addWidget( labelBalance ); labelBalanceForex = new ClickableLabel( balanceContainer ); labelBalanceForex->setObjectName( "gulden_label_balance_forex" ); labelBalanceForex->setText(""); labelBalanceForex->setToolTip(""); labelBalanceForex->setCursor( Qt::PointingHandCursor ); connect( labelBalanceForex, SIGNAL( clicked() ), this, SLOT( showExchangeRateDialog() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); labelBalanceForex->setVisible(false); layoutBalance->addWidget( labelBalanceForex ); //Right margin { QWidget* spacerR = new QWidget(this); spacerR->setObjectName("gulden_bar_right_margin"); spacerR->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); layoutBalance->addWidget( spacerR ); } balanceContainer->setMinimumWidth( sideBarWidth ); } addToolBar( guldenBar ); //Add spacer bar spacerBarL = new QToolBar( QCoreApplication::translate( "toolbar", "Spacer toolbar" ) ); spacerBarL->setFixedHeight( horizontalBarHeight ); spacerBarL->setObjectName( "spacer_bar_left" ); spacerBarL->setMovable( false ); //Spacer to fill width { QWidget* spacerL = new QWidget(this); spacerL->setObjectName( "spacer_bar_left_spacer" ); spacerL->setMinimumWidth( 40 ); spacerL->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); spacerBarL->addWidget( spacerL ); spacerBarL->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); } addToolBar( spacerBarL ); tabsBar = findChildren<QToolBar*>( "" )[0]; //Add the main toolbar - middle (tabs) tabsBar->setFixedHeight( horizontalBarHeight ); tabsBar->setObjectName( "navigation_bar" ); tabsBar->setMovable( false ); tabsBar->setToolButtonStyle( Qt::ToolButtonTextOnly ); //Remove all the actions so we can add them again in a different order tabsBar->removeAction(historyAction); tabsBar->removeAction(overviewAction); tabsBar->removeAction(viewAddressAction); tabsBar->removeAction(receiveCoinsAction); tabsBar->removeAction(sendCoinsAction); tabsBar->removeAction(witnessDialogAction); //Setup the tab toolbar tabsBar->addAction(witnessDialogAction); tabsBar->addAction(viewAddressAction); tabsBar->addAction(receiveCoinsAction); tabsBar->addAction(sendCoinsAction); tabsBar->addAction(historyAction); passwordAction = new QAction(GUIUtil::getIconFromFontAwesomeRegularGlyph(0xf084), tr("&Password"), this); passwordAction->setObjectName("action_password"); passwordAction->setStatusTip(tr("Change wallet password")); passwordAction->setToolTip(passwordAction->statusTip()); passwordAction->setCheckable(true); passwordAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5)); tabsBar->addAction(passwordAction); backupAction = new QAction(GUIUtil::getIconFromFontAwesomeRegularGlyph(0xf0c7), tr("&Backup"), this); backupAction->setObjectName("action_backup"); backupAction->setStatusTip(tr("Backup wallet")); backupAction->setToolTip(backupAction->statusTip()); backupAction->setCheckable(true); backupAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_6)); tabsBar->addAction(backupAction); connect(passwordAction, SIGNAL(triggered()), this, SLOT(gotoPasswordDialog()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection)); connect(backupAction, SIGNAL(triggered()), this, SLOT(gotoBackupDialog()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection)); receiveCoinsAction->setChecked( true ); tabsBar->widgetForAction( historyAction )->setCursor( Qt::PointingHandCursor ); tabsBar->widgetForAction( passwordAction )->setObjectName( "password_button" ); tabsBar->widgetForAction( passwordAction )->setContentsMargins( 0, 0, 0, 0 ); tabsBar->widgetForAction( passwordAction )->setCursor( Qt::PointingHandCursor ); tabsBar->widgetForAction( backupAction )->setObjectName( "backup_button" ); tabsBar->widgetForAction( backupAction )->setContentsMargins( 0, 0, 0, 0 ); tabsBar->widgetForAction( backupAction )->setCursor( Qt::PointingHandCursor ); tabsBar->widgetForAction( viewAddressAction )->setObjectName( "view_address_button" ); tabsBar->widgetForAction( viewAddressAction )->setContentsMargins( 0, 0, 0, 0 ); tabsBar->widgetForAction( viewAddressAction )->setCursor( Qt::PointingHandCursor ); tabsBar->widgetForAction( receiveCoinsAction )->setObjectName( "receive_coins_button" ); tabsBar->widgetForAction( receiveCoinsAction )->setContentsMargins( 0, 0, 0, 0 ); tabsBar->widgetForAction( receiveCoinsAction )->setCursor( Qt::PointingHandCursor ); tabsBar->widgetForAction( sendCoinsAction )->setObjectName( "send_coins_button" ); tabsBar->widgetForAction( sendCoinsAction )->setContentsMargins( 0, 0, 0, 0 ); tabsBar->widgetForAction( sendCoinsAction )->setCursor( Qt::PointingHandCursor ); tabsBar->widgetForAction( historyAction )->setObjectName( "history_button" ); tabsBar->widgetForAction( historyAction )->setContentsMargins( 0, 0, 0, 0 ); tabsBar->widgetForAction( witnessDialogAction )->setObjectName( "witness_button" ); tabsBar->widgetForAction( witnessDialogAction )->setContentsMargins( 0, 0, 0, 0 ); tabsBar->widgetForAction( witnessDialogAction )->setCursor( Qt::PointingHandCursor ); tabsBar->setContentsMargins( 0, 0, 0, 0 ); //Spacer to fill width { QWidget* spacerR = new QWidget(this); spacerR->setObjectName("navigation_bar_right_spacer"); spacerR->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); //Delibritely large amount - to push the next toolbar as far right as possible. spacerR->setMinimumWidth( 500000 ); tabsBar->addWidget( spacerR ); tabsBar->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); } //Only show the actions we want viewAddressAction->setVisible( true ); receiveCoinsAction->setVisible( true ); sendCoinsAction->setVisible( true ); historyAction->setVisible( true ); passwordAction->setVisible( false ); backupAction->setVisible( false ); overviewAction->setVisible( false ); tabsBar->setWindowTitle( QCoreApplication::translate( "toolbar", "Navigation toolbar" ) ); addToolBar( tabsBar ); //Setup the account info bar accountInfoBar = new QToolBar( QCoreApplication::translate( "toolbar", "Account info toolbar" ) ); accountInfoBar->setFixedHeight( horizontalBarHeight ); accountInfoBar->setObjectName( "account_info_bar" ); accountInfoBar->setMovable( false ); accountInfoBar->setToolButtonStyle( Qt::ToolButtonIconOnly ); accountSummaryWidget = new AccountSummaryWidget( ticker, this ); accountSummaryWidget->setObjectName( "settings_button" ); accountSummaryWidget->setContentsMargins( 0, 0, 0, 0 ); accountInfoBar->setContentsMargins( 0, 0, 0, 0 ); accountSummaryWidget->setObjectName( "accountSummaryWidget" ); accountInfoBar->addWidget( accountSummaryWidget ); addToolBar( accountInfoBar ); connect(accountSummaryWidget, SIGNAL( requestAccountSettings() ), this, SLOT( showAccountSettings() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); connect(accountSummaryWidget, SIGNAL( requestExchangeRateDialog() ), this, SLOT( showExchangeRateDialog() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); //Add spacer bar spacerBarR = new QToolBar( QCoreApplication::translate( "toolbar", "Spacer toolbar" ) ); spacerBarR->setFixedHeight( horizontalBarHeight ); spacerBarR->setObjectName( "spacer_bar_right" ); spacerBarR->setMovable( false ); //Spacer to fill width { QWidget* spacerR = new QWidget(this); spacerR->setObjectName("spacer_bar_right_spacer"); spacerR->setMinimumWidth( 40 ); spacerR->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Preferred ); spacerBarR->addWidget( spacerR ); spacerBarR->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); } addToolBar( spacerBarR ); //Hide all toolbars and menus until UI fully loaded hideToolBars(); appMenuBar->setVisible(false); #ifndef MAC_OSX menuBarSpaceFiller->setVisible(false); #endif //Init the welcome dialog inside walletFrame welcomeScreen = new WelcomeDialog(platformStyle, this); walletFrame->walletStack->addWidget(welcomeScreen); walletFrame->walletStack->setCurrentWidget(welcomeScreen); connect(welcomeScreen, SIGNAL( loadWallet() ), walletFrame, SIGNAL( loadWallet() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection)); } void GUI::hideToolBars() { LogPrint(BCLog::QT, "GUI::hideToolBars\n"); if (accountBar) accountBar->setVisible(false); if (guldenBar) guldenBar->setVisible(false); if (spacerBarL) spacerBarL->setVisible(false); if (tabsBar) tabsBar->setVisible(false); if (spacerBarR) spacerBarR->setVisible(false); if (accountInfoBar) accountInfoBar->setVisible(false); if (statusToolBar) { statusToolBar->setVisible(false); } } void GUI::showToolBars() { LogPrint(BCLog::QT, "GUI::showToolBars\n"); welcomeScreen = NULL; if (appMenuBar) appMenuBar->setStyleSheet(""); if (accountBar) accountBar->setVisible(true); if (guldenBar) guldenBar->setVisible(true); if (spacerBarL) spacerBarL->setVisible(true); if (tabsBar) tabsBar->setVisible(true); if (spacerBarR) spacerBarR->setVisible(true); if (accountInfoBar) accountInfoBar->setVisible(true); if (statusToolBar) { bool visibility = (progressBarLabel ? progressBarLabel->isVisible() : false); statusToolBar->setVisible(visibility); } } void GUI::doApplyStyleSheet() { LogPrint(BCLog::QT, "GUI::doApplyStyleSheet\n"); if(!enableWallet || !enableFullUI) return; //Load our own QSS stylesheet template for 'whole app' QFile styleFile( ":Gulden/qss" ); styleFile.open( QFile::ReadOnly ); //Replace variables in the 'template' with actual values QString style( styleFile.readAll() ); style.replace( "ACCENT_COLOR_1", QString(ACCENT_COLOR_1) ); style.replace( "ACCENT_COLOR_2", QString(ACCENT_COLOR_2) ); style.replace( "TEXT_COLOR_1", QString(TEXT_COLOR_1) ); style.replace( "COLOR_VALIDATION_FAILED", QString(COLOR_VALIDATION_FAILED) ); if (sideBarWidth == sideBarWidthExtended) { style.replace( "SIDE_BAR_WIDTH", SIDE_BAR_WIDTH_EXTENDED ); } else { style.replace( "SIDE_BAR_WIDTH", SIDE_BAR_WIDTH ); } style.replace( "LOGO_FONT_SIZE", QString(LOGO_FONT_SIZE) ); style.replace( "TOOLBAR_FONT_SIZE", QString(TOOLBAR_FONT_SIZE) ); style.replace( "BUTTON_FONT_SIZE", QString(BUTTON_FONT_SIZE) ); style.replace( "SMALL_BUTTON_FONT_SIZE", QString(SMALL_BUTTON_FONT_SIZE) ); style.replace( "MINOR_LABEL_FONT_SIZE", QString(MINOR_LABEL_FONT_SIZE) ); //Apply the final QSS - after making the 'template substitutions' //NB! This should happen last after all object IDs etc. are set. setStyleSheet( style ); } void GUI::resizeToolBarsGulden() { LogPrint(BCLog::QT, "GUI::resizeToolBarsGulden\n"); //Filler for right of menu bar. #ifndef MAC_OSX menuBarSpaceFiller->move(sideBarWidth, 0); #endif accountBar->setFixedWidth( sideBarWidth ); accountBar->setMinimumWidth( sideBarWidth ); guldenBar->setFixedWidth( sideBarWidth ); guldenBar->setMinimumWidth( sideBarWidth ); balanceContainer->setMinimumWidth( sideBarWidth ); } void GUI::doPostInit() { LogPrint(BCLog::QT, "GUI::doPostInit\n"); //Fonts // We 'abuse' the translation system here to allow different 'font stacks' for different languages. //QString MAIN_FONTSTACK = QObject::tr("Arial, 'Helvetica Neue', Helvetica, sans-serif"); appMenuBar->setStyleSheet("QMenuBar{background-color: rgba(255, 255, 255, 0%);} QMenu{background-color: #f3f4f6; border: 1px solid #999; color: black;} QMenu::item { color: black; } QMenu::item:disabled {color: #999;} QMenu::separator{background-color: #999; height: 1px; margin-left: 10px; margin-right: 5px;}"); { // Qt status bar sucks - it is impossible to style nicely, so we just rip the thing out and use a toolbar instead. statusBar()->setVisible(false); //Allow us to target the progress label for easy styling //statusBar()->removeWidget(progressBarLabel); //statusBar()->removeWidget(progressBar); //statusBar()->removeWidget(frameBlocks); //Add a spacer to the frameBlocks so that we can force them to expand to same size as the progress text (Needed for proper centering of progress bar) /*QFrame* frameBlocksSpacerL = new QFrame(frameBlocks); frameBlocksSpacerL->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); frameBlocksSpacerL->setContentsMargins( 0, 0, 0, 0); ((QHBoxLayout*)frameBlocks->layout())->insertWidget(0, frameBlocksSpacerL);*/ frameBlocks->layout()->setContentsMargins( 0, 0, 0, 0 ); frameBlocks->layout()->setSpacing( 0 ); //Hide some of the 'task items' we don't need //labelBlocksIcon->setVisible( false ); //Status bar { statusToolBar = new QToolBar( QCoreApplication::translate( "toolbar", "Status toolbar" ), this); statusToolBar->setObjectName( "status_bar" ); statusToolBar->setMovable( false ); QFrame* statusBarStatusArea = new QFrame(statusToolBar); statusBarStatusArea->setObjectName("status_bar_status_area"); statusBarStatusArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); statusBarStatusArea->setContentsMargins( 0, 0, 0, 0); QHBoxLayout* statusBarStatusAreaLayout = new QHBoxLayout(); statusBarStatusArea->setLayout(statusBarStatusAreaLayout); statusBarStatusAreaLayout->setSpacing(0); statusBarStatusAreaLayout->setContentsMargins( 0, 0, 0, 0 ); statusToolBar->addWidget(statusBarStatusArea); statusBarStatusAreaLayout->addWidget(progressBarLabel); QFrame* statusProgressSpacerL = new QFrame(statusToolBar); statusProgressSpacerL->setObjectName("progress_bar_spacer_left"); statusProgressSpacerL->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); statusProgressSpacerL->setContentsMargins( 0, 0, 0, 0); statusToolBar->addWidget(statusProgressSpacerL); QFrame* progressBarWrapper = new QFrame(statusToolBar); progressBarWrapper->setObjectName("progress_bar"); progressBarWrapper->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Preferred); progressBarWrapper->setContentsMargins( 0, 0, 0, 0); QHBoxLayout* layoutProgressBarWrapper = new QHBoxLayout; progressBarWrapper->setLayout(layoutProgressBarWrapper); layoutProgressBarWrapper->setSpacing(0); layoutProgressBarWrapper->setContentsMargins( 0, 0, 0, 0 ); layoutProgressBarWrapper->addWidget(progressBar); statusToolBar->addWidget(progressBarWrapper); progressBar->setVisible(false); QFrame* statusProgressSpacerR = new QFrame(statusToolBar); statusProgressSpacerR->setObjectName("progress_bar_spacer_right"); statusProgressSpacerR->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); statusProgressSpacerR->setContentsMargins( 0, 0, 0, 0); statusToolBar->addWidget(statusProgressSpacerR); frameBlocks->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred ); frameBlocks->setObjectName("status_bar_frame_blocks"); //Use spacer to push all the icons to the right QFrame* frameBlocksSpacerL = new QFrame(frameBlocks); frameBlocksSpacerL->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); frameBlocksSpacerL->setContentsMargins( 0, 0, 0, 0); ((QHBoxLayout*)frameBlocks->layout())->insertWidget(0, frameBlocksSpacerL, 1); statusToolBar->addWidget(frameBlocks); //Right margin to match rest of UI QFrame* frameBlocksSpacerR = new QFrame(statusToolBar); frameBlocksSpacerR->setObjectName("status_bar_right_margin"); frameBlocksSpacerR->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); frameBlocksSpacerR->setContentsMargins( 0, 0, 0, 0); statusToolBar->addWidget(frameBlocksSpacerR); //Use our own styling - clear the styling that is already applied progressBar->setStyleSheet(""); //Hide text we don't want it as it looks cluttered. progressBar->setTextVisible(false); progressBar->setCursor(Qt::PointingHandCursor); addToolBar( Qt::BottomToolBarArea, statusToolBar ); statusToolBar->setVisible(false); } } backupWalletAction->setIconText( QCoreApplication::translate( "toolbar", "Backup" ) ); //Change shortcut keys because we have hidden overview pane and changed tab orders overviewAction->setShortcut( QKeySequence( Qt::ALT + Qt::Key_0 ) ); viewAddressAction->setShortcut( QKeySequence( Qt::ALT + Qt::Key_0 ) ); sendCoinsAction->setShortcut( QKeySequence( Qt::ALT + Qt::Key_2 ) ); receiveCoinsAction->setShortcut( QKeySequence( Qt::ALT + Qt::Key_3 ) ); historyAction->setShortcut( QKeySequence( Qt::ALT + Qt::Key_1 ) ); doApplyStyleSheet(); //Force font antialiasing QFont f = QApplication::font(); f.setStyleStrategy( QFont::PreferAntialias ); QApplication::setFont( f ); openAction->setVisible(false); setContextMenuPolicy(Qt::NoContextMenu); setMinimumSize(860, 520); disconnect(backupWalletAction, SIGNAL(triggered()), 0, 0); connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(gotoBackupDialog()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection)); encryptWalletAction->setCheckable(false); disconnect(encryptWalletAction, SIGNAL(triggered()), 0, 0); connect(encryptWalletAction, SIGNAL(triggered()), this, SLOT(gotoPasswordDialog()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection)); disconnect(changePassphraseAction, SIGNAL(triggered()), 0, 0); connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(gotoPasswordDialog()), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection)); if (labelBalance) labelBalance->setVisible(false); } void GUI::hideProgressBarLabel() { LogPrint(BCLog::QT, "GUI::hideProgressBarLabel\n"); if (progressBarLabel) { progressBarLabel->setText(""); progressBarLabel->setVisible(false); } if(statusToolBar) { statusToolBar->setVisible(false); } } void GUI::showProgressBarLabel() { LogPrint(BCLog::QT, "GUI::showProgressBarLabel\n"); if (progressBarLabel) progressBarLabel->setVisible(true); if(statusToolBar) { statusToolBar->setVisible(true); } } void GUI::hideBalances() { LogPrint(BCLog::QT, "GUI::hideBalances\n"); if (!labelBalance) return; labelBalance->setVisible(false); labelBalanceForex->setVisible(false); accountSummaryWidget->hideBalances(); } void GUI::showBalances() { LogPrint(BCLog::QT, "GUI::showBalances\n"); if (!labelBalance) return; labelBalance->setVisible(true); // Give forex label a chance to update if appropriate. updateExchangeRates(); accountSummaryWidget->showBalances(); } bool GUI::welcomeScreenIsVisible() { return welcomeScreen != NULL; } QDialog* GUI::createDialog(QWidget* parent, QString message, QString confirmLabel, QString cancelLabel, int minWidth, int minHeight, QString objectName) { LogPrint(BCLog::QT, "GUI::createDialog\n"); QDialog* d = new QDialog(parent); d->setWindowFlags(Qt::Dialog); d->setMinimumSize(QSize(minWidth, minHeight)); QVBoxLayout* vbox = new QVBoxLayout(); vbox->setSpacing(0); vbox->setContentsMargins( 0, 0, 0, 0 ); if (!objectName.isEmpty()) d->setObjectName(objectName); QLabel* labelDialogMessage = new QLabel(d); labelDialogMessage->setText(message); labelDialogMessage->setObjectName("labelDialogMessage"); labelDialogMessage->setContentsMargins( 0, 0, 0, 0 ); labelDialogMessage->setIndent(0); labelDialogMessage->setWordWrap(true); vbox->addWidget(labelDialogMessage); QWidget* spacer = new QWidget(d); spacer->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); vbox->addWidget(spacer); QFrame* horizontalLine = new QFrame(d); horizontalLine->setFrameStyle(QFrame::HLine); horizontalLine->setFixedHeight(1); horizontalLine->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); horizontalLine->setStyleSheet(GULDEN_DIALOG_HLINE_STYLE); vbox->addWidget(horizontalLine); QDialogButtonBox::StandardButtons buttons; if (!confirmLabel.isEmpty()) { buttons |= QDialogButtonBox::Ok; } if (!cancelLabel.isEmpty()) { // We use reset button because it shows on the left where we want it. buttons |= QDialogButtonBox::Reset; } QDialogButtonBox* buttonBox = new QDialogButtonBox(buttons, d); vbox->addWidget(buttonBox); buttonBox->setContentsMargins( 0, 0, 0, 0 ); if(!confirmLabel.isEmpty()) { buttonBox->button(QDialogButtonBox::Ok)->setObjectName("dialogConfirmButton"); buttonBox->button(QDialogButtonBox::Ok)->setText(confirmLabel); buttonBox->button(QDialogButtonBox::Ok)->setCursor(Qt::PointingHandCursor); buttonBox->button(QDialogButtonBox::Ok)->setStyleSheet(GULDEN_DIALOG_CONFIRM_BUTTON_STYLE); QObject::connect(buttonBox, SIGNAL(accepted()), d, SLOT(accept())); } if (!cancelLabel.isEmpty()) { buttonBox->button(QDialogButtonBox::Reset)->setObjectName("dialogCancelButton"); buttonBox->button(QDialogButtonBox::Reset)->setText(cancelLabel); buttonBox->button(QDialogButtonBox::Reset)->setCursor(Qt::PointingHandCursor); buttonBox->button(QDialogButtonBox::Reset)->setStyleSheet(GULDEN_DIALOG_CANCEL_BUTTON_STYLE); QObject::connect(buttonBox->button(QDialogButtonBox::Reset), SIGNAL(clicked()), d, SLOT(reject())); } d->setLayout(vbox); return d; } const QString ELLIPSIS("\u2026"); QString limitString(const QString& string, int maxLength) { if (string.length() <= maxLength) return string; float spacePerPart = (maxLength - ELLIPSIS.length()) / 2.0; auto beforeEllipsis = string.left(std::ceil(spacePerPart)); auto afterEllipsis = string.right(std::floor(spacePerPart)); return beforeEllipsis + GUIUtil::fontAwesomeLight(ELLIPSIS) + afterEllipsis; } static QString superscriptSpan(const QString& sText) { return QString("<span style='font-size: 8px;'>%1</span>").arg(sText); } static QString colourSpan(QString sColour, const QString& sText) { return QString("<span style='color: %1;'>%2</span>").arg(sColour).arg(sText); } static QString getAccountLabel(CAccount* account) { QString accountName = QString::fromStdString( account->getLabel() ); accountName = limitString(accountName, 26); QString accountNamePrefixIndicator; //Large prefix icon (e.g. building for witness, credit card for normal account) QString accountNamePrefixIndicatorQualifier; //small superscript prefix icon in addition to large icon (e.g. warning icon for warning condition, lock for locked witness, eye for read only account) if (account->IsReadOnly()) { accountNamePrefixIndicatorQualifier = GUIUtil::fontAwesomeLight("\uf06e"); // Eye } if (account->IsMobi()) { accountNamePrefixIndicator = GUIUtil::fontAwesomeLight("\uf10b"); // Mobile phone } else if (account->m_Type == ImportedPrivateKeyAccount) { accountNamePrefixIndicator = GUIUtil::fontAwesomeLight("\uf084"); // Key } else if (account->IsPoW2Witness()) { accountNamePrefixIndicator = GUIUtil::fontAwesomeLight("\uf19c"); // Institutional building if (account->m_Type == WitnessOnlyWitnessAccount) accountNamePrefixIndicator = GUIUtil::fontAwesomeLight("\uf06e"); // Eye switch (account->GetWarningState()) { case AccountStatus::WitnessEmpty: break; case AccountStatus::Default: accountNamePrefixIndicatorQualifier += GUIUtil::fontAwesomeSolid("\uf023"); break; // Lock case AccountStatus::WitnessPending: accountNamePrefixIndicatorQualifier += GUIUtil::fontAwesomeSolid("\uf251"); break; // Hourglass case AccountStatus::WitnessExpired: accountNamePrefixIndicatorQualifier += colourSpan("#c97676", GUIUtil::fontAwesomeSolid("\uf12a")); break; // Exclamation case AccountStatus::WitnessEnded: accountNamePrefixIndicatorQualifier += GUIUtil::fontAwesomeSolid("\uf11e"); break; // Checkered flag } } else if (!account->IsHD()) { accountNamePrefixIndicator = GUIUtil::fontAwesomeLight("\uf187"); // Archival box } else { accountNamePrefixIndicator = GUIUtil::fontAwesomeLight("\uf09d"); // Credit card } QString accountNamePrefix = QString("<table cellspacing=0 padding=0><tr><td>%1</td><td valign=top>%2</td><table>").arg(accountNamePrefixIndicator).arg(superscriptSpan(accountNamePrefixIndicatorQualifier)); accountName = QString("<table cellspacing=0 padding=0><tr><td width=28 align=left>%1</td><td width=2></td><td>%2</td></tr></table>").arg(accountNamePrefix).arg(accountName); return accountName; } void GUI::refreshTabVisibilities() { LogPrint(BCLog::QT, "GUI::refreshTabVisibilities\n"); if (pactiveWallet->getActiveAccount()->IsPoW2Witness()) { viewAddressAction->setVisible(true); receiveCoinsAction->setVisible(false); sendCoinsAction->setVisible(false); witnessDialogAction->setVisible(true); if ( walletFrame->currentWalletView()->currentWidget() == (QWidget*)walletFrame->currentWalletView()->receiveCoinsPage || walletFrame->currentWalletView()->currentWidget() == (QWidget*)walletFrame->currentWalletView()->sendCoinsPage ) { showWitnessDialog(); } } else { viewAddressAction->setVisible(false); receiveCoinsAction->setVisible(true); sendCoinsAction->setVisible(true); witnessDialogAction->setVisible(false); //Required here because when we open wallet and it is already on a read only account restoreCachedWidgetIfNeeded is not called. if (pactiveWallet->getActiveAccount()->IsReadOnly()) { sendCoinsAction->setVisible( false ); } if (walletFrame->currentWalletView()->currentWidget() == (QWidget*)walletFrame->currentWalletView()->witnessDialogPage) { gotoReceiveCoinsPage(); } } } static std::map<QString, CAccount*, std::function<bool(const QString&, const QString&)>> getSortedAccounts() { QCollator collateAccountsNumerically; collateAccountsNumerically.setNumericMode(true); std::function<bool(const QString&, const QString&)> cmpAccounts = [collateAccountsNumerically](const QString& s1, const QString& s2){ return collateAccountsNumerically.compare(s1, s2) < 0; }; std::map<QString, CAccount*, std::function<bool(const QString&, const QString&)>> sortedAccounts(cmpAccounts); { for ( const auto& accountPair : pactiveWallet->mapAccounts ) { if (accountPair.second->m_State == AccountState::Normal || (fShowChildAccountsSeperately && accountPair.second->m_State == AccountState::ShadowChild) ) sortedAccounts[QString::fromStdString(accountPair.second->getLabel())] = accountPair.second; } } return sortedAccounts; } void GUI::refreshAccountControls() { LogPrint(BCLog::QT, "GUI::refreshAccountControls\n"); refreshTabVisibilities(); if (pactiveWallet) { //Disable layout to prevent updating to changes immediately accountScrollArea->layout()->setEnabled(false); { // Get an ordered list of old account labels. std::vector<ClickableLabel*> allLabels; for (int32_t i=0; i<accountScrollArea->layout()->count(); ++i) { allLabels.push_back(dynamic_cast<ClickableLabel*>((accountScrollArea->layout()->itemAt(i)->widget()))); } m_accountMap.clear(); // Sort the accounts. auto sortedAccounts = getSortedAccounts(); { //NB! Mutex scope here is important to avoid deadlock inside setActiveAccountButton LOCK(pactiveWallet->cs_wallet); // Update to the sorted list uint32_t nCount = 0; for (const auto& sortedIter : sortedAccounts) { ClickableLabel* accLabel = nullptr; QString label = getAccountLabel(sortedIter.second); if (allLabels.size() >= nCount+1) { accLabel = allLabels[nCount]; accLabel->setText( label ); } else { accLabel = createAccountButton( label ); accountScrollArea->layout()->addWidget( accLabel ); } m_accountMap[accLabel] = sortedIter.second; if (!walletFrame->currentWalletView()->walletModel) return; if (sortedIter.second->getUUID() == walletFrame->currentWalletView()->walletModel->getActiveAccount()->getUUID()) setAccountLabelSelected(accLabel); else setAccountLabelUnselected(accLabel); ++nCount; } // Remove any excess widgets that are still in UI if required. for (;nCount < allLabels.size();++nCount) { accountScrollArea->layout()->removeWidget(allLabels[nCount]); } } } // Force layout to update now that all the changes are made. accountScrollArea->layout()->setEnabled(true); } } ClickableLabel* GUI::createAccountButton( const QString& accountName ) { ClickableLabel* newAccountButton = new ClickableLabel( this ); newAccountButton->setObjectName(QString("account_selection_button_%1").arg(rand())); newAccountButton->setTextFormat( Qt::RichText ); newAccountButton->setText( accountName ); newAccountButton->setCursor( Qt::PointingHandCursor ); connect( newAccountButton, SIGNAL( clicked() ), this, SLOT( accountButtonPressed() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); return newAccountButton; } void GUI::setActiveAccountButton( ClickableLabel* activeButton ) { LogPrint(BCLog::QT, "GUI::setActiveAccountButton\n"); for ( const auto & button : accountBar->findChildren<ClickableLabel*>( "" ) ) { setAccountLabelUnselected(button); } setAccountLabelSelected(activeButton); // Update the account if ( walletFrame->currentWalletView() ) { if ( walletFrame->currentWalletView()->receiveCoinsPage ) { if (!walletFrame->currentWalletView()->walletModel) return; accountSummaryWidget->setActiveAccount( m_accountMap[activeButton] ); walletFrame->currentWalletView()->walletModel->setActiveAccount( m_accountMap[activeButton] ); updateAccount(m_accountMap[activeButton]); } } } void GUI::updateAccount(CAccount* account) { LogPrint(BCLog::QT, "GUI::updateAccount\n"); LOCK2(cs_main, pactiveWallet->cs_wallet); if (!walletFrame) return; if (!walletFrame->currentWalletView()) return; walletFrame->currentWalletView()->viewAddressPage->updateAddress(""); if (account->IsPoW2Witness()) { if (!walletFrame->currentWalletView()->viewAddressPage) return; if (!walletFrame->currentWalletView()->walletModel) return; //fixme: (2.1) - Look into improving performance here, also better way to handle multiple addresses? std::unique_ptr<TransactionFilterProxy> filter; filter.reset(new TransactionFilterProxy); filter->setSourceModel(walletFrame->currentWalletView()->walletModel->getTransactionTableModel()); filter->setDynamicSortFilter(true); filter->setSortRole(Qt::EditRole); filter->setShowInactive(false); filter->sort(TransactionTableModel::Date, Qt::DescendingOrder); filter->setAccountFilter(account); int rows = filter->rowCount(); for (int row = 0; row < rows; ++row) { QModelIndex index = filter->index(row, 0); int nType = filter->data(index, TransactionTableModel::TypeRole).toInt(); if ( (nType == TransactionRecord::WitnessFundRecv) || (nType == TransactionRecord::WitnessRenew) ) { walletFrame->currentWalletView()->viewAddressPage->updateAddress(filter->data(index, TransactionTableModel::AddressRole).toString()); return; } } } else { if (!walletFrame->currentWalletView()->receiveCoinsPage) return; CReserveKeyOrScript* receiveAddress = new CReserveKeyOrScript(pactiveWallet, account, KEYCHAIN_EXTERNAL); CPubKey pubKey; if (receiveAddress->GetReservedKey(pubKey)) { CKeyID keyID = pubKey.GetID(); walletFrame->currentWalletView()->receiveCoinsPage->updateAddress( QString::fromStdString(CGuldenAddress(keyID).ToString()) ); } else { LogPrint(BCLog::ALL, "Keypool exhausted for account.\n"); walletFrame->currentWalletView()->receiveCoinsPage->updateAddress( "error" ); } walletFrame->currentWalletView()->receiveCoinsPage->setActiveAccount( account ); receiveAddress->ReturnKey(); delete receiveAddress; } } void GUI::balanceChanged() { LogPrint(BCLog::QT, "GUI::balanceChanged\n"); if (!walletFrame || !walletFrame->currentWalletView() || !walletFrame->currentWalletView()->walletModel) return; // Force receive Qr code to update on balance change. updateAccount( walletFrame->currentWalletView()->walletModel->getActiveAccount() ); } void GUI::accountNameChanged(CAccount* account) { LogPrint(BCLog::QT, "GUI::accountNameChanged\n"); //Disable layout to prevent updating to changes immediately accountScrollArea->layout()->setEnabled(false); { accountDeleted(account); ClickableLabel* added = accountAddedHelper(account); if (!walletFrame || !walletFrame->currentWalletView() || !walletFrame->currentWalletView()->walletModel) return; if (account->getUUID() == walletFrame->currentWalletView()->walletModel->getActiveAccount()->getUUID()) setAccountLabelSelected(added); } // Force layout to update now that all the changes are made. accountScrollArea->layout()->setEnabled(true); } void GUI::accountWarningChanged(CAccount* account) { LogPrint(BCLog::QT, "GUI::accountWarningChanged\n"); if (!account) return; boost::uuids::uuid searchUUID = account->getUUID(); for (auto& iter : m_accountMap) { if (iter.second->getUUID() == searchUUID) { iter.first->setText( getAccountLabel(account) ); break; } } } void GUI::activeAccountChanged(CAccount* account) { LogPrint(BCLog::QT, "GUI::activeAccountChanged\n"); if (accountSummaryWidget) accountSummaryWidget->setActiveAccount(account); // Force receive Qr code to update on balance change. updateAccount( walletFrame->currentWalletView()->walletModel->getActiveAccount() ); refreshTabVisibilities(); if ( walletFrame) walletFrame->currentWalletView()->witnessDialogPage->update(); //Update account name 'in place' in account list bool haveAccount=false; if (pactiveWallet) { for ( const auto& accountPair : m_accountMap ) { if (accountPair.second == account) { haveAccount = true; if (!accountPair.first->isChecked()) { setAccountLabelSelected(accountPair.first); } accountPair.first->setText( getAccountLabel(account) ); } else if (accountPair.first->isChecked()) { setAccountLabelUnselected(accountPair.first); } } } if(!haveAccount) { refreshAccountControls(); } } ClickableLabel* GUI::accountAddedHelper(CAccount* addedAccount) { if (pactiveWallet) { LOCK(pactiveWallet->cs_wallet); QString addedAccountLabel = QString::fromStdString(addedAccount->getLabel()); auto sortedAccounts = getSortedAccounts(); if (sortedAccounts.find(addedAccountLabel) != sortedAccounts.end()) { for (const auto& [accountLabel, account] : m_accountMap) { if (account->getUUID() == addedAccount->getUUID()) { return accountLabel; } } } sortedAccounts[addedAccountLabel] = addedAccount; uint32_t nCount = 0; for (const auto& [sortedLabel, sortedAccount] : sortedAccounts) { (unused)sortedLabel; if (sortedAccount->getUUID() == addedAccount->getUUID()) { QString decoratedAccountlabel = getAccountLabel(sortedAccount); ClickableLabel* accLabel = createAccountButton(decoratedAccountlabel); m_accountMap[accLabel] = sortedAccount; ((QVBoxLayout*)accountScrollArea->layout())->insertWidget(nCount, accLabel); return accLabel; } nCount++; } } return nullptr; } void GUI::accountAdded(CAccount* addedAccount) { LogPrint(BCLog::QT, "GUI::accountAdded\n"); if (!addedAccount || (addedAccount->m_State != AccountState::Normal && !(fShowChildAccountsSeperately && addedAccount->m_State == AccountState::ShadowChild)) ) return; //Disable layout to prevent updating to changes immediately accountScrollArea->layout()->setEnabled(false); { if (!walletFrame || !walletFrame->currentWalletView() || !walletFrame->currentWalletView()->walletModel) return; ClickableLabel* added = accountAddedHelper(addedAccount); if (addedAccount->getUUID() == walletFrame->currentWalletView()->walletModel->getActiveAccount()->getUUID()) setAccountLabelSelected(added); } // Force layout to update now that all the changes are made. accountScrollArea->layout()->setEnabled(true); } void GUI::accountDeleted(CAccount* account) { LogPrint(BCLog::QT, "GUI::accountDeleted\n"); if (!account) return; boost::uuids::uuid searchUUID = account->getUUID(); for (auto iter = m_accountMap.begin(); iter != m_accountMap.end(); ++iter) { if (searchUUID == iter->second->getUUID()) { accountScrollArea->layout()->removeWidget(iter->first); iter->first->deleteLater(); m_accountMap.erase(iter); break; } } } void GUI::accountButtonPressed() { QObject* sender = this->sender(); ClickableLabel* accButton = qobject_cast<ClickableLabel*>( sender ); setActiveAccountButton( accButton ); restoreCachedWidgetIfNeeded(); } void GUI::promptImportPrivKey(const QString accountName) { LogPrint(BCLog::QT, "GUI::promptImportPrivKey\n"); std::string adjustedAccountName = accountName.toStdString(); if (adjustedAccountName.empty()) adjustedAccountName = tr("Imported key").toStdString(); ImportPrivKeyDialog dlg(this); if (dlg.exec()) { // Temporarily unlock for account generation. SecureString encodedPrivKey = dlg.getPrivKey(); std::function<void (void)> successCallback = [=](){ pactiveWallet->importPrivKey(encodedPrivKey, adjustedAccountName); }; if (pactiveWallet->IsLocked()) { uiInterface.RequestUnlockWithCallback(pactiveWallet, _("Wallet unlock required to import private key"), successCallback); } else { successCallback(); } return; } } void GUI::promptImportWitnessOnlyAccount(QString accountName) { LogPrint(BCLog::QT, "GUI::promptImportWitnessOnlyAccount\n"); if (accountName.isEmpty()) accountName = tr("Imported witness"); ImportWitnessDialog dlg(this); if (dlg.exec()) { // Temporarily unlock for account generation. SecureString witnessURL = dlg.getWitnessURL(); std::function<void (void)> successCallback = [=](){pactiveWallet->importWitnessOnlyAccountFromURL(witnessURL, accountName.toStdString());}; if (pactiveWallet->IsLocked()) { uiInterface.RequestUnlockWithCallback(pactiveWallet, _("Wallet unlock required to import witness-only account"), successCallback); } else { successCallback(); } } } void GUI::promptRescan() { LogPrint(BCLog::QT, "GUI::promptRescan\n"); // Whenever a key is imported, we need to scan the whole chain - do so now pactiveWallet->nTimeFirstKey = 1; boost::thread t(rescanThread); // thread runs free } void GUI::gotoWebsite() { LogPrint(BCLog::QT, "GUI::gotoWebsite\n"); QDesktopServices::openUrl( QUrl( "http://www.Gulden.com/" ) ); } void GUI::restoreCachedWidgetIfNeeded() { LogPrint(BCLog::QT, "GUI::restoreCachedWidgetIfNeeded\n"); bool stateReceiveCoinsAction = true; bool stateSendCoinsAction = true; walletFrame->currentWalletView()->sendCoinsPage->update(); walletFrame->currentWalletView()->witnessDialogPage->update(); if (pactiveWallet->getActiveAccount()->IsReadOnly()) { stateSendCoinsAction = false; if ( walletFrame->currentWalletView()->currentWidget() == (QWidget*)walletFrame->currentWalletView()->sendCoinsPage ) { gotoReceiveCoinsPage(); } } if (pactiveWallet->getActiveAccount()->IsPoW2Witness()) { witnessDialogAction->setVisible( true ); stateReceiveCoinsAction = false; stateSendCoinsAction = false; if ( walletFrame->currentWalletView()->currentWidget() == (QWidget*)walletFrame->currentWalletView()->receiveCoinsPage || walletFrame->currentWalletView()->currentWidget() == (QWidget*)walletFrame->currentWalletView()->sendCoinsPage ) { showWitnessDialog(); } } else { if (cacheCurrentWidget && cacheCurrentWidget == (QWidget*)walletFrame->currentWalletView()->witnessDialogPage) cacheCurrentWidget = nullptr; witnessDialogAction->setVisible( false ); if ( walletFrame->currentWalletView()->currentWidget() == (QWidget*)walletFrame->currentWalletView()->witnessDialogPage ) { gotoReceiveCoinsPage(); } } historyAction->setVisible( true ); passwordAction->setVisible( false ); backupAction->setVisible( false ); overviewAction->setVisible( true ); if (dialogPasswordModify) { walletFrame->currentWalletView()->removeWidget( dialogPasswordModify ); dialogPasswordModify->deleteLater(); dialogPasswordModify = NULL; } if (dialogBackup) { walletFrame->currentWalletView()->removeWidget( dialogBackup ); dialogBackup->deleteLater(); dialogBackup = NULL; } if (dialogNewAccount) { walletFrame->currentWalletView()->removeWidget( dialogNewAccount ); dialogNewAccount->deleteLater(); dialogNewAccount = NULL; } if (dialogAccountSettings) { walletFrame->currentWalletView()->removeWidget( dialogAccountSettings ); dialogAccountSettings->deleteLater(); dialogAccountSettings = NULL; } if (cacheCurrentWidget) { walletFrame->currentWalletView()->setCurrentWidget( cacheCurrentWidget ); cacheCurrentWidget = NULL; } if (viewAddressAction) receiveCoinsAction->setVisible(!stateReceiveCoinsAction); if (receiveCoinsAction) receiveCoinsAction->setVisible( stateReceiveCoinsAction ); if (sendCoinsAction) sendCoinsAction->setVisible( stateSendCoinsAction ); } void GUI::gotoNewAccountDialog() { LogPrint(BCLog::QT, "GUI::gotoNewAccountDialog\n"); if ( walletFrame ) { restoreCachedWidgetIfNeeded(); dialogNewAccount = new NewAccountDialog( platformStyle, walletFrame->currentWalletView(), walletFrame->currentWalletView()->walletModel); connect( dialogNewAccount, SIGNAL( cancel() ), this, SLOT( cancelNewAccountDialog() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); connect( dialogNewAccount, SIGNAL( accountAdded() ), this, SLOT( acceptNewAccount() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); connect( dialogNewAccount, SIGNAL( addAccountMobile() ), this, SLOT( acceptNewAccountMobile() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); cacheCurrentWidget = walletFrame->currentWalletView()->currentWidget(); walletFrame->currentWalletView()->addWidget( dialogNewAccount ); walletFrame->currentWalletView()->setCurrentWidget( dialogNewAccount ); } } void GUI::gotoPasswordDialog() { LogPrint(BCLog::QT, "GUI::gotoPasswordDialog\n"); if ( walletFrame ) { restoreCachedWidgetIfNeeded(); passwordAction->setVisible( true ); backupAction->setVisible( true ); passwordAction->setChecked(true); backupAction->setChecked(false); receiveCoinsAction->setVisible( false ); sendCoinsAction->setVisible( false ); historyAction->setVisible( false ); overviewAction->setVisible( false ); witnessDialogAction->setVisible( false ); dialogPasswordModify = new PasswordModifyDialog( platformStyle, walletFrame->currentWalletView() ); connect( dialogPasswordModify, SIGNAL( dismiss() ), this, SLOT( dismissPasswordDialog() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); cacheCurrentWidget = walletFrame->currentWalletView()->currentWidget(); walletFrame->currentWalletView()->addWidget( dialogPasswordModify ); walletFrame->currentWalletView()->setCurrentWidget( dialogPasswordModify ); } } void GUI::gotoBackupDialog() { LogPrint(BCLog::QT, "GUI::gotoBackupDialog\n"); if ( walletFrame ) { restoreCachedWidgetIfNeeded(); passwordAction->setVisible( true ); backupAction->setVisible( true ); passwordAction->setChecked(false); backupAction->setChecked(true); receiveCoinsAction->setVisible( false ); sendCoinsAction->setVisible( false ); historyAction->setVisible( false ); overviewAction->setVisible( false ); witnessDialogAction->setVisible( false ); dialogBackup = new BackupDialog( platformStyle, walletFrame->currentWalletView(), walletFrame->currentWalletView()->walletModel); connect( dialogBackup, SIGNAL( saveBackupFile() ), walletFrame, SLOT( backupWallet() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); connect( dialogBackup, SIGNAL( dismiss() ), this, SLOT( dismissBackupDialog() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); cacheCurrentWidget = walletFrame->currentWalletView()->currentWidget(); walletFrame->currentWalletView()->addWidget( dialogBackup ); walletFrame->currentWalletView()->setCurrentWidget( dialogBackup ); } } void GUI::dismissBackupDialog() { LogPrint(BCLog::QT, "GUI::dismissBackupDialog\n"); restoreCachedWidgetIfNeeded(); } void GUI::dismissPasswordDialog() { LogPrint(BCLog::QT, "GUI::dismissPasswordDialog\n"); restoreCachedWidgetIfNeeded(); } void GUI::cancelNewAccountDialog() { LogPrint(BCLog::QT, "GUI::cancelNewAccountDialog\n"); restoreCachedWidgetIfNeeded(); } void GUI::acceptNewAccount() { LogPrint(BCLog::QT, "GUI::acceptNewAccount\n"); const auto newAccountType = dialogNewAccount->getAccountType(); if (newAccountType == NewAccountType::ImportKey) { gotoReceiveCoinsPage(); promptImportPrivKey(dialogNewAccount->getAccountName()); return; } else if(newAccountType == NewAccountType::WitnessOnly) { gotoReceiveCoinsPage(); promptImportWitnessOnlyAccount(dialogNewAccount->getAccountName()); return; } if ( !dialogNewAccount->getAccountName().simplified().isEmpty() ) { //fixme: (2.1) This can be improved; we don't really need to unlock for every single creation only sometimes //This is here to stop the weird effect of shadow thread requesting password -after- account creation though //This should tie in better with the shadow thread.. // Temporarily unlock for account generation. std::function<void (void)> successCallback = [=]() { CAccount* newAccount = nullptr; if (newAccountType == NewAccountType::FixedDeposit) { newAccount = pactiveWallet->GenerateNewAccount(dialogNewAccount->getAccountName().toStdString(), AccountState::Normal, AccountType::PoW2Witness); } else { newAccount = pactiveWallet->GenerateNewAccount(dialogNewAccount->getAccountName().toStdString(), AccountState::Normal, AccountType::Desktop); } if (!newAccount) { std::string strAlert = "Failed to create new account"; CAlert::Notify(strAlert, true, true); LogPrintf("%s", strAlert.c_str()); return; } restoreCachedWidgetIfNeeded(); if (newAccountType == NewAccountType::FixedDeposit) { newAccount->SetWarningState(AccountStatus::WitnessEmpty); static_cast<const CGuldenWallet*>(pactiveWallet)->NotifyAccountWarningChanged(pactiveWallet, newAccount); showWitnessDialog(); } else { gotoReceiveCoinsPage(); } }; if (pactiveWallet->IsLocked()) { uiInterface.RequestUnlockWithCallback(pactiveWallet, _("Wallet unlock required for account creation"), successCallback); } else { successCallback(); } return; } else { //fixme: (2.1) Mark invalid. } } void GUI::acceptNewAccountMobile() { LogPrint(BCLog::QT, "GUI::acceptNewAccountMobile\n"); restoreCachedWidgetIfNeeded(); } void GUI::showAccountSettings() { LogPrint(BCLog::QT, "GUI::showAccountSettings\n"); if ( walletFrame ) { restoreCachedWidgetIfNeeded(); dialogAccountSettings = new AccountSettingsDialog( platformStyle, walletFrame->currentWalletView(), walletFrame->currentWalletView()->walletModel->getActiveAccount(), walletFrame->currentWalletView()->walletModel); connect( dialogAccountSettings, SIGNAL( dismissAccountSettings() ), this, SLOT( dismissAccountSettings() ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); connect( walletFrame->currentWalletView()->walletModel, SIGNAL( activeAccountChanged(CAccount*) ), dialogAccountSettings, SLOT( activeAccountChanged(CAccount*) ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); cacheCurrentWidget = walletFrame->currentWalletView()->currentWidget(); walletFrame->currentWalletView()->addWidget( dialogAccountSettings ); walletFrame->currentWalletView()->setCurrentWidget( dialogAccountSettings ); } } void GUI::dismissAccountSettings() { LogPrint(BCLog::QT, "GUI::dismissAccountSettings\n"); restoreCachedWidgetIfNeeded(); } void GUI::showExchangeRateDialog() { LogPrint(BCLog::QT, "GUI::showExchangeRateDialog\n"); if (!dialogExchangeRate) { CurrencyTableModel* currencyTabelmodel = ticker->GetCurrencyTableModel(); currencyTabelmodel->setBalance( walletFrame->currentWalletView()->walletModel->getBalance() ); connect( walletFrame->currentWalletView()->walletModel, SIGNAL( balanceChanged(WalletBalances, CAmount, CAmount, CAmount) ), currencyTabelmodel , SLOT( balanceChanged(WalletBalances, CAmount, CAmount, CAmount) ), (Qt::ConnectionType)(Qt::AutoConnection|Qt::UniqueConnection) ); dialogExchangeRate = new ExchangeRateDialog( platformStyle, this, currencyTabelmodel ); dialogExchangeRate->setOptionsModel( optionsModel ); } dialogExchangeRate->show(); } std::string CurrencySymbolForCurrencyCode(const std::string& currencyCode) { static std::map<std::string, std::string> currencyCodeSymbolMap = { {"ALL", "Lek"}, {"AFN", "؋"}, {"ARS", "$"}, {"AWG", "ƒ"}, {"AUD", "$"}, {"AZN", "ман"}, {"BSD", "$"}, {"BBD", "$"}, {"BYN", "Br"}, {"BZD", "BZ$"}, {"BMD", "$"}, {"BOB", "$b"}, {"BAM", "KM"}, {"BWP", "P"}, {"BGN", "лв"}, {"BRL", "R$"}, {"BND", "$"}, {"BTC", GUIUtil::fontAwesomeBrand("\uF15A").toStdString()}, {"KHR", "៛"}, {"CAD", "$"}, {"KYD", "$"}, {"CLP", "$"}, {"CNY", "¥"}, {"COP", "$"}, {"CRC", "₡"}, {"HRK", "kn"}, {"CUP", "₱"}, {"CZK", "Kč"}, {"DKK", "kr"}, {"DOP", "RD$"}, {"XCD", "$"}, {"EGP", "£"}, {"SVC", "$"}, {"EUR", "€"}, {"FKP", "£"}, {"FJD", "$"}, {"GHS", "¢"}, {"GIP", "£"}, {"GTQ", "Q"}, {"GGP", "£"}, {"GYD", "$"}, {"HNL", "L"}, {"HKD", "$"}, {"HUF", "Ft"}, {"ISK", "kr"}, {"INR", ""}, {"IDR", "Rp"}, {"IRR", "﷼"}, {"IMP", "£"}, {"ILS", "₪"}, {"JMD", "J$"}, {"JPY", "¥"}, {"JEP", "£"}, {"KZT", "лв"}, {"KPW", "₩"}, {"KRW", "₩"}, {"KGS", "лв"}, {"LAK", "₭"}, {"LBP", "£"}, {"LRD", "$"}, {"MKD", "ден"}, {"MYR", "RM"}, {"MUR", "₨"}, {"MXN", "$"}, {"MNT", "₮"}, {"MZN", "MT"}, {"NAD", "$"}, {"NPR", "₨"}, {"ANG", "ƒ"}, {"NZD", "$"}, {"NIO", "C$"}, {"NGN", "₦"}, {"KPW", "₩"}, {"NOK", "kr"}, {"OMR", "﷼"}, {"PKR", "₨"}, {"PAB", "B/."}, {"PYG", "Gs"}, {"PEN", "S/."}, {"PHP", "₱"}, {"PLN", "zł"}, {"QAR", "﷼"}, {"RON", "lei"}, {"RUB", "₽"}, {"SHP", "£"}, {"SAR", "﷼"}, {"RSD", "Дин."}, {"SCR", "₨"}, {"SGD", "$"}, {"SBD", "$"}, {"SOS", "S"}, {"ZAR", "R"}, {"KRW", "₩"}, {"LKR", "₨"}, {"SEK", "kr"}, {"CHF", "CHF"}, {"SRD", "$"}, {"SYP", "£"}, {"TWD", "NT$"}, {"THB", "฿"}, {"TTD", "TT$"}, {"TRY", ""}, {"TVD", "$"}, {"UAH", "₴"}, {"GBP", "£"}, {"USD", "$"}, {"UYU", "$U"}, {"UZS", "лв"}, {"VEF", "Bs"}, {"VND", "₫"}, {"YER", "﷼"}, {"ZWD", "Z$"}, {"NLG", "\u0120"} }; if (currencyCodeSymbolMap.find(currencyCode) != currencyCodeSymbolMap.end()) { return currencyCodeSymbolMap[currencyCode]; } return ""; }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cpdp/v20190820/model/ApplyOutwardOrderResult.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cpdp::V20190820::Model; using namespace rapidjson; using namespace std; ApplyOutwardOrderResult::ApplyOutwardOrderResult() : m_dataHasBeenSet(false), m_codeHasBeenSet(false) { } CoreInternalOutcome ApplyOutwardOrderResult::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Data") && !value["Data"].IsNull()) { if (!value["Data"].IsObject()) { return CoreInternalOutcome(Error("response `ApplyOutwardOrderResult.Data` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_data.Deserialize(value["Data"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_dataHasBeenSet = true; } if (value.HasMember("Code") && !value["Code"].IsNull()) { if (!value["Code"].IsString()) { return CoreInternalOutcome(Error("response `ApplyOutwardOrderResult.Code` IsString=false incorrectly").SetRequestId(requestId)); } m_code = string(value["Code"].GetString()); m_codeHasBeenSet = true; } return CoreInternalOutcome(true); } void ApplyOutwardOrderResult::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_dataHasBeenSet) { Value iKey(kStringType); string key = "Data"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_data.ToJsonObject(value[key.c_str()], allocator); } if (m_codeHasBeenSet) { Value iKey(kStringType); string key = "Code"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_code.c_str(), allocator).Move(), allocator); } } ApplyOutwardOrderData ApplyOutwardOrderResult::GetData() const { return m_data; } void ApplyOutwardOrderResult::SetData(const ApplyOutwardOrderData& _data) { m_data = _data; m_dataHasBeenSet = true; } bool ApplyOutwardOrderResult::DataHasBeenSet() const { return m_dataHasBeenSet; } string ApplyOutwardOrderResult::GetCode() const { return m_code; } void ApplyOutwardOrderResult::SetCode(const string& _code) { m_code = _code; m_codeHasBeenSet = true; } bool ApplyOutwardOrderResult::CodeHasBeenSet() const { return m_codeHasBeenSet; }
#pragma once #include "ChipWaveShared.hpp" #include "DistrhoUI.hpp" #include "Image.hpp" #include <vector> #include <memory> class TextEdit; class ChipWaveUI : public DISTRHO::UI { public: ChipWaveUI(); ~ChipWaveUI(); bool onMotion(const MotionEvent &event) override; void onDisplay() override; void parameterChanged(uint32_t index, float value) override; void programLoaded(uint32_t index) override; void stateChanged(const char* key, const char* value) override; private: void SliderAdd(int32_t x, int32_t y, int32_t w, int32_t h, int32_t param, int32_t steps, bool invert); void RenderWaveform(int32_t x, int32_t y, int32_t w, int32_t h, int32_t osc); void RenderEnvelope(int32_t x, int32_t y, int32_t w, int32_t h, int32_t env); private: float getControlValue(uint32_t index) const; void setControlValue(uint32_t index, float value); private: bool fGraphicsInitialized = false; DGL::Image fBackgroundImage; std::unique_ptr<TextEdit> fNameEdit; std::unique_ptr<std::unique_ptr<DGL::Widget>[]> fControls; std::unique_ptr<int[]> fControlNumSteps; int fControlHovered = -1; Parameter fParameters[Parameter_Count]; };
//////////////////////////////////////////////////////////////////////////////// /// Reaper /// /// Copyright (c) 2015-2021 Thibault Schueller /// This file is distributed under the MIT License //////////////////////////////////////////////////////////////////////////////// #include "Backend.h" // TODO use Pimpl to prevent name clashes between Xlib and fmt and move this include forward #include "common/Log.h" #include "core/Profile.h" #include "Display.h" #include "Swapchain.h" #include <cstring> #include <iostream> #include "PresentationSurface.h" #include "renderer/window/Window.h" #ifndef REAPER_VK_LIB_NAME # error #endif // Version of the API to query when loading vulkan symbols #define REAPER_VK_API_VERSION VK_MAKE_VERSION(1, 2, 0) // Decide which swapchain extension to use #if defined(VK_USE_PLATFORM_WIN32_KHR) # define REAPER_VK_SWAPCHAIN_EXTENSION_NAME VK_KHR_WIN32_SURFACE_EXTENSION_NAME #elif defined(VK_USE_PLATFORM_XCB_KHR) # define REAPER_VK_SWAPCHAIN_EXTENSION_NAME VK_KHR_XCB_SURFACE_EXTENSION_NAME #elif defined(VK_USE_PLATFORM_XLIB_KHR) # define REAPER_VK_SWAPCHAIN_EXTENSION_NAME VK_KHR_XLIB_SURFACE_EXTENSION_NAME #endif namespace Reaper { namespace { VkDescriptorPool create_global_descriptor_pool(ReaperRoot& root, VulkanBackend& backend) { // Create descriptor pool // FIXME Sizes are arbitrary for now, as long as everything fits constexpr u32 MaxDescriptorSets = 100; std::vector<VkDescriptorPoolSize> descriptorPoolSizes = {{VK_DESCRIPTOR_TYPE_SAMPLER, 16}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 256}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 32}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 32}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 32}}; VkDescriptorPoolCreateInfo poolInfo = {VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, nullptr, VK_FLAGS_NONE, MaxDescriptorSets, static_cast<uint32_t>(descriptorPoolSizes.size()), descriptorPoolSizes.data()}; VkDescriptorPool pool = VK_NULL_HANDLE; Assert(vkCreateDescriptorPool(backend.device, &poolInfo, nullptr, &pool) == VK_SUCCESS); log_debug(root, "vulkan: created descriptor pool with handle: {}", static_cast<void*>(pool)); return pool; } } // namespace void vulkan_instance_check_extensions(const std::vector<const char*>& extensions); void vulkan_instance_check_layers(const std::vector<const char*>& layers); void vulkan_device_check_extensions(const std::vector<const char*>& extensions, VkPhysicalDevice physicalDevice); void vulkan_setup_debug_callback(ReaperRoot& root, VulkanBackend& renderer); void vulkan_destroy_debug_callback(VulkanBackend& renderer); bool vulkan_check_physical_device(IWindow* window, VkPhysicalDevice physical_device, VkSurfaceKHR presentationSurface, const std::vector<const char*>& extensions, uint32_t& queue_family_index, uint32_t& selected_present_queue_family_index); void vulkan_choose_physical_device(ReaperRoot& root, VulkanBackend& backend, const std::vector<const char*>& device_extensions, PhysicalDeviceInfo& physicalDeviceInfo); void vulkan_create_logical_device(ReaperRoot& root, VulkanBackend& backend, const std::vector<const char*>& device_extensions); VulkanBackend::VulkanBackend() : vulkanLib(nullptr) , instance(VK_NULL_HANDLE) , physicalDevice(VK_NULL_HANDLE) , physicalDeviceInfo({0, 0, {}}) , device(VK_NULL_HANDLE) , deviceInfo({VK_NULL_HANDLE, VK_NULL_HANDLE}) , presentInfo({}) , debugMessenger(VK_NULL_HANDLE) , mustTransitionSwapchain(false) , new_swapchain_extent({0, 0}) , resources(nullptr) { options.freeze_culling = false; options.use_compacted_draw = true; } void create_vulkan_renderer_backend(ReaperRoot& root, VulkanBackend& backend) { REAPER_PROFILE_SCOPE("Vulkan", MP_RED1); log_info(root, "vulkan: creating backend"); log_debug(root, "vulkan: loading {}", REAPER_VK_LIB_NAME); backend.vulkanLib = dynlib::load(REAPER_VK_LIB_NAME); vulkan_load_exported_functions(backend.vulkanLib); vulkan_load_global_level_functions(); std::vector<const char*> instanceExtensions = {VK_KHR_SURFACE_EXTENSION_NAME, REAPER_VK_SWAPCHAIN_EXTENSION_NAME}; #if REAPER_DEBUG instanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); #endif log_info(root, "vulkan: using {} instance level extensions", instanceExtensions.size()); for (auto& e : instanceExtensions) log_debug(root, "- {}", e); vulkan_instance_check_extensions(instanceExtensions); std::vector<const char*> instanceLayers; #if REAPER_DEBUG instanceLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif log_info(root, "vulkan: using {} instance level layers", instanceLayers.size()); for (auto& layer : instanceLayers) log_debug(root, "- {}", layer); vulkan_instance_check_layers(instanceLayers); const u32 appVersion = VK_MAKE_VERSION(REAPER_VERSION_MAJOR, REAPER_VERSION_MINOR, REAPER_VERSION_PATCH); const u32 engineVersion = appVersion; const u32 vulkanVersion = REAPER_VK_API_VERSION; VkApplicationInfo application_info = { VK_STRUCTURE_TYPE_APPLICATION_INFO, // VkStructureType sType nullptr, // const void* pNext "MyGame", // const char* pApplicationName appVersion, // uint32_t applicationVersion "Reaper", // const char* pEngineName engineVersion, // uint32_t engineVersion vulkanVersion // uint32_t apiVersion }; VkInstanceCreateInfo instance_create_info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, // VkStructureType sType nullptr, // const void* pNext 0, // VkInstanceCreateFlags flags &application_info, // const VkApplicationInfo *pApplicationInfo static_cast<u32>(instanceLayers.size()), // uint32_t enabledLayerCount instanceLayers.data(), // const char * const *ppEnabledLayerNames static_cast<u32>(instanceExtensions.size()), // uint32_t enabledExtensionCount instanceExtensions.data(), // const char * const *ppEnabledExtensionNames }; Assert(vkCreateInstance(&instance_create_info, nullptr, &backend.instance) == VK_SUCCESS, "cannot create Vulkan instance"); vulkan_load_instance_level_functions(backend.instance); #if REAPER_DEBUG log_debug(root, "vulkan: attaching debug callback"); vulkan_setup_debug_callback(root, backend); #endif WindowCreationDescriptor windowDescriptor; windowDescriptor.title = "Vulkan"; windowDescriptor.width = 800; windowDescriptor.height = 600; windowDescriptor.fullscreen = false; log_info(root, "vulkan: creating window: size = {}x{}, title = '{}', fullscreen = {}", windowDescriptor.width, windowDescriptor.height, windowDescriptor.title, windowDescriptor.fullscreen); IWindow* window = createWindow(windowDescriptor); root.renderer->window = window; log_debug(root, "vulkan: creating presentation surface"); vulkan_create_presentation_surface(backend.instance, backend.presentInfo.surface, window); std::vector<const char*> device_extensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, }; log_debug(root, "vulkan: choosing physical device"); vulkan_choose_physical_device(root, backend, device_extensions, backend.physicalDeviceInfo); log_debug(root, "vulkan: creating logical device"); vulkan_create_logical_device(root, backend, device_extensions); log_debug(root, "vulkan: create global descriptor pool"); backend.global_descriptor_pool = create_global_descriptor_pool(root, backend); log_debug(root, "vulkan: create gpu memory allocator"); VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.physicalDevice = backend.physicalDevice; allocatorInfo.device = backend.device; allocatorInfo.instance = backend.instance; vmaCreateAllocator(&allocatorInfo, &backend.vma_instance); SwapchainDescriptor swapchainDesc; swapchainDesc.preferredImageCount = 2; // Double buffering swapchainDesc.preferredFormat = {VK_FORMAT_B8G8R8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; // swapchainDesc.preferredFormat = {VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}; swapchainDesc.preferredExtent = {windowDescriptor.width, windowDescriptor.height}; configure_vulkan_wm_swapchain(root, backend, swapchainDesc, backend.presentInfo); create_vulkan_wm_swapchain(root, backend, backend.presentInfo); // create_vulkan_display_swapchain(root, backend); #if defined(REAPER_USE_MICROPROFILE) const u32 node_count = 1; // NOTE: not sure what this is for MicroProfileGpuInitVulkan(&backend.device, &backend.physicalDevice, &backend.deviceInfo.graphicsQueue, &backend.physicalDeviceInfo.graphicsQueueFamilyIndex, node_count); #endif log_info(root, "vulkan: ready"); } void destroy_vulkan_renderer_backend(ReaperRoot& root, VulkanBackend& backend) { REAPER_PROFILE_SCOPE("Vulkan", MP_RED1); log_info(root, "vulkan: destroying backend"); log_debug(root, "vulkan: waiting for current work to finish"); Assert(vkDeviceWaitIdle(backend.device) == VK_SUCCESS); #if defined(REAPER_USE_MICROPROFILE) MicroProfileGpuShutdown(); #endif destroy_vulkan_wm_swapchain(root, backend, backend.presentInfo); log_debug(root, "vulkan: destroy gpu memory allocator"); vmaDestroyAllocator(backend.vma_instance); log_debug(root, "vulkan: destroy global descriptor pool"); vkDestroyDescriptorPool(backend.device, backend.global_descriptor_pool, nullptr); log_debug(root, "vulkan: destroying logical device"); vkDestroyDevice(backend.device, nullptr); log_debug(root, "vulkan: destroying presentation surface"); vkDestroySurfaceKHR(backend.instance, backend.presentInfo.surface, nullptr); delete root.renderer->window; root.renderer->window = nullptr; #if REAPER_DEBUG log_debug(root, "vulkan: detaching debug callback"); vulkan_destroy_debug_callback(backend); #endif vkDestroyInstance(backend.instance, nullptr); log_debug(root, "vulkan: unloading {}", REAPER_VK_LIB_NAME); Assert(backend.vulkanLib != nullptr); dynlib::close(backend.vulkanLib); backend.vulkanLib = nullptr; } void vulkan_instance_check_extensions(const std::vector<const char*>& extensions) { uint32_t extensions_count = 0; Assert(vkEnumerateInstanceExtensionProperties(nullptr, &extensions_count, nullptr) == VK_SUCCESS); Assert(extensions_count > 0); std::vector<VkExtensionProperties> available_extensions(extensions_count); Assert(vkEnumerateInstanceExtensionProperties(nullptr, &extensions_count, &available_extensions[0]) == VK_SUCCESS); for (size_t i = 0; i < extensions.size(); ++i) { bool found = false; for (size_t j = 0; j < available_extensions.size(); ++j) { if (std::strcmp(available_extensions[j].extensionName, extensions[i]) == 0) found = true; } Assert(found, fmt::format("vulkan: extension '{}' not supported by the instance", extensions[i])); } } void vulkan_instance_check_layers(const std::vector<const char*>& layers) { uint32_t layers_count = 0; Assert(vkEnumerateInstanceLayerProperties(&layers_count, nullptr) == VK_SUCCESS); Assert(layers_count > 0); std::vector<VkLayerProperties> available_layers(layers_count); Assert(vkEnumerateInstanceLayerProperties(&layers_count, &available_layers[0]) == VK_SUCCESS); for (size_t i = 0; i < layers.size(); ++i) { bool found = false; for (size_t j = 0; j < available_layers.size(); ++j) { if (std::strcmp(available_layers[j].layerName, layers[i]) == 0) found = true; } Assert(found, fmt::format("vulkan: layer '{}' not supported by the instance", layers[i])); } } namespace { VkBool32 VKAPI_PTR debugReportCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT /*messageTypes*/, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData) { ReaperRoot* root = static_cast<ReaperRoot*>(pUserData); Assert(root != nullptr); log_debug(*root, "vulkan debug message: {} ({}): {}", pCallbackData->pMessageIdName ? pCallbackData->pMessageIdName : "unnamed", pCallbackData->messageIdNumber, pCallbackData->pMessage); u32 queueCount = pCallbackData->queueLabelCount; if (queueCount > 0) { log_debug(*root, "queues labels:"); for (u32 i = 0; i < queueCount; i++) { const VkDebugUtilsLabelEXT& queueInfo = pCallbackData->pQueueLabels[i]; const char* label = queueInfo.pLabelName; log_debug(*root, "- {}", label ? label : "unnamed"); } } u32 cmdBufferCount = pCallbackData->cmdBufLabelCount; if (cmdBufferCount > 0) { log_debug(*root, "command buffer labels:"); for (u32 i = 0; i < cmdBufferCount; i++) { const VkDebugUtilsLabelEXT& cmdBufferInfo = pCallbackData->pCmdBufLabels[i]; const char* label = cmdBufferInfo.pLabelName; log_debug(*root, "- {}", label ? label : "unnamed"); } } u32 objetCount = pCallbackData->objectCount; if (objetCount > 0) { log_debug(*root, "oject info:"); for (u32 i = 0; i < objetCount; i++) { const VkDebugUtilsObjectNameInfoEXT& objectInfo = pCallbackData->pObjects[i]; const char* label = objectInfo.pObjectName; log_debug(*root, "- {}, handle = {}", label ? label : "unnamed", objectInfo.objectHandle); } } Assert(messageSeverity < VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT); return VK_FALSE; } } // namespace void vulkan_setup_debug_callback(ReaperRoot& root, VulkanBackend& backend) { VkDebugUtilsMessengerCreateInfoEXT callbackCreateInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, nullptr, 0, VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT, &debugReportCallback, &root}; #if REAPER_DEBUG Assert(vkCreateDebugUtilsMessengerEXT(backend.instance, &callbackCreateInfo, nullptr, &backend.debugMessenger) == VK_SUCCESS); #endif } // namespace Reaper void vulkan_destroy_debug_callback(VulkanBackend& backend) { Assert(backend.debugMessenger != nullptr); #if REAPER_DEBUG vkDestroyDebugUtilsMessengerEXT(backend.instance, backend.debugMessenger, nullptr); #endif backend.debugMessenger = nullptr; } // Move this up void vulkan_device_check_extensions(const std::vector<const char*>& extensions, VkPhysicalDevice physicalDevice) { uint32_t extensions_count = 0; Assert(vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensions_count, nullptr) == VK_SUCCESS); Assert(extensions_count > 0); std::vector<VkExtensionProperties> available_extensions(extensions_count); Assert(vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensions_count, (extensions_count > 0 ? &available_extensions[0] : nullptr)) == VK_SUCCESS); for (size_t i = 0; i < extensions.size(); ++i) { bool found = false; for (size_t j = 0; j < available_extensions.size(); ++j) { if (std::strcmp(available_extensions[j].extensionName, extensions[i]) == 0) found = true; } Assert(found, fmt::format("vulkan: extension '{}' not supported by the device", extensions[i])); } } bool vulkan_check_physical_device(IWindow* window, VkPhysicalDevice physical_device, VkSurfaceKHR presentationSurface, const std::vector<const char*>& extensions, uint32_t& queue_family_index, uint32_t& selected_present_queue_family_index) { Assert(window != nullptr); vulkan_device_check_extensions(extensions, physical_device); VkPhysicalDeviceProperties2 device_properties2 = {}; device_properties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; vkGetPhysicalDeviceProperties2(physical_device, &device_properties2); VkPhysicalDeviceProperties& device_properties = device_properties2.properties; // NOTE: // For some reason the validation layer barks at us if we don't initialize sType to this value. // This shouldn't be the case since vkGetPhysicalDeviceFeatures2 should overwrite it. VkPhysicalDeviceFeatures2 device_features2 = {}; device_features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; // NOTE: // Even if VkPhysicalDeviceVulkan12Features is used during device creation, // Vulkan 1.2 does NOT force vkGetPhysicalDeviceFeatures2 to include it in the pNext chain. vkGetPhysicalDeviceFeatures2(physical_device, &device_features2); Assert(device_properties.apiVersion >= REAPER_VK_API_VERSION); Assert(device_properties.limits.maxImageDimension2D >= 4096); Assert(device_features2.features.shaderClipDistance == VK_TRUE); // This is just checked, not enabled uint32_t queue_families_count = 0; vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &queue_families_count, nullptr); Assert(queue_families_count > 0, "device doesn't have any queue families"); if (queue_families_count == 0) return false; std::vector<VkQueueFamilyProperties> queue_family_properties(queue_families_count); std::vector<VkBool32> queue_present_support(queue_families_count); vkGetPhysicalDeviceQueueFamilyProperties(physical_device, &queue_families_count, &queue_family_properties[0]); uint32_t graphics_queue_family_index = UINT32_MAX; uint32_t present_queue_family_index = UINT32_MAX; for (uint32_t i = 0; i < queue_families_count; ++i) { Assert(vkGetPhysicalDeviceSurfaceSupportKHR(physical_device, i, presentationSurface, &queue_present_support[i]) == VK_SUCCESS); if ((queue_family_properties[i].queueCount > 0) && (queue_family_properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)) { // Select first queue that supports graphics if (graphics_queue_family_index == UINT32_MAX) graphics_queue_family_index = i; Assert(vulkan_queue_family_has_presentation_support(physical_device, i, window) == (queue_present_support[i] == VK_TRUE), "Queue family presentation support mismatch."); // If there is queue that supports both graphics and present - prefer it if (queue_present_support[i]) { queue_family_index = i; selected_present_queue_family_index = i; return true; } } } // We don't have queue that supports both graphics and present so we have to use separate queues for (uint32_t i = 0; i < queue_families_count; ++i) { if (queue_present_support[i] == VK_TRUE) { present_queue_family_index = i; break; } } Assert(graphics_queue_family_index != UINT32_MAX); Assert(present_queue_family_index != UINT32_MAX); queue_family_index = graphics_queue_family_index; selected_present_queue_family_index = present_queue_family_index; return true; } namespace { const char* vulkan_physical_device_type_name(VkPhysicalDeviceType deviceType) { switch (deviceType) { case VK_PHYSICAL_DEVICE_TYPE_OTHER: return "other"; case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated"; case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete"; case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual"; case VK_PHYSICAL_DEVICE_TYPE_CPU: return "other"; default: AssertUnreachable(); break; } return "unknown"; } } // namespace void vulkan_choose_physical_device(ReaperRoot& root, VulkanBackend& backend, const std::vector<const char*>& device_extensions, PhysicalDeviceInfo& physicalDeviceInfo) { uint32_t deviceCount = 0; Assert(vkEnumeratePhysicalDevices(backend.instance, &deviceCount, nullptr) == VK_SUCCESS); Assert(deviceCount > 0); log_debug(root, "vulkan: enumerating {} physical devices", deviceCount); std::vector<VkPhysicalDevice> availableDevices(deviceCount); Assert(vkEnumeratePhysicalDevices(backend.instance, &deviceCount, &availableDevices[0]) == VK_SUCCESS, "error occurred during physical devices enumeration"); uint32_t selected_queue_family_index = UINT32_MAX; uint32_t selected_present_queue_family_index = UINT32_MAX; VkPhysicalDevice chosenPhysicalDevice = VK_NULL_HANDLE; for (auto& device : availableDevices) { if (vulkan_check_physical_device(root.renderer->window, device, backend.presentInfo.surface, device_extensions, selected_queue_family_index, selected_present_queue_family_index)) { chosenPhysicalDevice = device; break; } } Assert(chosenPhysicalDevice != VK_NULL_HANDLE, "could not select physical device based on the chosen properties"); physicalDeviceInfo.graphicsQueueFamilyIndex = selected_queue_family_index; physicalDeviceInfo.presentQueueFamilyIndex = selected_present_queue_family_index; vkGetPhysicalDeviceMemoryProperties(chosenPhysicalDevice, &physicalDeviceInfo.memory); // re-fetch device infos TODO avoid VkPhysicalDeviceDriverProperties deviceDriverProperties; deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES; deviceDriverProperties.pNext = nullptr; VkPhysicalDeviceSubgroupProperties subgroupProperties; subgroupProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES; subgroupProperties.pNext = &deviceDriverProperties; VkPhysicalDeviceProperties2 physicalDeviceProperties2; physicalDeviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; physicalDeviceProperties2.pNext = &subgroupProperties; vkGetPhysicalDeviceProperties2(chosenPhysicalDevice, &physicalDeviceProperties2); Assert(subgroupProperties.supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT); Assert(subgroupProperties.supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT); Assert(subgroupProperties.supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT); Assert(subgroupProperties.supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT); // VK_SUBGROUP_FEATURE_BASIC_BIT = 0x00000001, // VK_SUBGROUP_FEATURE_VOTE_BIT = 0x00000002, // VK_SUBGROUP_FEATURE_ARITHMETIC_BIT = 0x00000004, // VK_SUBGROUP_FEATURE_BALLOT_BIT = 0x00000008, // VK_SUBGROUP_FEATURE_SHUFFLE_BIT = 0x00000010, // VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT = 0x00000020, // VK_SUBGROUP_FEATURE_CLUSTERED_BIT = 0x00000040, // VK_SUBGROUP_FEATURE_QUAD_BIT = 0x00000080, // VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV = 0x00000100, const VkPhysicalDeviceProperties physicalDeviceProperties = physicalDeviceProperties2.properties; log_info(root, "vulkan: selecting device '{}'", physicalDeviceProperties.deviceName); log_debug(root, "- type = {}", vulkan_physical_device_type_name(physicalDeviceProperties.deviceType)); uint32_t apiVersion = physicalDeviceProperties.apiVersion; uint32_t driverVersion = physicalDeviceProperties.driverVersion; log_debug(root, "- api version = {}.{}.{}", VK_VERSION_MAJOR(apiVersion), VK_VERSION_MINOR(apiVersion), VK_VERSION_PATCH(apiVersion)); log_debug(root, "- driver '{}' version = {}.{}.{}", deviceDriverProperties.driverName, VK_VERSION_MAJOR(driverVersion), VK_VERSION_MINOR(driverVersion), VK_VERSION_PATCH(driverVersion)); log_debug(root, "- driver info '{}' conformance version = {}.{}.{}.{}", deviceDriverProperties.driverInfo, deviceDriverProperties.conformanceVersion.major, deviceDriverProperties.conformanceVersion.minor, deviceDriverProperties.conformanceVersion.subminor, deviceDriverProperties.conformanceVersion.patch); log_debug(root, "- memory type count = {}, memory heap count = {}", physicalDeviceInfo.memory.memoryTypeCount, physicalDeviceInfo.memory.memoryHeapCount); for (u32 i = 0; i < physicalDeviceInfo.memory.memoryHeapCount; ++i) { VkMemoryHeap& heap = physicalDeviceInfo.memory.memoryHeaps[i]; log_debug(root, "- heap {}: available size = {}, flags = {}", i, heap.size, heap.flags); } backend.physicalDevice = chosenPhysicalDevice; backend.physicalDeviceProperties = physicalDeviceProperties; } void vulkan_create_logical_device(ReaperRoot& root, VulkanBackend& backend, const std::vector<const char*>& device_extensions) { std::vector<VkDeviceQueueCreateInfo> queue_create_infos; std::vector<float> queue_priorities = {1.0f}; queue_create_infos.push_back({ VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, // VkStructureType sType nullptr, // const void *pNext 0, // VkDeviceQueueCreateFlags flags backend.physicalDeviceInfo.graphicsQueueFamilyIndex, // uint32_t queueFamilyIndex static_cast<uint32_t>(queue_priorities.size()), // uint32_t queueCount &queue_priorities[0] // const float *pQueuePriorities }); if (backend.physicalDeviceInfo.graphicsQueueFamilyIndex != backend.physicalDeviceInfo.presentQueueFamilyIndex) { queue_create_infos.push_back({ VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, // VkStructureType sType nullptr, // const void *pNext 0, // VkDeviceQueueCreateFlags flags backend.physicalDeviceInfo.presentQueueFamilyIndex, // uint32_t queueFamilyIndex static_cast<uint32_t>(queue_priorities.size()), // uint32_t queueCount &queue_priorities[0] // const float *pQueuePriorities }); } Assert(!queue_create_infos.empty()); Assert(!queue_priorities.empty()); Assert(queue_priorities.size() == queue_create_infos.size()); uint32_t queueCreateCount = static_cast<uint32_t>(queue_create_infos.size()); log_info(root, "vulkan: using {} device level extensions", device_extensions.size()); for (auto& e : device_extensions) log_debug(root, "- {}", e); VkPhysicalDeviceFeatures deviceFeatures = {}; deviceFeatures.multiDrawIndirect = true; deviceFeatures.drawIndirectFirstInstance = true; VkPhysicalDeviceVulkan12Features device_features_1_2 = {}; device_features_1_2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES; device_features_1_2.pNext = nullptr; device_features_1_2.drawIndirectCount = VK_TRUE; device_features_1_2.imagelessFramebuffer = VK_TRUE; device_features_1_2.separateDepthStencilLayouts = VK_TRUE; device_features_1_2.descriptorIndexing = VK_TRUE; device_features_1_2.runtimeDescriptorArray = VK_TRUE; device_features_1_2.descriptorBindingPartiallyBound = VK_TRUE; device_features_1_2.timelineSemaphore = VK_TRUE; VkPhysicalDeviceFeatures2 deviceFeatures2 = {}; deviceFeatures2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; deviceFeatures2.pNext = &device_features_1_2; deviceFeatures2.features = deviceFeatures; VkDeviceCreateInfo device_create_info = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, // VkStructureType sType &deviceFeatures2, // const void *pNext 0, // VkDeviceCreateFlags flags queueCreateCount, // uint32_t queueCreateInfoCount &queue_create_infos[0], // const VkDeviceQueueCreateInfo *pQueueCreateInfos 0, // uint32_t enabledLayerCount nullptr, // const char * const *ppEnabledLayerNames static_cast<u32>(device_extensions.size()), // uint32_t enabledExtensionCount device_extensions.data(), // const char * const *ppEnabledExtensionNames nullptr // const VkPhysicalDeviceFeatures *pEnabledFeatures }; Assert(vkCreateDevice(backend.physicalDevice, &device_create_info, nullptr, &backend.device) == VK_SUCCESS, "could not create Vulkan device"); vulkan_load_device_level_functions(backend.device); vkGetDeviceQueue(backend.device, backend.physicalDeviceInfo.graphicsQueueFamilyIndex, 0, &backend.deviceInfo.graphicsQueue); vkGetDeviceQueue(backend.device, backend.physicalDeviceInfo.presentQueueFamilyIndex, 0, &backend.deviceInfo.presentQueue); } } // namespace Reaper
// Copyright (c) 2014 The Caroline authors. All rights reserved. // Use of this source file is governed by a MIT license that can be found in the // LICENSE file. /// @author Glazachev Vladimir <glazachev.vladimir@gmail.com> #include "core/mesh.h" namespace core { Mesh::Mesh() { } void Mesh::AddVertex(const cv::Point3d &point) { vertexes_.push_back(point); } void Mesh::AddFace(const Triangle &face) { faces_.push_back(face); } void Mesh::SetVertexes(const std::vector<cv::Point3d>& vertexes) { vertexes_ = vertexes; } void Mesh::SetFaces(const std::vector<Triangle>& faces) { faces_ = faces; } } // namespace core
#include "graphnode.h" const qreal GraphNode::cCircleR = 4.0; quint32 GraphNode::m_count = 0; const QPen GraphNode::cPenNormal = QPen(Qt::black); //const QPen GraphNode::cPenSelected = QPen(QBrush(Qt::black), 2); const QPen GraphNode::cPenWay = QPen(Qt::black); const QBrush GraphNode::cBrushNormal = QBrush(Qt::blue); //const QBrush GraphNode::cBrushSelected = QBrush(Global::colorSelected); const QBrush GraphNode::cBrushWay = QBrush(Qt::darkGreen); GraphNode::GraphNode(): QGraphicsEllipseItem(-cCircleR, -cCircleR, 2*cCircleR, 2*cCircleR) { setBrush(cBrushNormal); setPen(cPenNormal); setZValue(100500 - 1); m_door = 0; m_uin = ++m_count; } GraphNode::GraphNode(const QPointF &point, quint32 floor): QGraphicsEllipseItem(-cCircleR, -cCircleR, 2*cCircleR, 2*cCircleR), m_floor(floor) { setPos(point); setBrush(cBrushNormal); setPen(cPenNormal); setZValue(100500 - 1); m_door = 0; m_uin = ++m_count; } GraphNode::~GraphNode() { while (m_arcs.size() != 0) { GraphArc *arc = m_arcs.at(0); m_arcs.remove(0); delete arc; } } QDataStream & operator<<(QDataStream &output, const GraphNode &node) { output << node.m_uin << node.x() << node.y() << node.m_floor; return output; } QDataStream & operator>>(QDataStream &input, GraphNode &node) { qreal x, y; input >> node.m_uin >> x >> y >> node.m_floor; node.setPos(x, y); node.m_count = qMax(node.m_count, node.m_uin); return input; } MapDoor* GraphNode::door() const { return m_door; } void GraphNode::setDoor(MapDoor *door) { m_door = door; if (door->node() != this) door->setNode(this); } quint32 GraphNode::floorUin() const { return m_floor; } void GraphNode::addArc(GraphArc *arc) { m_arcs.append(arc); } GraphArc* GraphNode::arc(int i) const { return m_arcs.at(i); } GraphArc* GraphNode::arc(const GraphNode *adjacent, const bool oneWay) const { for (int i = 0; i != m_arcs.size(); i++) if ((adjacentNode(m_arcs.at(i)) == adjacent) & !(oneWay & !m_arcs.at(i)->isRight(this))) return m_arcs.at(i); return 0; } void GraphNode::deleteArc(GraphArc *arc) { int i = m_arcs.indexOf(arc); if (i > -1) m_arcs.remove(i); } int GraphNode::arcsNumber() const { return m_arcs.size(); } GraphNode* GraphNode::adjacentNode(const GraphArc *arc) const { if ((arc->node1() != this) & (arc->node2() == this)) return arc->node1(); if ((arc->node2() != this) & (arc->node1() == this)) return arc->node2(); return 0; // It's impossible, but who know?.. Сompiller say me, // it isn't good to keep code without this stupid line :) // Bye the way: this is XPEHb! :D } int GraphNode::type() const { return Type; } quint32 GraphNode::uin() const { return m_uin; }
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "user_main.hpp" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ SAI_HandleTypeDef hsai_BlockA1; SAI_HandleTypeDef hsai_BlockB1; SPI_HandleTypeDef hspi1; /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_GPIO_Init(void); static void MX_SAI1_Init(void); static void MX_SPI1_Init(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* Enable D-Cache---------------------------------------------------------*/ SCB_EnableDCache(); /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_SAI1_Init(); MX_SPI1_Init(); /* USER CODE BEGIN 2 */ mainInit(); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ mainLoop(); } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; /** Supply configuration update enable */ HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY); /** Configure the main internal regulator output voltage */ __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0); while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {} /** Macro to configure the PLL clock source */ __HAL_RCC_PLL_PLLSOURCE_CONFIG(RCC_PLLSOURCE_HSE); /** Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 4; RCC_OscInitStruct.PLL.PLLN = 480; RCC_OscInitStruct.PLL.PLLP = 2; RCC_OscInitStruct.PLL.PLLQ = 2; RCC_OscInitStruct.PLL.PLLR = 2; RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_1; RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE; RCC_OscInitStruct.PLL.PLLFRACN = 0; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2 |RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2; RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2; RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) { Error_Handler(); } PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SPI1|RCC_PERIPHCLK_SAI1; PeriphClkInitStruct.PLL2.PLL2M = 8; PeriphClkInitStruct.PLL2.PLL2N = 271; PeriphClkInitStruct.PLL2.PLL2P = 3; PeriphClkInitStruct.PLL2.PLL2Q = 2; PeriphClkInitStruct.PLL2.PLL2R = 2; PeriphClkInitStruct.PLL2.PLL2RGE = RCC_PLL2VCIRANGE_0; PeriphClkInitStruct.PLL2.PLL2VCOSEL = RCC_PLL2VCOWIDE; PeriphClkInitStruct.PLL2.PLL2FRACN = 0; PeriphClkInitStruct.Sai1ClockSelection = RCC_SAI1CLKSOURCE_PLL2; PeriphClkInitStruct.Spi123ClockSelection = RCC_SPI123CLKSOURCE_PLL; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { Error_Handler(); } } /** * @brief SAI1 Initialization Function * @param None * @retval None */ static void MX_SAI1_Init(void) { /* USER CODE BEGIN SAI1_Init 0 */ /* USER CODE END SAI1_Init 0 */ /* USER CODE BEGIN SAI1_Init 1 */ /* USER CODE END SAI1_Init 1 */ hsai_BlockA1.Instance = SAI1_Block_A; hsai_BlockA1.Init.AudioMode = SAI_MODESLAVE_RX; hsai_BlockA1.Init.Synchro = SAI_ASYNCHRONOUS; hsai_BlockA1.Init.OutputDrive = SAI_OUTPUTDRIVE_DISABLE; hsai_BlockA1.Init.FIFOThreshold = SAI_FIFOTHRESHOLD_HF; hsai_BlockA1.Init.SynchroExt = SAI_SYNCEXT_DISABLE; hsai_BlockA1.Init.MonoStereoMode = SAI_STEREOMODE; hsai_BlockA1.Init.CompandingMode = SAI_NOCOMPANDING; hsai_BlockA1.Init.TriState = SAI_OUTPUT_NOTRELEASED; if (HAL_SAI_InitProtocol(&hsai_BlockA1, SAI_I2S_STANDARD, SAI_PROTOCOL_DATASIZE_32BIT, 2) != HAL_OK) { Error_Handler(); } hsai_BlockB1.Instance = SAI1_Block_B; hsai_BlockB1.Init.AudioMode = SAI_MODESLAVE_TX; hsai_BlockB1.Init.Synchro = SAI_SYNCHRONOUS; hsai_BlockB1.Init.OutputDrive = SAI_OUTPUTDRIVE_DISABLE; hsai_BlockB1.Init.FIFOThreshold = SAI_FIFOTHRESHOLD_HF; hsai_BlockB1.Init.SynchroExt = SAI_SYNCEXT_DISABLE; hsai_BlockB1.Init.MonoStereoMode = SAI_STEREOMODE; hsai_BlockB1.Init.CompandingMode = SAI_NOCOMPANDING; hsai_BlockB1.Init.TriState = SAI_OUTPUT_NOTRELEASED; if (HAL_SAI_InitProtocol(&hsai_BlockB1, SAI_I2S_STANDARD, SAI_PROTOCOL_DATASIZE_32BIT, 2) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN SAI1_Init 2 */ /* USER CODE END SAI1_Init 2 */ } /** * @brief SPI1 Initialization Function * @param None * @retval None */ static void MX_SPI1_Init(void) { /* USER CODE BEGIN SPI1_Init 0 */ /* USER CODE END SPI1_Init 0 */ /* USER CODE BEGIN SPI1_Init 1 */ /* USER CODE END SPI1_Init 1 */ /* SPI1 parameter configuration*/ hspi1.Instance = SPI1; hspi1.Init.Mode = SPI_MODE_MASTER; hspi1.Init.Direction = SPI_DIRECTION_2LINES; hspi1.Init.DataSize = SPI_DATASIZE_8BIT; hspi1.Init.CLKPolarity = SPI_POLARITY_LOW; hspi1.Init.CLKPhase = SPI_PHASE_1EDGE; hspi1.Init.NSS = SPI_NSS_SOFT; hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi1.Init.TIMode = SPI_TIMODE_DISABLE; hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi1.Init.CRCPolynomial = 0x0; hspi1.Init.NSSPMode = SPI_NSS_PULSE_ENABLE; hspi1.Init.NSSPolarity = SPI_NSS_POLARITY_LOW; hspi1.Init.FifoThreshold = SPI_FIFO_THRESHOLD_01DATA; hspi1.Init.TxCRCInitializationPattern = SPI_CRC_INITIALIZATION_ALL_ZERO_PATTERN; hspi1.Init.RxCRCInitializationPattern = SPI_CRC_INITIALIZATION_ALL_ZERO_PATTERN; hspi1.Init.MasterSSIdleness = SPI_MASTER_SS_IDLENESS_00CYCLE; hspi1.Init.MasterInterDataIdleness = SPI_MASTER_INTERDATA_IDLENESS_00CYCLE; hspi1.Init.MasterReceiverAutoSusp = SPI_MASTER_RX_AUTOSUSP_DISABLE; hspi1.Init.MasterKeepIOState = SPI_MASTER_KEEP_IO_STATE_DISABLE; hspi1.Init.IOSwap = SPI_IO_SWAP_DISABLE; if (HAL_SPI_Init(&hspi1) != HAL_OK) { Error_Handler(); } /* USER CODE BEGIN SPI1_Init 2 */ /* USER CODE END SPI1_Init 2 */ } /** * @brief GPIO Initialization Function * @param None * @retval None */ static void MX_GPIO_Init(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /* GPIO Ports Clock Enable */ __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOH_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(CODEC_RST_GPIO_Port, CODEC_RST_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(BOARD_LED_GPIO_Port, BOARD_LED_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(T_CS_GPIO_Port, T_CS_Pin, GPIO_PIN_RESET); /*Configure GPIO pin Output Level */ HAL_GPIO_WritePin(GPIOD, DC_Pin|RST_Pin|CS_Pin, GPIO_PIN_RESET); /*Configure GPIO pin : CODEC_RST_Pin */ GPIO_InitStruct.Pin = CODEC_RST_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(CODEC_RST_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pin : BOARD_LED_Pin */ GPIO_InitStruct.Pin = BOARD_LED_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(BOARD_LED_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : T_SW_Pin F_SW_Pin */ GPIO_InitStruct.Pin = T_SW_Pin|F_SW_Pin; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /*Configure GPIO pin : T_CS_Pin */ GPIO_InitStruct.Pin = T_CS_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(T_CS_GPIO_Port, &GPIO_InitStruct); /*Configure GPIO pins : DC_Pin RST_Pin CS_Pin */ GPIO_InitStruct.Pin = DC_Pin|RST_Pin|CS_Pin; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); } /* USER CODE BEGIN 4 */ /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
#include <bits/stdc++.h> #include <cmath> using namespace std; map<int, int> prime_map; map<int, int> not_prime_map; void isPrime(const int num) { // Test if we know this number. if (num == 1 || prime_map.count(num) > 0) { cout << "Prime" << '\n'; return; } // prime_map contains all primed number between his first and last element. // If the num is below thann the last, then it's not prime (we'd have return otherwise). else if (not_prime_map.count(num) > 0) { cout << "Not prime" << '\n'; return; } int numSquare = sqrt(num); map<int, int>::iterator primeIt; // Loop over our primes and find out if it's divisible or not. for ( primeIt = prime_map.begin(); primeIt != prime_map.end() && primeIt->first <= numSquare; ++primeIt ) { bool divisibleByPrime = (num % primeIt->first == 0); if (divisibleByPrime) { cout << "Not prime" << '\n'; not_prime_map[num] = 1; return; } } // Loop until we the num to maybe discover new prime numbers and find out if num is Prime; int possible_prime = (prime_map.rbegin())->first + 2; for (;possible_prime <= numSquare;) { bool isPrime = true; for ( primeIt = prime_map.begin(); primeIt != prime_map.end() && primeIt->first <= sqrt(possible_prime); ++primeIt ) { bool divisibleByPrime = (possible_prime % primeIt->first == 0); if (divisibleByPrime) { isPrime = false; break; } } if (isPrime) prime_map[possible_prime] = 1; else not_prime_map[possible_prime] = 1; // Make sure that this possible prime is not a divider of our num. if (num != possible_prime && num % possible_prime == 0) { cout << "Not prime" << '\n'; return; } possible_prime += 2; } if (prime_map.count(num) > 0 || possible_prime > numSquare) { prime_map[num] = 1; cout << "Prime" << '\n'; } else { not_prime_map[possible_prime] = 1; cout << "Not prime" << '\n'; } } int main() { int p; cin >> p; cin.ignore(numeric_limits<streamsize>::max(), '\n'); prime_map[2] = 1; prime_map[3] = 1; prime_map[5] = 1; prime_map[7] = 1; prime_map[11] = 1; prime_map[13] = 1; prime_map[17] = 1; prime_map[19] = 1; prime_map[23] = 1; prime_map[29] = 1; for (int p_itr = 0; p_itr < p; p_itr++) { int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); isPrime(n); } return 0; }
// jhcOcvVSrc.cpp : reads videos using OpenCV infrastructure // // Written by Jonathan H. Connell, jconnell@alum.mit.edu // /////////////////////////////////////////////////////////////////////////// // // Copyright 2018 IBM Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////// // Linker additional library directories must have: // ../../OpenCV/build/x64/vc10/staticlib // Note: ALWAYS needs opencv_ffmpeg245_64.dll !!! #ifndef _DEBUG // needed for DLL or static libs #pragma comment(lib, "opencv_core245.lib") #pragma comment(lib, "opencv_highgui245.lib") // needed for static libs only #pragma comment(lib, "zlib.lib") #pragma comment(lib, "IlmImf.lib") #pragma comment(lib, "libjpeg.lib") #pragma comment(lib, "libjasper.lib") #pragma comment(lib, "libpng.lib") #pragma comment(lib, "libtiff.lib") #else // needed for DLL or static libs #pragma comment(lib, "opencv_core245d.lib") #pragma comment(lib, "opencv_highgui245d.lib") // needed for static libs only #pragma comment(lib, "zlibd.lib") #pragma comment(lib, "IlmImfd.lib") #pragma comment(lib, "libjpegd.lib") #pragma comment(lib, "libjasperd.lib") #pragma comment(lib, "libpngd.lib") #pragma comment(lib, "libtiffd.lib") #endif // extra Windows libraries #pragma comment(lib, "Comctl32.lib") #pragma comment(lib, "vfw32.lib") /////////////////////////////////////////////////////////////////////////// // C++ include directoires must have: // ../../OpenCv/sources/include // ../../OpenCV/build/include // ../../OpenCV/3rdparty/include/ffmpeg_ #include <windows.h> // needed for mutex #include <process.h> // for thread #include <string.h> #include "opencv2/opencv.hpp" #include "Interface/jhcMessage.h" #include "Interface/jms_x.h" #include "Video/jhcOcvVSrc.h" ////////////////////////////////////////////////////////////////////////////// // Register File Extensions // ////////////////////////////////////////////////////////////////////////////// // "ocv" is a dummy MIME-dispatch extension which gets stripped off #ifdef JHC_GVID #include "Video/jhcVidReg.h" JREG_VURL(jhcOcvVSrc, "ocv"); #endif /////////////////////////////////////////////////////////////////////////// // Creation and Initialization // /////////////////////////////////////////////////////////////////////////// //= Default destructor does necessary cleanup. jhcOcvVSrc::~jhcOcvVSrc () { HANDLE mutex = (HANDLE) lock, ready = (HANDLE) done; cv::VideoCapture *capture = (cv::VideoCapture *) cap; cv::Mat *frame; int i; // stop capturing and deallocate thread control items Prefetch(0); CloseHandle(mutex); CloseHandle(ready); // deallocate OpenCV items delete capture; for (i = 0; i < bsz; i++) { frame = (cv::Mat *) buf[i]; delete frame; } } //= Default constructor initializes certain values. jhcOcvVSrc::jhcOcvVSrc (const char *name, int index) { cv::VideoCapture *capture; int i; // save details of source strcpy_s(kind, "jhcOcvVSrc"); ParseName(name); ok = 0; // make up thread control items lock = (void *) CreateMutex(NULL, false, NULL); done = (void *) CreateEvent(NULL, TRUE, FALSE, NULL); bg = NULL; run = 0; // make up OpenCV capture object and array of frames capture = new cv::VideoCapture; cap = (void *) capture; for (i = 0; i < bsz; i++) buf[i] = (void *) new cv::Mat; // try opening source if (!capture->open(Trimmed())) return; if (!capture->isOpened()) return; ok = 1; // read size of images and get framerate w = ROUND(capture->get(CV_CAP_PROP_FRAME_WIDTH)); h = ROUND(capture->get(CV_CAP_PROP_FRAME_HEIGHT)); d = 3; freq = capture->get(CV_CAP_PROP_FPS); // set maximum staleness for newly captured frames lag = ROUND(2.0 * 1000.0 / freq); } /////////////////////////////////////////////////////////////////////////// // Main Functions // /////////////////////////////////////////////////////////////////////////// //= Start background thread reading images from stream. void jhcOcvVSrc::Prefetch (int doit) { HANDLE backg = (HANDLE) bg, ready = (HANDLE) done; int i; if ((doit > 0) && (run <= 0)) { // clear frame times for (i = 0; i < bsz; i++) tdec[i] = 0; fill = 0; // start background loop run = 1; ResetEvent(ready); bg = (void *) _beginthreadex(NULL, 0, grab_backg, this, 0, NULL); } else if ((doit <= 0) && (run > 0)) { // signal background thread to end then wait for exit run = 0; WaitForSingleObject(backg, 1000); CloseHandle(backg); bg = NULL; } } //= Read next frame from already open stream. int jhcOcvVSrc::iGet (jhcImg &dest, int *advance, int src, int block) { HANDLE mutex = (HANDLE) lock, ready = (HANDLE) done; cv::Mat *dump; DWORD tnow; int attempt, i, j, ans = 0; // make sure class was setup properly if (ok < 1) return 0; Prefetch(1); // possible retry a few times if bad frame received for (attempt = 0; (attempt < 10) && (ans <= 0); attempt++) { // wait for a new frame to be ready then lock buffers if (WaitForSingleObject(ready, 5000) != WAIT_OBJECT_0) return Complain("No new frame ready in jhcOcvVSrc::iGet"); if (WaitForSingleObject(mutex, 1000) != WAIT_OBJECT_0) return Complain("Failed to get buffer lock in jhcOcvVSrc::iGet"); // figure out which frame in circular buffer to read tnow = jms_now(); for (i = 1; i < bsz; i++) { // find oldest unread that is within "lag" ms of current time j = (fill + i) % bsz; if (tdec[j] == 0) continue; if (jms_diff(tnow, tdec[j]) <= lag) break; tdec[j] = 0; // frame unusable } // see if all cached frames now used up if (i >= (bsz - 1)) ResetEvent(ready); // check that a suitable frame was found if (i < bsz) { tdec[j] = 0; // prevent re-selection dump = (cv::Mat *) buf[j]; if (dump->data != NULL) ans = 1; } // minimize buffer lock time so no UDP packets dropped ReleaseMutex(mutex); } // image copy de facto guarded by long ring buffer if (ans > 0) dest.LoadFlip(dump->data); return ans; } //= Continuously grab frames into buffers (run as a separate thread). int jhcOcvVSrc::grab_loop () { HANDLE mutex = (HANDLE) lock, ready = (HANDLE) done; cv::VideoCapture *capture = (cv::VideoCapture *) cap; cv::Mat *frame; while (run > 0) { // get a frame into current array slot frame = (cv::Mat *) buf[fill]; if (!capture->read(*frame)) return 0; // lock buffers then save time and advance pointer if (WaitForSingleObject(mutex, 1000) != WAIT_OBJECT_0) return Complain("Failed to get buffer lock in jhcOcvVSrc::grab_loop"); tdec[fill] = jms_now(); fill = (fill + 1) % bsz; // signal new frame is available and unlock buffers SetEvent(ready); ReleaseMutex(mutex); } return 1; }
/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "gdcmCAPICryptographicMessageSyntax.h" #include <stdio.h> // fseek namespace gdcm { CAPICryptographicMessageSyntax::CAPICryptographicMessageSyntax() : hProv(0), hRsaPrivK(0), cipherType(AES128_CIPHER) { initialized = Initialize(); } CAPICryptographicMessageSyntax::~CAPICryptographicMessageSyntax() { for (std::vector<PCCERT_CONTEXT>::iterator it = certifList.begin(); it != certifList.end(); ++it) { CertFreeCertificateContext(*it); /*if (! CertFreeCertificateContext(*it)) { gdcmWarningMacro( "Error at releasing certificate context: " << std::hex << GetLastError() ); }*/ } if (hRsaPrivK) CryptDestroyKey(hRsaPrivK); if (!CryptReleaseContext(hProv, 0)) { gdcmWarningMacro("Error when releasing context: 0x" << std::hex << GetLastError()); } } // http://stackoverflow.com/questions/11709500/capi-does-not-support-password-based-encryption-pbe-encryption bool CAPICryptographicMessageSyntax::SetPassword(const char * , size_t ) { gdcmWarningMacro( "CAPI does not support Password Based Encryption." ); return false; } bool CAPICryptographicMessageSyntax::ParseCertificateFile( const char *filename ) { bool ret = false; unsigned char *certHexBuf = NULL, *certBin = NULL; DWORD certHexBufLen, certBinLen; if ( !LoadFile(filename, certHexBuf, certHexBufLen) ) goto err; // Call to get the needed amount of space if ( !CryptStringToBinaryA( (LPCSTR)certHexBuf, 0, CRYPT_STRING_BASE64_ANY, NULL, &certBinLen, NULL, NULL ) ) { gdcmErrorMacro( "CryptStringToBinary failed with error 0x" << std::hex << GetLastError() ); goto err; } certBin = new unsigned char[certBinLen]; // Convert from PEM format to DER format - removes header and footer and decodes from base64 if ( !CryptStringToBinaryA( (LPCSTR)certHexBuf, 0, CRYPT_STRING_BASE64_ANY, certBin, &certBinLen, NULL, NULL ) ) { gdcmErrorMacro( "CryptStringToBinary failed with error 0x" << std::hex << GetLastError() ); goto err; } PCCERT_CONTEXT certContext; certContext = CertCreateCertificateContext(X509_ASN_ENCODING, certBin, certBinLen); if (certContext == NULL) { gdcmErrorMacro( "CertCreateCertificateContext failed with error 0x" << std::hex << GetLastError() ); goto err; } certifList.push_back(certContext); ret = true; err: if (certBin) delete[] certBin; if (certHexBuf) delete[] certHexBuf; return ret; } bool CAPICryptographicMessageSyntax::ParseKeyFile( const char *filename ) { bool ret = false; unsigned char *keyHexBuffer = NULL, *keyBinBuffer = NULL, *keyBlob = NULL; DWORD keyHexBufferLen, keyBinBufferLen, keyBlobLen; HCRYPTKEY hKey = 0; if (!LoadFile(filename, keyHexBuffer, keyHexBufferLen)) goto err; if ( !CryptStringToBinaryA((LPCSTR)keyHexBuffer, 0, CRYPT_STRING_BASE64_ANY, NULL, &keyBinBufferLen, NULL, NULL) ) { gdcmErrorMacro( "Failed to convert from BASE64. CryptStringToBinary failed with error 0x" << std::hex << GetLastError() ); goto err; } keyBinBuffer = new unsigned char[keyBinBufferLen]; if ( !CryptStringToBinaryA((LPCSTR)keyHexBuffer, 0, CRYPT_STRING_BASE64_ANY, keyBinBuffer, &keyBinBufferLen, NULL, NULL) ) { gdcmErrorMacro( "Failed to convert from BASE64. CryptStringToBinary failed with error 0x" << std::hex << GetLastError() ); goto err; } if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, keyBinBuffer, keyBinBufferLen, 0, NULL, NULL, &keyBlobLen)) { gdcmErrorMacro( "Failed to parse private key. CryptDecodeObjectEx failed with error 0x" << std::hex << GetLastError() ); goto err; } keyBlob = new unsigned char[keyBlobLen]; if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, keyBinBuffer, keyBinBufferLen, 0, NULL, keyBlob, &keyBlobLen)) { gdcmErrorMacro( "Failed to parse private key. CryptDecodeObjectEx failed with error 0x" << std::hex << GetLastError() ); goto err; } if (!CryptImportKey(hProv, keyBlob, keyBlobLen, 0, 0, &hKey)) { gdcmErrorMacro( "CryptImportKey failed with error 0x" << std::hex << GetLastError() ); goto err; } if (hRsaPrivK) CryptDestroyKey(hRsaPrivK); hRsaPrivK = hKey; ret = true; err: if (keyHexBuffer) delete[] keyHexBuffer; if (keyBinBuffer) delete[] keyBinBuffer; if (keyBlob) delete[] keyBlob; return ret; } void CAPICryptographicMessageSyntax::SetCipherType(CryptographicMessageSyntax::CipherTypes type) { cipherType = type; } CryptographicMessageSyntax::CipherTypes CAPICryptographicMessageSyntax::GetCipherType() const { return cipherType; } bool CAPICryptographicMessageSyntax::Encrypt(char *output, size_t &outlen, const char *array, size_t len) const { CRYPT_ALGORITHM_IDENTIFIER EncryptAlgorithm = {0}; const char *objid = GetCipherObjId(); if( !objid ) { gdcmErrorMacro( "Could not GetCipherObjId" ); return false; } EncryptAlgorithm.pszObjId = (char*)objid; CRYPT_ENCRYPT_MESSAGE_PARA EncryptParams = {0}; EncryptParams.cbSize = sizeof(EncryptParams); EncryptParams.dwMsgEncodingType = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING; EncryptParams.hCryptProv = hProv; EncryptParams.ContentEncryptionAlgorithm = EncryptAlgorithm; if (certifList.size() == 0) { gdcmErrorMacro("No recipients certificates loaded."); return false; } if(! CryptEncryptMessage(&EncryptParams, (DWORD)certifList.size(), (PCCERT_CONTEXT *)&certifList[0], (unsigned char *)array, (DWORD)len, (unsigned char *)output, (DWORD *)&outlen) ) { DWORD dwResult = GetLastError(); gdcmErrorMacro( "Couldn't encrypt message. CryptEncryptMessage failed with error 0x" << std::hex << dwResult ); if (dwResult == CRYPT_E_UNKNOWN_ALGO) { gdcmErrorMacro("Unknown encryption algorithm. If on Windows XP please use only 3DES."); } return false; } return true; } bool CAPICryptographicMessageSyntax::Decrypt(char *output, size_t &outlen, const char *array, size_t len) const { bool ret = false; unsigned char* cek = NULL; HCRYPTMSG hMsg = NULL; PCMSG_CMS_RECIPIENT_INFO recipientInfo = NULL; DWORD dwMessageType, cbMessageTypeLen = sizeof(DWORD); PCRYPT_ALGORITHM_IDENTIFIER cekAlg = NULL; ALG_ID kekAlg; DWORD kekAlgLen = sizeof(ALG_ID); DWORD nrOfRecipeints, nrOfRecipientsLen = sizeof(DWORD); unsigned char* bareContent = NULL; struct { BLOBHEADER header; DWORD cbKeySize; unsigned char rgbKeyData[32]; //the maximum is 256 bit for aes } keyBlob = {{0}}; if (hRsaPrivK == 0) { gdcmErrorMacro("No private key loaded loaded."); return false; } if (! (hMsg = CryptMsgOpenToDecode(CRYPT_ASN_ENCODING | X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CMSG_ENVELOPED_DATA_PKCS_1_5_VERSION, 0, NULL, NULL)) ) { gdcmErrorMacro( "MsgOpenToDecode failed with error 0x" << std::hex << GetLastError() ); goto err; } if(! CryptMsgUpdate(hMsg, (unsigned char*)array, (DWORD)len, TRUE)) { gdcmErrorMacro( "MsgUpdate failed with error 0x" << std::hex << GetLastError() ); goto err; } if(! CryptMsgGetParam(hMsg, CMSG_TYPE_PARAM, 0, &dwMessageType, &cbMessageTypeLen)) { gdcmErrorMacro( "CryptMsgGetParam CMSG_TYPE_PARAM failed with error 0x" << std::hex << GetLastError() ); goto err; } if(dwMessageType != CMSG_ENVELOPED) { gdcmErrorMacro("Wrong message type ( != CMSG_ENVELOPED )"); goto err; } if(! CryptGetKeyParam(hRsaPrivK, KP_ALGID, (unsigned char*)&kekAlg, &kekAlgLen, 0)) { gdcmErrorMacro( "MsgGetParam KP_ALGID failed with error 0x" << std::hex << GetLastError() ); goto err; } if (kekAlg != CALG_RSA_KEYX) { gdcmErrorMacro( "Key encryption algorithm is not RSA." ); goto err; } if(! CryptMsgGetParam(hMsg, CMSG_RECIPIENT_COUNT_PARAM, 0, &nrOfRecipeints, &nrOfRecipientsLen)) { gdcmErrorMacro( "Decode CMSG_RECIPIENT_COUNT_PARAM failed with error 0x" << std::hex << GetLastError() ); goto err; } DWORD cekLen; { BOOL foundRecipient = FALSE; for (DWORD i=0; i < nrOfRecipeints; i++) { if (recipientInfo) delete[] recipientInfo; DWORD cbRecipientInfoLen; if(! CryptMsgGetParam(hMsg, CMSG_CMS_RECIPIENT_INFO_PARAM, i, NULL, &cbRecipientInfoLen)) { gdcmErrorMacro( "MsgGetParam CMSG_CMS_RECIPIENT_INFO_PARAM size failed with error 0x" << std::hex << GetLastError() ); goto err; } recipientInfo = (PCMSG_CMS_RECIPIENT_INFO) new unsigned char[cbRecipientInfoLen]; if(! CryptMsgGetParam(hMsg, CMSG_CMS_RECIPIENT_INFO_PARAM, i, recipientInfo, &cbRecipientInfoLen)) { gdcmErrorMacro( "MsgGetParam CMSG_CMS_RECIPIENT_INFO_PARAM failed with error 0x" << std::hex << GetLastError() ); goto err; } DWORD rsaPadding = 0; if (strcmp(recipientInfo->pKeyTrans->KeyEncryptionAlgorithm.pszObjId, szOID_RSAES_OAEP) == 0) { rsaPadding = CRYPT_OAEP; } //cek - content encryption key cekLen = recipientInfo->pKeyTrans->EncryptedKey.cbData; cek = recipientInfo->pKeyTrans->EncryptedKey.pbData; ReverseBytes(cek, cekLen); if ( (foundRecipient = CryptDecrypt(hRsaPrivK, 0, TRUE, rsaPadding, cek, &cekLen)) ) break; } // end loop recipients if (!foundRecipient) { gdcmErrorMacro( "No recipient found with the specified private key." ); goto err; } } DWORD cekAlgLen; if(! CryptMsgGetParam(hMsg, CMSG_ENVELOPE_ALGORITHM_PARAM, 0, NULL, &cekAlgLen)) { gdcmErrorMacro( "MsgGetParam CMSG_ENVELOPE_ALGORITHM_PARAM failed with error 0x" << std::hex << GetLastError() ); goto err; } cekAlg = (PCRYPT_ALGORITHM_IDENTIFIER) new unsigned char[cekAlgLen]; if(! CryptMsgGetParam(hMsg, CMSG_ENVELOPE_ALGORITHM_PARAM, 0, cekAlg, &cekAlgLen)) { gdcmErrorMacro( "MsgGetParam CMSG_ENVELOPE_ALGORITHM_PARAM failed with error 0x" << std::hex << GetLastError() ); goto err; } HCRYPTKEY hCEK; keyBlob.header.bType = PLAINTEXTKEYBLOB; keyBlob.header.bVersion = CUR_BLOB_VERSION; keyBlob.header.reserved = 0; keyBlob.header.aiKeyAlg = GetAlgIdByObjId(cekAlg->pszObjId); keyBlob.cbKeySize = cekLen; assert(cekLen <= 32); memcpy(keyBlob.rgbKeyData, cek, cekLen); if (!CryptImportKey(hProv, (unsigned char*)&keyBlob, sizeof(keyBlob), 0, 0, &hCEK)) { gdcmErrorMacro( "CryptImportKey failed with error 0x" << std::hex << GetLastError() ); goto err; } if(! CryptSetKeyParam(hCEK, KP_IV, (unsigned char *) cekAlg->Parameters.pbData+2, 0)) //+2 for ASN header ??? { gdcmErrorMacro( "SetKeyParam KP_IV failed with error 0x" << std::hex << GetLastError() ); goto err; } { DWORD dwMode = CRYPT_MODE_CBC; if(! CryptSetKeyParam(hCEK, KP_MODE, (unsigned char*) &dwMode, 0)) { gdcmErrorMacro( "SetKeyParam KP_MODE failed with error 0x" << std::hex << GetLastError() ); goto err; } } DWORD bareContentLen; if(! CryptMsgGetParam(hMsg, CMSG_CONTENT_PARAM, 0, NULL, &bareContentLen)) { gdcmErrorMacro( "MsgGetParam CMSG_BARE_CONTENT_PARAM size failed with error 0x" << std::hex << GetLastError() ); goto err; } bareContent = new unsigned char[bareContentLen]; if(! CryptMsgGetParam(hMsg, CMSG_CONTENT_PARAM, 0, bareContent, &bareContentLen)) { gdcmErrorMacro( "MsgGetParam CMSG_BARE_CONTENT_PARAM failed with error 0x" << std::hex << GetLastError() ); goto err; } if (! CryptDecrypt(hCEK, 0, TRUE, 0, bareContent, &bareContentLen)) { gdcmErrorMacro( "CryptDecrypt failed with error 0x" << std::hex << GetLastError() ); goto err; } if (bareContentLen > outlen) { gdcmErrorMacro( "Supplied output buffer too small: " << bareContentLen << " bytes needed." ); goto err; } memcpy(output, bareContent, bareContentLen); outlen = bareContentLen; ret = true; err: if (hMsg) CryptMsgClose(hMsg); if (recipientInfo) delete[] recipientInfo; if (bareContent) delete[] bareContent; if (cekAlg) delete[] cekAlg; return ret; } ALG_ID CAPICryptographicMessageSyntax::GetAlgIdByObjId(const char * pszObjId) { // HACK: fix compilation on mingw64: // See: http://sourceforge.net/tracker/?func=detail&aid=3561209&group_id=202880&atid=983354 #ifndef szOID_NIST_AES128_CBC #define szOID_NIST_AES128_CBC "2.16.840.1.101.3.4.1.2" #define szOID_NIST_AES192_CBC "2.16.840.1.101.3.4.1.22" #define szOID_NIST_AES256_CBC "2.16.840.1.101.3.4.1.42" #endif if (strcmp(pszObjId, szOID_NIST_AES128_CBC) == 0) { return CALG_AES_128; } else if (strcmp(pszObjId, szOID_NIST_AES192_CBC) == 0) { return CALG_AES_192; } else if (strcmp(pszObjId, szOID_NIST_AES256_CBC) == 0) { return CALG_AES_256; } else if (strcmp(pszObjId, szOID_RSA_DES_EDE3_CBC) == 0) { return CALG_3DES; } return 0; } const char *CAPICryptographicMessageSyntax::GetCipherObjId() const { switch( cipherType ) { case AES128_CIPHER: return szOID_NIST_AES128_CBC; case AES192_CIPHER: return szOID_NIST_AES192_CBC; case AES256_CIPHER: return szOID_NIST_AES256_CBC; case DES3_CIPHER: return szOID_RSA_DES_EDE3_CBC; } return 0; } bool CAPICryptographicMessageSyntax::Initialize() { DWORD dwResult; if (!CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) //CRYPT_VERIFYCONTEXT aes decr in cryptmsgcontrol not working { dwResult = GetLastError(); if (dwResult == NTE_BAD_KEYSET) { if (!CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_NEWKEYSET | CRYPT_VERIFYCONTEXT)) { dwResult = GetLastError(); gdcmErrorMacro( "CryptAcquireContext() failed:" << std::hex << dwResult); return false; } } else if (dwResult == NTE_KEYSET_NOT_DEF) { //Probably WinXP gdcmWarningMacro( "Certificate based encryption is supported on Windows XP only using 3DES." ); if (!CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV_A" (Prototype)" /*"Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"*/, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) //CRYPT_VERIFYCONTEXT aes decr in cryptmsgcontrol not working { dwResult = GetLastError(); if (dwResult == NTE_BAD_KEYSET) { if (!CryptAcquireContextA(&hProv, NULL, MS_ENH_RSA_AES_PROV_A" (Prototype)" /*"Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"*/, PROV_RSA_AES, CRYPT_NEWKEYSET | CRYPT_VERIFYCONTEXT)) { dwResult = GetLastError(); gdcmErrorMacro( "CryptAcquireContext() failed: " << std::hex << dwResult ); return false; } } else { dwResult = GetLastError(); return false; } } } else { dwResult = GetLastError(); return false; } } return true; } void CAPICryptographicMessageSyntax::ReverseBytes(unsigned char* data, DWORD len) { unsigned char temp; for (DWORD i = 0; i < len/2; i++) { temp = data[len-i-1]; data[len-i-1] = data[i]; data[i] = temp; } } bool CAPICryptographicMessageSyntax::LoadFile(const char * filename, unsigned char* & buffer, DWORD & bufLen) { assert( !buffer ); FILE * f = fopen(filename, "rb"); if (f == NULL) { gdcmErrorMacro("Couldn't open the file: " << filename); fclose(f); return false; } fseek(f, 0L, SEEK_END); long sz = ftell(f); rewind(f); buffer = new unsigned char[sz]; if( !buffer ) { fclose(f); return false; } bufLen = sz; while (sz) { size_t l = fread(buffer + bufLen - sz, sizeof(unsigned char), sz, f); sz -= (long)l; } fclose(f); return true; } } // end namespace gdcm
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #include "open3d/core/Dispatch.h" #include "open3d/core/ParallelFor.h" #include "open3d/core/Tensor.h" #include "open3d/core/kernel/Arange.h" namespace open3d { namespace core { namespace kernel { void ArangeCPU(const Tensor& start, const Tensor& stop, const Tensor& step, Tensor& dst) { Dtype dtype = start.GetDtype(); DISPATCH_DTYPE_TO_TEMPLATE(dtype, [&]() { scalar_t sstart = start.Item<scalar_t>(); scalar_t sstep = step.Item<scalar_t>(); scalar_t* dst_ptr = dst.GetDataPtr<scalar_t>(); int64_t n = dst.GetLength(); ParallelFor(start.GetDevice(), n, [&](int64_t workload_idx) { dst_ptr[workload_idx] = sstart + static_cast<scalar_t>(sstep * workload_idx); }); }); } } // namespace kernel } // namespace core } // namespace open3d
// Copyright (c) 2012-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util.h> #include <utiltime.h> #include <validation.h> #include <test/test_paycheckcash.h> #include <checkqueue.h> #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <atomic> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <unordered_set> #include <memory> #include <random.h> // BasicTestingSetup not sufficient because nScriptCheckThreads is not set // otherwise. BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const unsigned int QUEUE_BATCH_SIZE = 128; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck& x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { n_calls.fetch_add(1, std::memory_order_relaxed); return true; } void swap(FakeCheckCheckCompletion& x){}; }; struct FailingCheck { bool fails; FailingCheck(bool _fails) : fails(_fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck& x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck& x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b{false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck& x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; ~MemoryCheck() { fake_allocated_memory.fetch_sub(b, std::memory_order_relaxed); }; void swap(MemoryCheck& x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze{false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen.store(1, std::memory_order_relaxed); cv.notify_one(); cv.wait(l, [] { return nFrozen.load(std::memory_order_relaxed) == 0; }); } } void swap(FrozenCleanupCheck& x) { std::swap(should_freeze, x.should_freeze); }; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ static void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = std::unique_ptr<Correct_Queue>(new Correct_Queue{QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { small_queue->Thread(); }); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (auto i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t)InsecureRandRange(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); BOOST_TEST_MESSAGE("Failure on trial " << i << " expected, got " << FakeCheckCheckCompletion::n_calls); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000 / 1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min((size_t)1000, ((size_t)100000) - i)))) range.push_back(i); Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue{QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { fail_queue->Thread(); }); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = InsecureRandRange(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) vChecks.emplace_back(remaining == 1); control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue{QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { fail_queue->Thread(); }); } for (auto times = 0; times < 10; ++times) { for (bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r = control.Wait(); BOOST_REQUIRE(r != end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = std::unique_ptr<Unique_Queue>(new Unique_Queue{QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { queue->Thread(); }); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) vChecks.emplace_back(--total); control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) r = r && UniqueCheck::results.count(i) == 1; BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory aggressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = std::unique_ptr<Memory_Queue>(new Memory_Queue{QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { queue->Thread(); }); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i / 2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0U); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = std::unique_ptr<FrozenCleanup_Queue>(new FrozenCleanup_Queue{QUEUE_BATCH_SIZE}); boost::thread_group tg; bool fails = false; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&] { queue->Thread(); }); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); control.Wait(); // Hangs here }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait(l, []() { return FrozenCleanupCheck::nFrozen == 1; }); } // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } { // Unfreeze (we need lock n case of spurious wakeup) std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = std::unique_ptr<Standard_Queue>(new Standard_Queue{QUEUE_BATCH_SIZE}); { boost::thread_group tg; std::atomic<int> nThreads{0}; std::atomic<int> fails{0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread( [&] { CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; MilliSleep(10); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; std::condition_variable cv; bool has_lock{false}; bool has_tried{false}; bool done{false}; bool done_ack{false}; { std::unique_lock<std::mutex> l(m); tg.create_thread([&] { CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> ll(m); has_lock = true; cv.notify_one(); cv.wait(ll, [&] { return has_tried; }); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(ll, [&] { return done_ack; }); }); // Wait for thread to get the lock cv.wait(l, [&]() { return has_lock; }); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&]() { return done; }); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END()
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qplatformdefs.h> #include "qfilesystemwatcher.h" #include "qfilesystemwatcher_kqueue_p.h" #include "private/qcore_unix_p.h" #ifndef QT_NO_FILESYSTEMWATCHER #include <qdebug.h> #include <qfile.h> #include <qsocketnotifier.h> #include <qvarlengtharray.h> #include <sys/types.h> #include <sys/event.h> #include <sys/stat.h> #include <sys/time.h> #include <fcntl.h> QT_BEGIN_NAMESPACE // #define KEVENT_DEBUG #ifdef KEVENT_DEBUG # define DEBUG qDebug #else # define DEBUG if(false)qDebug #endif QKqueueFileSystemWatcherEngine *QKqueueFileSystemWatcherEngine::create(QObject *parent) { int kqfd = kqueue(); if (kqfd == -1) return 0; return new QKqueueFileSystemWatcherEngine(kqfd, parent); } QKqueueFileSystemWatcherEngine::QKqueueFileSystemWatcherEngine(int kqfd, QObject *parent) : QFileSystemWatcherEngine(parent), kqfd(kqfd), notifier(kqfd, QSocketNotifier::Read, this) { connect(&notifier, SIGNAL(activated(int)), SLOT(readFromKqueue())); fcntl(kqfd, F_SETFD, FD_CLOEXEC); } QKqueueFileSystemWatcherEngine::~QKqueueFileSystemWatcherEngine() { notifier.setEnabled(false); close(kqfd); foreach (int id, pathToID) ::close(id < 0 ? -id : id); } QStringList QKqueueFileSystemWatcherEngine::addPaths(const QStringList &paths, QStringList *files, QStringList *directories) { QStringList p = paths; QMutableListIterator<QString> it(p); while (it.hasNext()) { QString path = it.next(); int fd; #if defined(O_EVTONLY) fd = qt_safe_open(QFile::encodeName(path), O_EVTONLY); #else fd = qt_safe_open(QFile::encodeName(path), O_RDONLY); #endif if (fd == -1) { perror("QKqueueFileSystemWatcherEngine::addPaths: open"); continue; } if (fd >= (int)FD_SETSIZE / 2 && fd < (int)FD_SETSIZE) { int fddup = fcntl(fd, F_DUPFD, FD_SETSIZE); if (fddup != -1) { ::close(fd); fd = fddup; } } fcntl(fd, F_SETFD, FD_CLOEXEC); QT_STATBUF st; if (QT_FSTAT(fd, &st) == -1) { perror("QKqueueFileSystemWatcherEngine::addPaths: fstat"); ::close(fd); continue; } int id = (S_ISDIR(st.st_mode)) ? -fd : fd; if (id < 0) { if (directories->contains(path)) { ::close(fd); continue; } } else { if (files->contains(path)) { ::close(fd); continue; } } struct kevent kev; EV_SET(&kev, fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_RENAME | NOTE_REVOKE, 0, 0); if (kevent(kqfd, &kev, 1, 0, 0, 0) == -1) { perror("QKqueueFileSystemWatcherEngine::addPaths: kevent"); ::close(fd); continue; } it.remove(); if (id < 0) { DEBUG() << "QKqueueFileSystemWatcherEngine: added directory path" << path; directories->append(path); } else { DEBUG() << "QKqueueFileSystemWatcherEngine: added file path" << path; files->append(path); } pathToID.insert(path, id); idToPath.insert(id, path); } return p; } QStringList QKqueueFileSystemWatcherEngine::removePaths(const QStringList &paths, QStringList *files, QStringList *directories) { bool isEmpty; QStringList p = paths; if (pathToID.isEmpty()) return p; QMutableListIterator<QString> it(p); while (it.hasNext()) { QString path = it.next(); int id = pathToID.take(path); QString x = idToPath.take(id); if (x.isEmpty() || x != path) continue; ::close(id < 0 ? -id : id); it.remove(); if (id < 0) directories->removeAll(path); else files->removeAll(path); } isEmpty = pathToID.isEmpty(); return p; } void QKqueueFileSystemWatcherEngine::readFromKqueue() { forever { DEBUG() << "QKqueueFileSystemWatcherEngine: polling for changes"; int r; struct kevent kev; struct timespec ts = { 0, 0 }; // 0 ts, because we want to poll EINTR_LOOP(r, kevent(kqfd, 0, 0, &kev, 1, &ts)); if (r < 0) { perror("QKqueueFileSystemWatcherEngine: error during kevent wait"); return; } else if (r == 0) { // polling returned no events, so stop break; } else { int fd = kev.ident; DEBUG() << "QKqueueFileSystemWatcherEngine: processing kevent" << kev.ident << kev.filter; int id = fd; QString path = idToPath.value(id); if (path.isEmpty()) { // perhaps a directory? id = -id; path = idToPath.value(id); if (path.isEmpty()) { DEBUG() << "QKqueueFileSystemWatcherEngine: received a kevent for a file we're not watching"; continue; } } if (kev.filter != EVFILT_VNODE) { DEBUG() << "QKqueueFileSystemWatcherEngine: received a kevent with the wrong filter"; continue; } if ((kev.fflags & (NOTE_DELETE | NOTE_REVOKE | NOTE_RENAME)) != 0) { DEBUG() << path << "removed, removing watch also"; pathToID.remove(path); idToPath.remove(id); ::close(fd); if (id < 0) emit directoryChanged(path, true); else emit fileChanged(path, true); } else { DEBUG() << path << "changed"; if (id < 0) emit directoryChanged(path, false); else emit fileChanged(path, false); } } } } #endif //QT_NO_FILESYSTEMWATCHER QT_END_NAMESPACE
#include <bits/stdc++.h> using namespace std; bool H[400414]; int DP[300313], D[400414][26], n; int main() { ios_base::sync_with_stdio(0);cin.tie(0); string str, s; for (int cse=1; cin >> str >> n; ++cse) { int scnt = 0; memset(D[scnt], 0, 26*sizeof(int)); for (int i=0; i<n; ++i) { cin >> s; int st = 0; for (int i=0; s[i]; ++i) { int u = s[i]-'a'; if (!D[st][u]) { D[st][u] = ++scnt; memset(D[scnt], 0, 26*sizeof(int)); H[scnt] = 0; } st = D[st][u]; } H[st] = 1; } DP[str.length()] = 1; for (int i=str.length()-1; i>=0; --i) { int st = DP[i] = 0; for (int j=i; str[j]; ++j) { st = D[st][str[j]-'a']; if (!st) break; if (H[st]) { DP[i] += DP[j+1]; if (DP[i] >= 20071027) DP[i] %= 20071027; } } } cout << "Case " << cse << ": " << DP[0] << '\n'; } }
#include "uart.h" #include <void/interrupt.h> #include <cph/platform/interrupt_tag_define.h> extern "C" { #if defined(CPH_HAS_UART0) & defined(CPH_ENABLE_UART0) VOID_ISR(CPH_INT_USART0_RXC) { PROVIDE_ENTRY(CPH_INT_USART0_RXC); cph::Usart0::IntRxHandler(); } VOID_ISR(CPH_INT_USART0_TXE) { PROVIDE_ENTRY(CPH_INT_USART0_TXE); cph::Usart0::IntTxEmptyHandler(); } #endif }
#include "locale.hpp" #include <cstring> #include <clocale> #include <algorithm> #undef min #undef max namespace locale { std::vector<std::pair<std::string_view, std::string_view>> ListLocales() { std::vector<std::pair<std::string_view, std::string_view>> ret; ret.reserve(std::size_t(ELocale::MAXLocale)); for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) ret.emplace_back(GetName(l), GetFullName(l)); return ret; } ELocale LookupLocale(std::string_view name) { for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) if (name == GetName(l)) return l; return ELocale::Invalid; } ELocale SystemLocaleOrEnglish() { const char* sysLocale = std::setlocale(LC_ALL, nullptr); size_t sysLocaleLen = std::strlen(sysLocale); for (ELocale l = ELocale(0); l < ELocale::MAXLocale; l = ELocale(int(l) + 1)) { auto name = GetName(l); if (!name.compare(0, std::min(name.size(), sysLocaleLen), sysLocale)) return l; } return ELocale::en_US; } } // namespace locale
#ifndef MARLIN_CORE_FIBERS_SENTINELBUFFERFIBER_HPP #define MARLIN_CORE_FIBERS_SENTINELBUFFERFIBER_HPP #include <marlin/core/Buffer.hpp> #include <marlin/core/fibers/FiberScaffold.hpp> namespace marlin { namespace core { template<typename ExtFabric> class SentinelBufferFiber : public FiberScaffold< SentinelBufferFiber<ExtFabric>, ExtFabric, Buffer, Buffer > { public: using SelfType = SentinelBufferFiber<ExtFabric>; using FiberScaffoldType = FiberScaffold< SelfType, ExtFabric, Buffer, Buffer >; using typename FiberScaffoldType::InnerMessageType; using typename FiberScaffoldType::OuterMessageType; using FiberScaffoldType::FiberScaffoldType; core::Buffer buf = core::Buffer(0); void reset(uint64_t max_len) { buf = core::Buffer(max_len); buf.truncate_unsafe(max_len); } int did_recv(auto&&, InnerMessageType&& bytes, SocketAddress) { auto idx = buf.size(); // expand and check if there is enough room to copy if(!buf.expand(bytes.size())) { // no room, error and return return -1; } // have room, copy buf.write_unsafe(idx, bytes.data(), bytes.size()); return 0; } int did_recv_sentinel(auto&&, SocketAddress addr) { // pass on msg return FiberScaffoldType::did_recv(*this, std::move(buf), addr); } }; } // namespace core } // namespace marlin #endif // MARLIN_CORE_FIBERS_SENTINELBUFFERFIBER_HPP
// ==================================================================== // This file is part of FlexibleSUSY. // // FlexibleSUSY is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // FlexibleSUSY is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FlexibleSUSY. If not, see // <http://www.gnu.org/licenses/>. // ==================================================================== // File generated at Thu 10 May 2018 14:34:23 #include "MSSMatMGUTEFTHiggs_mAmu_soft_parameters.hpp" #include "wrappers.hpp" namespace flexiblesusy { #define INPUT(parameter) input.parameter #define TRACE_STRUCT soft_traces namespace { template <typename Derived> typename Eigen::MatrixBase<Derived>::PlainObject operator+(const Eigen::MatrixBase<Derived>& m, double n) { return m + Eigen::Matrix<double, Eigen::MatrixBase<Derived>::RowsAtCompileTime, Eigen::MatrixBase<Derived>::ColsAtCompileTime>::Identity() * n; } template <typename Derived> typename Eigen::MatrixBase<Derived>::PlainObject operator+(double n, const Eigen::MatrixBase<Derived>& m) { return m + Eigen::Matrix<double, Eigen::MatrixBase<Derived>::RowsAtCompileTime, Eigen::MatrixBase<Derived>::ColsAtCompileTime>::Identity() * n; } template <typename Derived> typename Eigen::MatrixBase<Derived>::PlainObject operator-(const Eigen::MatrixBase<Derived>& m, double n) { return m - Eigen::Matrix<double, Eigen::MatrixBase<Derived>::RowsAtCompileTime, Eigen::MatrixBase<Derived>::ColsAtCompileTime>::Identity() * n; } template <typename Derived> typename Eigen::MatrixBase<Derived>::PlainObject operator-(double n, const Eigen::MatrixBase<Derived>& m) { return - m + Eigen::Matrix<double, Eigen::MatrixBase<Derived>::RowsAtCompileTime, Eigen::MatrixBase<Derived>::ColsAtCompileTime>::Identity() * n; } } // anonymous namespace /** * Calculates the 1-loop beta function of mu2. * * @return 1-loop beta function */ Eigen::Matrix<double,3,3> MSSMatMGUTEFTHiggs_mAmu_soft_parameters::calc_beta_mu2_1_loop(const Soft_traces& soft_traces) const { const double Tr11 = TRACE_STRUCT.Tr11; Eigen::Matrix<double,3,3> beta_mu2; beta_mu2 = (oneOver16PiSqr*(4*mHu2*(Yu*Yu.adjoint()) + 4*(TYu*(TYu) .adjoint()) + 2*(mu2*Yu*Yu.adjoint()) + 4*(Yu*mq2*Yu.adjoint()) + 2*(Yu* Yu.adjoint()*mu2) - 0.26666666666666666*(3.872983346207417*g1*Tr11 + 8* AbsSqr(MassB)*Sqr(g1) + 40*AbsSqr(MassG)*Sqr(g3))*UNITMATRIX(3))).real(); return beta_mu2; } /** * Calculates the 2-loop beta function of mu2. * * @return 2-loop beta function */ Eigen::Matrix<double,3,3> MSSMatMGUTEFTHiggs_mAmu_soft_parameters::calc_beta_mu2_2_loop(const Soft_traces& soft_traces) const { const double traceYuAdjYu = TRACE_STRUCT.traceYuAdjYu; const double traceconjTYuTpTYu = TRACE_STRUCT.traceconjTYuTpTYu; const double tracemq2AdjYuYu = TRACE_STRUCT.tracemq2AdjYuYu; const double tracemu2YuAdjYu = TRACE_STRUCT.tracemu2YuAdjYu; const double traceAdjYuTYu = TRACE_STRUCT.traceAdjYuTYu; const double traceconjTYuTpYu = TRACE_STRUCT.traceconjTYuTpYu; const double Tr2U111 = TRACE_STRUCT.Tr2U111; const double Tr31 = TRACE_STRUCT.Tr31; const double Tr23 = TRACE_STRUCT.Tr23; Eigen::Matrix<double,3,3> beta_mu2; beta_mu2 = (twoLoop*(-0.8*(15*traceconjTYuTpTYu + 15*tracemq2AdjYuYu + 15*tracemu2YuAdjYu + 30*mHu2*traceYuAdjYu + mHu2*Sqr(g1) + 2*AbsSqr( MassB)*Sqr(g1) - 15*mHu2*Sqr(g2) - 30*AbsSqr(MassWB)*Sqr(g2))*(Yu* Yu.adjoint()) + (0.8*MassB*Sqr(g1) - 12*(traceAdjYuTYu + MassWB*Sqr(g2))) *(Yu*(TYu).adjoint()) + (0.8*Conj(MassB)*Sqr(g1) - 12*(traceconjTYuTpYu + Conj(MassWB)*Sqr(g2)))*(TYu*Yu.adjoint()) - 0.8*(Sqr(g1) + 15*( traceYuAdjYu - Sqr(g2)))*(TYu*(TYu).adjoint()) + (-6*traceYuAdjYu - 0.4* Sqr(g1) + 6*Sqr(g2))*(mu2*Yu*Yu.adjoint()) - 0.8*(Sqr(g1) + 15*( traceYuAdjYu - Sqr(g2)))*(Yu*mq2*Yu.adjoint()) + (-6*traceYuAdjYu - 0.4* Sqr(g1) + 6*Sqr(g2))*(Yu*Yu.adjoint()*mu2) - 4*(mHd2 + mHu2)*(Yu* Yd.adjoint()*Yd*Yu.adjoint()) - 4*(Yu*Yd.adjoint()*TYd*(TYu).adjoint()) - 8*mHu2*(Yu*Yu.adjoint()*Yu*Yu.adjoint()) - 4*(Yu*Yu.adjoint()*TYu*(TYu) .adjoint()) - 4*(Yu*(TYd).adjoint()*TYd*Yu.adjoint()) - 4*(Yu*(TYu) .adjoint()*TYu*Yu.adjoint()) - 4*(TYu*Yd.adjoint()*Yd*(TYu).adjoint()) - 4*(TYu*Yu.adjoint()*Yu*(TYu).adjoint()) - 4*(TYu*(TYd).adjoint()*Yd* Yu.adjoint()) - 4*(TYu*(TYu).adjoint()*Yu*Yu.adjoint()) - 2*(mu2*Yu* Yd.adjoint()*Yd*Yu.adjoint()) - 2*(mu2*Yu*Yu.adjoint()*Yu*Yu.adjoint()) - 4*(Yu*mq2*Yd.adjoint()*Yd*Yu.adjoint()) - 4*(Yu*mq2*Yu.adjoint()*Yu* Yu.adjoint()) - 4*(Yu*Yd.adjoint()*md2*Yd*Yu.adjoint()) - 4*(Yu* Yd.adjoint()*Yd*mq2*Yu.adjoint()) - 2*(Yu*Yd.adjoint()*Yd*Yu.adjoint()* mu2) - 4*(Yu*Yu.adjoint()*mu2*Yu*Yu.adjoint()) - 4*(Yu*Yu.adjoint()*Yu* mq2*Yu.adjoint()) - 2*(Yu*Yu.adjoint()*Yu*Yu.adjoint()*mu2) + 0.07111111111111111*(2*Conj(MassB)*(321*MassB*Quad(g1) + 40*(2*MassB + MassG)*Sqr(g1)*Sqr(g3)) + 5*(-11.618950038622252*g1*Tr31 + 30*Tr23*Quad( g3) + 6*Tr2U111*Sqr(g1) + 8*Conj(MassG)*Sqr(g3)*(2*(MassB + 2*MassG)*Sqr( g1) - 15*MassG*Sqr(g3))))*UNITMATRIX(3))).real(); return beta_mu2; } /** * Calculates the 3-loop beta function of mu2. * * @return 3-loop beta function */ Eigen::Matrix<double,3,3> MSSMatMGUTEFTHiggs_mAmu_soft_parameters::calc_beta_mu2_3_loop(const Soft_traces& soft_traces) const { DEFINE_PROJECTOR(3,3,3,3) Eigen::Matrix<double,3,3> beta_mu2; beta_mu2 = ZEROMATRIX(3,3); return beta_mu2; } } // namespace flexiblesusy
#ifndef WIN32 #include <unistd.h> #include <cstdlib> #include <cstring> #include <netdb.h> #else #include <winsock2.h> #include <ws2tcpip.h> #include <wspiapi.h> #endif #include <iostream> #include <udt.h> #include "cc.h" #include "test_util.h" using namespace std; #ifndef WIN32 void* monitor(void*); #else DWORD WINAPI monitor(LPVOID); #endif int main(int argc, char* argv[]) { if ((3 != argc) || (0 == atoi(argv[2]))) { cout << "usage: appclient server_ip server_port" << endl; return 0; } // Automatically start up and clean up UDT module. UDTUpDown _udt_; struct addrinfo hints, *local, *peer; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; //hints.ai_socktype = SOCK_DGRAM; if (0 != getaddrinfo(NULL, "9000", &hints, &local)) { cout << "incorrect network address.\n" << endl; return 0; } UDTSOCKET client = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol); // UDT Options UDT::setsockopt(client, 0, UDT_CC, new CCCFactory<PCC>, sizeof(CCCFactory<PCC>)); //UDT::setsockopt(client, 0, UDT_MSS, new int(9000), sizeof(int)); //UDT::setsockopt(client, 0, UDT_SNDBUF, new int(10000000), sizeof(int)); //UDT::setsockopt(client, 0, UDP_SNDBUF, new int(10000000), sizeof(int)); //UDT::setsockopt(client, 0, UDT_MAXBW, new int64_t(12500000), sizeof(int)); // Windows UDP issue // For better performance, modify HKLM\System\CurrentControlSet\Services\Afd\Parameters\FastSendDatagramThreshold #ifdef WIN32 UDT::setsockopt(client, 0, UDT_MSS, new int(1052), sizeof(int)); #endif // for rendezvous connection, enable the code below /* UDT::setsockopt(client, 0, UDT_RENDEZVOUS, new bool(true), sizeof(bool)); if (UDT::ERROR == UDT::bind(client, local->ai_addr, local->ai_addrlen)) { cout << "bind: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } */ freeaddrinfo(local); if (0 != getaddrinfo(argv[1], argv[2], &hints, &peer)) { cout << "incorrect server/peer address. " << argv[1] << ":" << argv[2] << endl; return 0; } // connect to the server, implict bind if (UDT::ERROR == UDT::connect(client, peer->ai_addr, peer->ai_addrlen)) { cout << "connect: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } freeaddrinfo(peer); // using CC method //CUDPBlast* cchandle = NULL; //int temp; //UDT::getsockopt(client, 0, UDT_CC, &cchandle, &temp); //if (NULL != cchandle) // cchandle->setRate(500); int size = 100000; char* data = new char[size]; #ifndef WIN32 pthread_create(new pthread_t, NULL, monitor, &client); #else CreateThread(NULL, 0, monitor, &client, 0, NULL); #endif for (int i = 0; i < 1000000; i ++) { int ssize = 0; int ss; while (ssize < size) { if (UDT::ERROR == (ss = UDT::send(client, data + ssize, size - ssize, 0))) { cout << "send:" << UDT::getlasterror().getErrorMessage() << endl; break; } ssize += ss; } if (ssize < size) break; } UDT::close(client); delete [] data; return 0; } #ifndef WIN32 void* monitor(void* s) #else DWORD WINAPI monitor(LPVOID s) #endif { UDTSOCKET u = *(UDTSOCKET*)s; UDT::TRACEINFO perf; cout << "SendRate(Mb/s)--Bw--LossRate"<< endl; while (true) { #ifndef WIN32 sleep(1); #else Sleep(1000); #endif if (UDT::ERROR == UDT::perfmon(u, &perf)) { cout << "perfmon: " << UDT::getlasterror().getErrorMessage() << endl; break; } cout << perf.mbpsSendRate << "\t\t" << perf.mbpsBandwidth << "\t" << (double)perf.pktSndLoss/perf.pktSent<< "\t" <<perf.msRTT <<endl; } #ifndef WIN32 return NULL; #else return 0; #endif }
/****************************************************************** * * mUPnP for C * * Copyright (C) Satoshi Konno 2005 * Copyright (C) 2006 Nokia Corporation. All rights reserved. * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/test/unit_test.hpp> #include <limits.h> #include <mupnp/xml/xml.h> //////////////////////////////////////// // XML //////////////////////////////////////// BOOST_AUTO_TEST_CASE(XMLChildNode) { const char* XML_CHILD_NODE_NAME = "cnode"; const char* XML_CHILD_NODE_VALUE = "cnode_value"; mUpnpXmlNode* parentNode = mupnp_xml_node_new(); BOOST_CHECK(parentNode); BOOST_CHECK(!mupnp_xml_node_removechildnode(parentNode, XML_CHILD_NODE_NAME)); // Set child node mupnp_xml_node_setchildnode(parentNode, XML_CHILD_NODE_NAME, XML_CHILD_NODE_VALUE); mUpnpXmlNode* childNode = mupnp_xml_node_getchildnode(parentNode, XML_CHILD_NODE_NAME); BOOST_CHECK(childNode); BOOST_CHECK_EQUAL(strcmp(XML_CHILD_NODE_VALUE, mupnp_xml_node_getvalue(childNode)), 0); BOOST_CHECK_EQUAL(strcmp(XML_CHILD_NODE_VALUE, mupnp_xml_node_getchildnodevalue(parentNode, XML_CHILD_NODE_NAME)), 0); // Remove child node BOOST_CHECK(mupnp_xml_node_removechildnode(parentNode, XML_CHILD_NODE_NAME)); BOOST_CHECK(mupnp_xml_node_getchildnode(parentNode, XML_CHILD_NODE_NAME) == NULL); }
// ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // Cedric Nugteren <www.cedricnugteren.nl> // // ================================================================================================= #include "test/performance/client.hpp" #include "test/routines/level3/xhemm.hpp" // Shortcuts to the clblast namespace using float2 = clblast::float2; using double2 = clblast::double2; // Main function (not within the clblast namespace) int main(int argc, char *argv[]) { switch(clblast::GetPrecision(argc, argv, clblast::Precision::kComplexSingle)) { case clblast::Precision::kHalf: throw std::runtime_error("Unsupported precision mode"); case clblast::Precision::kSingle: throw std::runtime_error("Unsupported precision mode"); case clblast::Precision::kDouble: throw std::runtime_error("Unsupported precision mode"); case clblast::Precision::kComplexSingle: clblast::RunClient<clblast::TestXhemm<float2>, float2, float2>(argc, argv); break; case clblast::Precision::kComplexDouble: clblast::RunClient<clblast::TestXhemm<double2>, double2, double2>(argc, argv); break; } return 0; } // =================================================================================================
#include <vtkImageData.h> #include <vtkImplicitDataSet.h> #include <vtkNew.h> #include <vtkRTAnalyticSource.h> #include <vtkSphereSource.h> int main(int /* argc */, char* /* argv */[]) { vtkNew<vtkRTAnalyticSource> waveletSource; waveletSource->Update(); vtkNew<vtkImplicitDataSet> implicitWavelet; implicitWavelet->SetDataSet(waveletSource->GetOutput()); double x[3] = {0.5, 0, 0}; // Value should roughly be 258.658. cout << "x: " << implicitWavelet->EvaluateFunction(x) << endl; return EXIT_SUCCESS; }
// VisualBoyAdvance - Nintendo Gameboy/GameboyAdvance (TM) emulator. // Copyright (C) 1999-2003 Forgotten // Copyright (C) 2004 Forgotten and the VBA development team // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2, or(at your option) // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. #include <mednafen/mednafen.h> #include "Gfx.h" #include "gfx-draw.h" namespace MDFN_IEN_GBA { int all_coeff[32] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 }; uint32 AlphaClampLUT[64] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F }; alignas(16) uint32 line0[512]; alignas(16) uint32 line1[512]; alignas(16) uint32 line2[512]; alignas(16) uint32 line3[512]; alignas(16) uint32 lineOBJ[512]; alignas(16) uint32 lineOBJWin[512]; alignas(16) uint32 lineMix[512]; bool gfxInWin0[512]; bool gfxInWin1[512]; int gfxBG2Changed = 0; int gfxBG3Changed = 0; int gfxBG2X = 0; int gfxBG2Y = 0; int gfxBG2LastX = 0; int gfxBG2LastY = 0; int gfxBG3X = 0; int gfxBG3Y = 0; int gfxBG3LastX = 0; int gfxBG3LastY = 0; int gfxLastVCOUNT = 0; void gfxDrawTextScreen(uint16 control, uint16 hofs, uint16 vofs, uint32 *line) { uint16 *palette = (uint16 *)paletteRAM; uint8 *charBase = &vram[((control >> 2) & 0x03) * 0x4000]; uint16 *screenBase = (uint16 *)&vram[((control >> 8) & 0x1f) * 0x800]; uint32 prio = ((control & 3)<<25) + 0x1000000; int sizeX = 256; int sizeY = 256; switch((control >> 14) & 3) { case 0: break; case 1: sizeX = 512; break; case 2: sizeY = 512; break; case 3: sizeX = 512; sizeY = 512; break; } int maskX = sizeX-1; int maskY = sizeY-1; bool mosaicOn = (control & 0x40) ? true : false; int xxx = hofs & maskX; int yyy = (vofs + VCOUNT) & maskY; int mosaicX = (MOSAIC & 0x000F)+1; int mosaicY = ((MOSAIC & 0x00F0)>>4)+1; if(mosaicOn) { if((VCOUNT % mosaicY) != 0) { mosaicY = (VCOUNT / mosaicY) * mosaicY; yyy = (vofs + mosaicY) & maskY; } } if(yyy > 255 && sizeY > 256) { yyy &= 255; screenBase += 0x400; if(sizeX > 256) screenBase += 0x400; } int yshift = ((yyy>>3)<<5); if((control) & 0x80) { uint16 *screenSource = screenBase + 0x400 * (xxx>>8) + ((xxx & 255)>>3) + yshift; for(int x = 0; x < 240; x++) { uint16 data = READ16LE(screenSource); int tile = data & 0x3FF; int tileX = (xxx & 7); int tileY = yyy & 7; if(data & 0x0400) tileX = 7 - tileX; if(data & 0x0800) tileY = 7 - tileY; uint8 color = charBase[tile * 64 + tileY * 8 + tileX]; line[x] = color ? (READ16LE(&palette[color]) | prio): 0x80000000; if(data & 0x0400) { if(tileX == 0) screenSource++; } else if(tileX == 7) screenSource++; xxx++; if(xxx == 256) { if(sizeX > 256) screenSource = screenBase + 0x400 + yshift; else { screenSource = screenBase + yshift; xxx = 0; } } else if(xxx >= sizeX) { xxx = 0; screenSource = screenBase + yshift; } } } else { uint16 *screenSource = screenBase + 0x400*(xxx>>8)+((xxx&255)>>3) + yshift; uint16 data = READ16LE(screenSource); int tile = data & 0x3FF; int pal = (READ16LE(screenSource)>>8) & 0xF0; int tileXmatch = (data & 0x0400) ? 0 : 7; for(int x = 0; x < 240; x++) { int tileX = (xxx & 7); int tileY = yyy & 7; if(data & 0x0400) tileX = 7 - tileX; if(data & 0x0800) tileY = 7 - tileY; uint8 color = charBase[(tile<<5) + (tileY<<2) + (tileX>>1)]; if(tileX & 1) { color = (color >> 4); } else { color &= 0x0F; } line[x] = color ? (READ16LE(&palette[pal + color])|prio): 0x80000000; if(tileX == tileXmatch) { screenSource++; data = READ16LE(screenSource); tile = data & 0x3FF; pal = (READ16LE(screenSource)>>8) & 0xF0; tileXmatch = (data & 0x0400) ? 0 : 7; } xxx++; if(xxx == 256) { if(sizeX > 256) screenSource = screenBase + 0x400 + yshift; else { screenSource = screenBase + yshift; xxx = 0; } data = READ16LE(screenSource); tile = data & 0x3FF; pal = (READ16LE(screenSource)>>8) & 0xF0; tileXmatch = (data & 0x0400) ? 0 : 7; } else if(xxx >= sizeX) { xxx = 0; screenSource = screenBase + yshift; data = READ16LE(screenSource); tile = data & 0x3FF; pal = (READ16LE(screenSource)>>8) & 0xF0; tileXmatch = (data & 0x0400) ? 0 : 7; } } } if(mosaicOn) { if(mosaicX > 1) { int m = 1; for(int i = 0; i < 239; i++) { line[i+1] = line[i]; m++; if(m == mosaicX) { m = 1; i++; } } } } } void gfxDrawRotScreen(uint16 control, uint16 x_l, uint16 x_h, uint16 y_l, uint16 y_h, uint16 pa, uint16 pb, uint16 pc, uint16 pd, int& currentX, int& currentY, int changed, uint32 *line) { uint16 *palette = (uint16 *)paletteRAM; uint8 *charBase = &vram[((control >> 2) & 0x03) * 0x4000]; uint8 *screenBase = (uint8 *)&vram[((control >> 8) & 0x1f) * 0x800]; int prio = ((control & 3) << 25) + 0x1000000; int sizeX = 128; int sizeY = 128; switch((control >> 14) & 3) { case 0: break; case 1: sizeX = sizeY = 256; break; case 2: sizeX = sizeY = 512; break; case 3: sizeX = sizeY = 1024; break; } int dx = pa & 0x7FFF; if(pa & 0x8000) dx |= 0xFFFF8000; int dmx = pb & 0x7FFF; if(pb & 0x8000) dmx |= 0xFFFF8000; int dy = pc & 0x7FFF; if(pc & 0x8000) dy |= 0xFFFF8000; int dmy = pd & 0x7FFF; if(pd & 0x8000) dmy |= 0xFFFF8000; if(VCOUNT == 0) changed = 3; if(changed & 1) { currentX = (x_l) | ((x_h & 0x07FF)<<16); if(x_h & 0x0800) currentX |= 0xF8000000; } else { currentX += dmx; } if(changed & 2) { currentY = (y_l) | ((y_h & 0x07FF)<<16); if(y_h & 0x0800) currentY |= 0xF8000000; } else { currentY += dmy; } int realX = currentX; int realY = currentY; if(control & 0x40) { int mosaicY = ((MOSAIC & 0xF0)>>4) + 1; int y = (VCOUNT % mosaicY); realX -= y*dmx; realY -= y*dmy; } int xxx = (realX >> 8); int yyy = (realY >> 8); if(control & 0x2000) { xxx %= sizeX; yyy %= sizeY; if(xxx < 0) xxx += sizeX; if(yyy < 0) yyy += sizeY; } if(control & 0x80) { for(int x = 0; x < 240; x++) { if(xxx < 0 || yyy < 0 || xxx >= sizeX || yyy >= sizeY) { line[x] = 0x80000000; } else { int tile = screenBase[(xxx>>3) + (yyy>>3)*(sizeX>>3)]; int tileX = (xxx & 7); int tileY = yyy & 7; uint8 color = charBase[(tile<<6) + (tileY<<3) + tileX]; line[x] = color ? (READ16LE(&palette[color])|prio): 0x80000000; } realX += dx; realY += dy; xxx = (realX >> 8); yyy = (realY >> 8); if(control & 0x2000) { xxx %= sizeX; yyy %= sizeY; if(xxx < 0) xxx += sizeX; if(yyy < 0) yyy += sizeY; } } } else { for(int x = 0; x < 240; x++) { if(xxx < 0 || yyy < 0 || xxx >= sizeX || yyy >= sizeY) { line[x] = 0x80000000; } else { int tile = screenBase[(xxx>>3) + (yyy>>3)*(sizeX>>3)]; int tileX = (xxx & 7); int tileY = yyy & 7; uint8 color = charBase[(tile<<6) + (tileY<<3) + tileX]; line[x] = color ? (READ16LE(&palette[color])|prio): 0x80000000; } realX += dx; realY += dy; xxx = (realX >> 8); yyy = (realY >> 8); if(control & 0x2000) { xxx %= sizeX; yyy %= sizeY; if(xxx < 0) xxx += sizeX; if(yyy < 0) yyy += sizeY; } } } if(control & 0x40) { int mosaicX = (MOSAIC & 0xF) + 1; if(mosaicX > 1) { int m = 1; for(int i = 0; i < 239; i++) { line[i+1] = line[i]; m++; if(m == mosaicX) { m = 1; i++; } } } } } void gfxDrawRotScreen16Bit(uint16 control, uint16 x_l, uint16 x_h, uint16 y_l, uint16 y_h, uint16 pa, uint16 pb, uint16 pc, uint16 pd, int& currentX, int& currentY, int changed, uint32 *line) { uint16 *screenBase = (uint16 *)&vram[0]; int prio = ((control & 3) << 25) + 0x1000000; int sizeX = 240; int sizeY = 160; int startX = (x_l) | ((x_h & 0x07FF)<<16); if(x_h & 0x0800) startX |= 0xF8000000; int startY = (y_l) | ((y_h & 0x07FF)<<16); if(y_h & 0x0800) startY |= 0xF8000000; int dx = pa & 0x7FFF; if(pa & 0x8000) dx |= 0xFFFF8000; int dmx = pb & 0x7FFF; if(pb & 0x8000) dmx |= 0xFFFF8000; int dy = pc & 0x7FFF; if(pc & 0x8000) dy |= 0xFFFF8000; int dmy = pd & 0x7FFF; if(pd & 0x8000) dmy |= 0xFFFF8000; if(VCOUNT == 0) changed = 3; if(changed & 1) { currentX = (x_l) | ((x_h & 0x07FF)<<16); if(x_h & 0x0800) currentX |= 0xF8000000; } else currentX += dmx; if(changed & 2) { currentY = (y_l) | ((y_h & 0x07FF)<<16); if(y_h & 0x0800) currentY |= 0xF8000000; } else { currentY += dmy; } int realX = currentX; int realY = currentY; if(control & 0x40) { int mosaicY = ((MOSAIC & 0xF0)>>4) + 1; int y = (VCOUNT % mosaicY); realX -= y*dmx; realY -= y*dmy; } int xxx = (realX >> 8); int yyy = (realY >> 8); for(int x = 0; x < 240; x++) { if(xxx < 0 || yyy < 0 || xxx >= sizeX || yyy >= sizeY) { line[x] = 0x80000000; } else { line[x] = (READ16LE(&screenBase[yyy * sizeX + xxx]) | prio); } realX += dx; realY += dy; xxx = (realX >> 8); yyy = (realY >> 8); } if(control & 0x40) { int mosaicX = (MOSAIC & 0xF) + 1; if(mosaicX > 1) { int m = 1; for(int i = 0; i < 239; i++) { line[i+1] = line[i]; m++; if(m == mosaicX) { m = 1; i++; } } } } } void gfxDrawRotScreen256(uint16 control, uint16 x_l, uint16 x_h, uint16 y_l, uint16 y_h, uint16 pa, uint16 pb, uint16 pc, uint16 pd, int &currentX, int& currentY, int changed, uint32 *line) { uint16 *palette = (uint16 *)paletteRAM; uint8 *screenBase = (DISPCNT & 0x0010) ? &vram[0xA000] : &vram[0x0000]; int prio = ((control & 3) << 25) + 0x1000000; int sizeX = 240; int sizeY = 160; int startX = (x_l) | ((x_h & 0x07FF)<<16); if(x_h & 0x0800) startX |= 0xF8000000; int startY = (y_l) | ((y_h & 0x07FF)<<16); if(y_h & 0x0800) startY |= 0xF8000000; int dx = pa & 0x7FFF; if(pa & 0x8000) dx |= 0xFFFF8000; int dmx = pb & 0x7FFF; if(pb & 0x8000) dmx |= 0xFFFF8000; int dy = pc & 0x7FFF; if(pc & 0x8000) dy |= 0xFFFF8000; int dmy = pd & 0x7FFF; if(pd & 0x8000) dmy |= 0xFFFF8000; if(VCOUNT == 0) changed = 3; if(changed & 1) { currentX = (x_l) | ((x_h & 0x07FF)<<16); if(x_h & 0x0800) currentX |= 0xF8000000; } else { currentX += dmx; } if(changed & 2) { currentY = (y_l) | ((y_h & 0x07FF)<<16); if(y_h & 0x0800) currentY |= 0xF8000000; } else { currentY += dmy; } int realX = currentX; int realY = currentY; if(control & 0x40) { int mosaicY = ((MOSAIC & 0xF0)>>4) + 1; int y = (VCOUNT / mosaicY) * mosaicY; realX = startX + y*dmx; realY = startY + y*dmy; } int xxx = (realX >> 8); int yyy = (realY >> 8); for(int x = 0; x < 240; x++) { if(xxx < 0 || yyy < 0 || xxx >= sizeX || yyy >= sizeY) { line[x] = 0x80000000; } else { uint8 color = screenBase[yyy * 240 + xxx]; line[x] = color ? (READ16LE(&palette[color])|prio): 0x80000000; } realX += dx; realY += dy; xxx = (realX >> 8); yyy = (realY >> 8); } if(control & 0x40) { int mosaicX = (MOSAIC & 0xF) + 1; if(mosaicX > 1) { int m = 1; for(int i = 0; i < 239; i++) { line[i+1] = line[i]; m++; if(m == mosaicX) { m = 1; i++; } } } } } void gfxDrawRotScreen16Bit160(uint16 control, uint16 x_l, uint16 x_h, uint16 y_l, uint16 y_h, uint16 pa, uint16 pb, uint16 pc, uint16 pd, int& currentX, int& currentY, int changed, uint32 *line) { uint16 *screenBase = (DISPCNT & 0x0010) ? (uint16 *)&vram[0xa000] : (uint16 *)&vram[0]; int prio = ((control & 3) << 25) + 0x1000000; int sizeX = 160; int sizeY = 128; int startX = (x_l) | ((x_h & 0x07FF)<<16); if(x_h & 0x0800) startX |= 0xF8000000; int startY = (y_l) | ((y_h & 0x07FF)<<16); if(y_h & 0x0800) startY |= 0xF8000000; int dx = pa & 0x7FFF; if(pa & 0x8000) dx |= 0xFFFF8000; int dmx = pb & 0x7FFF; if(pb & 0x8000) dmx |= 0xFFFF8000; int dy = pc & 0x7FFF; if(pc & 0x8000) dy |= 0xFFFF8000; int dmy = pd & 0x7FFF; if(pd & 0x8000) dmy |= 0xFFFF8000; if(VCOUNT == 0) changed = 3; if(changed & 1) { currentX = (x_l) | ((x_h & 0x07FF)<<16); if(x_h & 0x0800) currentX |= 0xF8000000; } else { currentX += dmx; } if(changed & 2) { currentY = (y_l) | ((y_h & 0x07FF)<<16); if(y_h & 0x0800) currentY |= 0xF8000000; } else { currentY += dmy; } int realX = currentX; int realY = currentY; if(control & 0x40) { int mosaicY = ((MOSAIC & 0xF0)>>4) + 1; int y = (VCOUNT / mosaicY) * mosaicY; realX = startX + y*dmx; realY = startY + y*dmy; } int xxx = (realX >> 8); int yyy = (realY >> 8); for(int x = 0; x < 240; x++) { if(xxx < 0 || yyy < 0 || xxx >= sizeX || yyy >= sizeY) { line[x] = 0x80000000; } else { line[x] = (READ16LE(&screenBase[yyy * sizeX + xxx]) | prio); } realX += dx; realY += dy; xxx = (realX >> 8); yyy = (realY >> 8); } if(control & 0x40) { int mosaicX = (MOSAIC & 0xF) + 1; if(mosaicX > 1) { int m = 1; for(int i = 0; i < 239; i++) { line[i+1] = line[i]; m++; if(m == mosaicX) { m = 1; i++; } } } } } void gfxDrawSprites(void) { int m=0; gfxClearArray(lineOBJ); if(layerEnable & 0x1000) { uint16 *sprites = (uint16 *)oam; uint16 *spritePalette = &((uint16 *)paletteRAM)[256]; int mosaicY = ((MOSAIC & 0xF000)>>12) + 1; int mosaicX = ((MOSAIC & 0xF00)>>8) + 1; for(int i = 0; i < 128 ; i++) { uint16 a0 = READ16LE(sprites++); uint16 a1 = READ16LE(sprites++); uint16 a2 = READ16LE(sprites++); sprites++; // ignore OBJ-WIN if((a0 & 0x0c00) == 0x0800) continue; int sizeY = 8; int sizeX = 8; switch(((a0 >>12) & 0x0c)|(a1>>14)) { case 0: break; case 1: sizeX = sizeY = 16; break; case 2: sizeX = sizeY = 32; break; case 3: sizeX = sizeY = 64; break; case 4: sizeX = 16; break; case 5: sizeX = 32; break; case 6: sizeX = 32; sizeY = 16; break; case 7: sizeX = 64; sizeY = 32; break; case 8: sizeY = 16; break; case 9: sizeY = 32; break; case 10: sizeX = 16; sizeY = 32; break; case 11: sizeX = 32; sizeY = 64; break; default: continue; } #ifdef SPRITE_DEBUG int maskX = sizeX-1; int maskY = sizeY-1; #endif int sy = (a0 & 255); if(sy > 160) sy -= 256; if(a0 & 0x0100) { int fieldX = sizeX; int fieldY = sizeY; if(a0 & 0x0200) { fieldX <<= 1; fieldY <<= 1; } int t = VCOUNT - sy; if((t >= 0) && (t < fieldY)) { int sx = (a1 & 0x1FF); if((sx < 240) || (((sx + fieldX) & 511) < 240)) { // int t2 = t - (fieldY >> 1); int rot = (a1 >> 9) & 0x1F; uint16 *OAM = (uint16 *)oam; int dx = READ16LE(&OAM[3 + (rot << 4)]); if(dx & 0x8000) dx |= 0xFFFF8000; int dmx = READ16LE(&OAM[7 + (rot << 4)]); if(dmx & 0x8000) dmx |= 0xFFFF8000; int dy = READ16LE(&OAM[11 + (rot << 4)]); if(dy & 0x8000) dy |= 0xFFFF8000; int dmy = READ16LE(&OAM[15 + (rot << 4)]); if(dmy & 0x8000) dmy |= 0xFFFF8000; if(a0 & 0x1000) { t -= (t % mosaicY); } int realX = ((sizeX) << 7) - (fieldX >> 1)*dx - (fieldY>>1)*dmx + t * dmx; int realY = ((sizeY) << 7) - (fieldX >> 1)*dy - (fieldY>>1)*dmy + t * dmy; uint32 prio = (((a2 >> 10) & 3) << 25) | ((a0 & 0x0c00)<<6); if(a0 & 0x2000) { int c = (a2 & 0x3FF); if((DISPCNT & 7) > 2 && (c < 512)) continue; int inc = 32; if(DISPCNT & 0x40) inc = sizeX >> 2; else c &= 0x3FE; for(int x = 0; x < fieldX; x++) { int xxx = realX >> 8; int yyy = realY >> 8; if(xxx < 0 || xxx >= sizeX || yyy < 0 || yyy >= sizeY || sx >= 240); else { uint32 color = vram[0x10000 + ((((c + (yyy>>3) * inc)<<5) + ((yyy & 7)<<3) + ((xxx >> 3)<<6) + (xxx & 7))&0x7FFF)]; if ((color==0) && (((prio >> 25)&3) < ((lineOBJ[sx]>>25)&3))) { lineOBJ[sx] = (lineOBJ[sx] & 0xF9FFFFFF) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } else if((color) && (prio < (lineOBJ[sx]&0xFF000000))) { lineOBJ[sx] = READ16LE(&spritePalette[color]) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } if (a0 & 0x1000) { m++; if (m==mosaicX) m=0; } #ifdef SPRITE_DEBUG if(t == 0 || t == maskY || x == 0 || x == maskX) lineOBJ[sx] = 0x001F; #endif } sx = (sx+1)&511;; realX += dx; realY += dy; } } else { int c = (a2 & 0x3FF); if((DISPCNT & 7) > 2 && (c < 512)) continue; int inc = 32; if(DISPCNT & 0x40) inc = sizeX >> 3; int palette = (a2 >> 8) & 0xF0; for(int x = 0; x < fieldX; x++) { int xxx = realX >> 8; int yyy = realY >> 8; if(xxx < 0 || xxx >= sizeX || yyy < 0 || yyy >= sizeY || sx >= 240); else { uint32 color = vram[0x10000 + ((((c + (yyy>>3) * inc)<<5) + ((yyy & 7)<<2) + ((xxx >> 3)<<5) + ((xxx & 7)>>1))&0x7FFF)]; if(xxx & 1) color >>= 4; else color &= 0x0F; if ((color==0) && (((prio >> 25)&3) < ((lineOBJ[sx]>>25)&3))) { lineOBJ[sx] = (lineOBJ[sx] & 0xF9FFFFFF) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } else if((color) && (prio < (lineOBJ[sx]&0xFF000000))) { lineOBJ[sx] = READ16LE(&spritePalette[palette+color]) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } } if((a0 & 0x1000) && m) { m++; if (m==mosaicX) m=0; } #ifdef SPRITE_DEBUG if(t == 0 || t == maskY || x == 0 || x == maskX) lineOBJ[sx] = 0x001F; #endif sx = (sx+1)&511;; realX += dx; realY += dy; } } } } } else { int t = VCOUNT - sy; if((t >= 0) && (t < sizeY)) { int sx = (a1 & 0x1FF); if(((sx < 240)||(((sx+sizeX)&511)<240)) && !(a0 & 0x0200)) { if(a0 & 0x2000) { if(a1 & 0x2000) t = sizeY - t - 1; int c = (a2 & 0x3FF); if((DISPCNT & 7) > 2 && (c < 512)) continue; int inc = 32; if(DISPCNT & 0x40) { inc = sizeX >> 2; } else { c &= 0x3FE; } int xxx = 0; if(a1 & 0x1000) xxx = sizeX-1; if(a0 & 0x1000) { t -= (t % mosaicY); } int address = 0x10000 + ((((c+ (t>>3) * inc) << 5) + ((t & 7) << 3) + ((xxx>>3)<<6) + (xxx & 7)) & 0x7FFF); if(a1 & 0x1000) xxx = 7; uint32 prio = (((a2 >> 10) & 3) << 25) | ((a0 & 0x0c00)<<6); for(int xx = 0; xx < sizeX; xx++) { if(sx < 240) { uint8 color = vram[address]; if ((color==0) && (((prio >> 25)&3) < ((lineOBJ[sx]>>25)&3))) { lineOBJ[sx] = (lineOBJ[sx] & 0xF9FFFFFF) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } else if((color) && (prio < (lineOBJ[sx]&0xFF000000))) { lineOBJ[sx] = READ16LE(&spritePalette[color]) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } if (a0 & 0x1000) { m++; if (m==mosaicX) m=0; } #ifdef SPRITE_DEBUG if(t == 0 || t == maskY || xx == 0 || xx == maskX) lineOBJ[sx] = 0x001F; #endif } sx = (sx+1) & 511; if(a1 & 0x1000) { xxx--; address--; if(xxx == -1) { address -= 56; xxx = 7; } if(address < 0x10000) address += 0x8000; } else { xxx++; address++; if(xxx == 8) { address += 56; xxx = 0; } if(address > 0x17fff) address -= 0x8000; } } } else { if(a1 & 0x2000) t = sizeY - t - 1; int c = (a2 & 0x3FF); if((DISPCNT & 7) > 2 && (c < 512)) continue; int inc = 32; if(DISPCNT & 0x40) { inc = sizeX >> 3; } int xxx = 0; if(a1 & 0x1000) xxx = sizeX - 1; if(a0 & 0x1000) { t -= (t % mosaicY); } int address = 0x10000 + ((((c + (t>>3) * inc)<<5) + ((t & 7)<<2) + ((xxx>>3)<<5) + ((xxx & 7) >> 1))&0x7FFF); uint32 prio = (((a2 >> 10) & 3) << 25) | ((a0 & 0x0c00)<<6); int palette = (a2 >> 8) & 0xF0; if(a1 & 0x1000) { xxx = 7; for(int xx = sizeX - 1; xx >= 0; xx--) { if(sx < 240) { uint8 color = vram[address]; if(xx & 1) { color = (color >> 4); } else color &= 0x0F; if ((color==0) && (((prio >> 25)&3) < ((lineOBJ[sx]>>25)&3))) { lineOBJ[sx] = (lineOBJ[sx] & 0xF9FFFFFF) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } else if((color) && (prio < (lineOBJ[sx]&0xFF000000))) { lineOBJ[sx] = READ16LE(&spritePalette[palette + color]) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } } if (a0 & 0x1000) { m++; if (m==mosaicX) m=0; } #ifdef SPRITE_DEBUG if(t == 0 || t == maskY || xx == 0 || xx == maskX) lineOBJ[sx] = 0x001F; #endif sx = (sx+1) & 511; xxx--; if(!(xx & 1)) address--; if(xxx == -1) { xxx = 7; address -= 28; } if(address < 0x10000) address += 0x8000; } } else { for(int xx = 0; xx < sizeX; xx++) { if(sx < 240) { uint8 color = vram[address]; if(xx & 1) { color = (color >> 4); } else color &= 0x0F; if ((color==0) && (((prio >> 25)&3) < ((lineOBJ[sx]>>25)&3))) { lineOBJ[sx] = (lineOBJ[sx] & 0xF9FFFFFF) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } else if((color) && (prio < (lineOBJ[sx]&0xFF000000))) { lineOBJ[sx] = READ16LE(&spritePalette[palette + color]) | prio; if((a0 & 0x1000) && m) lineOBJ[sx]=(lineOBJ[sx-1] & 0xF9FFFFFF) | prio; } } if (a0 & 0x1000) { m++; if (m==mosaicX) m=0; } #ifdef SPRITE_DEBUG if(t == 0 || t == maskY || xx == 0 || xx == maskX) lineOBJ[sx] = 0x001F; #endif sx = (sx+1) & 511; xxx++; if(xx & 1) address++; if(xxx == 8) { address += 28; xxx = 0; } if(address > 0x17fff) address -= 0x8000; } } } } } } } } } void gfxDrawOBJWin(void) { gfxClearArray(lineOBJWin); if(layerEnable & 0x8000) { uint16 *sprites = (uint16 *)oam; // uint16 *spritePalette = &((uint16 *)paletteRAM)[256]; for(int i = 0; i < 128 ; i++) { uint16 a0 = READ16LE(sprites++); uint16 a1 = READ16LE(sprites++); uint16 a2 = READ16LE(sprites++); sprites++; // ignore non OBJ-WIN if((a0 & 0x0c00) != 0x0800) continue; int sizeY = 8; int sizeX = 8; switch(((a0 >>12) & 0x0c)|(a1>>14)) { case 0: break; case 1: sizeX = sizeY = 16; break; case 2: sizeX = sizeY = 32; break; case 3: sizeX = sizeY = 64; break; case 4: sizeX = 16; break; case 5: sizeX = 32; break; case 6: sizeX = 32; sizeY = 16; break; case 7: sizeX = 64; sizeY = 32; break; case 8: sizeY = 16; break; case 9: sizeY = 32; break; case 10: sizeX = 16; sizeY = 32; break; case 11: sizeX = 32; sizeY = 64; break; default: continue; } int sy = (a0 & 255); if(sy > 160) sy -= 256; if(a0 & 0x0100) { int fieldX = sizeX; int fieldY = sizeY; if(a0 & 0x0200) { fieldX <<= 1; fieldY <<= 1; } int t = VCOUNT - sy; if((t >= 0) && (t < fieldY)) { int sx = (a1 & 0x1FF); if((sx < 240) || (((sx + fieldX) & 511) < 240)) { // int t2 = t - (fieldY >> 1); int rot = (a1 >> 9) & 0x1F; uint16 *OAM = (uint16 *)oam; int dx = READ16LE(&OAM[3 + (rot << 4)]); if(dx & 0x8000) dx |= 0xFFFF8000; int dmx = READ16LE(&OAM[7 + (rot << 4)]); if(dmx & 0x8000) dmx |= 0xFFFF8000; int dy = READ16LE(&OAM[11 + (rot << 4)]); if(dy & 0x8000) dy |= 0xFFFF8000; int dmy = READ16LE(&OAM[15 + (rot << 4)]); if(dmy & 0x8000) dmy |= 0xFFFF8000; int realX = ((sizeX) << 7) - (fieldX >> 1)*dx - (fieldY>>1)*dmx + t * dmx; int realY = ((sizeY) << 7) - (fieldX >> 1)*dy - (fieldY>>1)*dmy + t * dmy; // uint32 prio = (((a2 >> 10) & 3) << 25) | ((a0 & 0x0c00)<<6); if(a0 & 0x2000) { int c = (a2 & 0x3FF); if((DISPCNT & 7) > 2 && (c < 512)) continue; int inc = 32; if(DISPCNT & 0x40) inc = sizeX >> 2; else c &= 0x3FE; for(int x = 0; x < fieldX; x++) { int xxx = realX >> 8; int yyy = realY >> 8; if(xxx < 0 || xxx >= sizeX || yyy < 0 || yyy >= sizeY || sx >= 240) { } else { uint32 color = vram[0x10000 + ((((c + (yyy>>3) * inc)<<5) + ((yyy & 7)<<3) + ((xxx >> 3)<<6) + (xxx & 7))&0x7fff)]; if(color) { lineOBJWin[sx] = 1; } } sx = (sx+1)&511;; realX += dx; realY += dy; } } else { int c = (a2 & 0x3FF); if((DISPCNT & 7) > 2 && (c < 512)) continue; int inc = 32; if(DISPCNT & 0x40) inc = sizeX >> 3; // int palette = (a2 >> 8) & 0xF0; for(int x = 0; x < fieldX; x++) { int xxx = realX >> 8; int yyy = realY >> 8; // if(x == 0 || x == (sizeX-1) || // t == 0 || t == (sizeY-1)) { // lineOBJ[sx] = 0x001F | prio; // } else { if(xxx < 0 || xxx >= sizeX || yyy < 0 || yyy >= sizeY || sx >= 240){ } else { uint32 color = vram[0x10000 + ((((c + (yyy>>3) * inc)<<5) + ((yyy & 7)<<2) + ((xxx >> 3)<<5) + ((xxx & 7)>>1))&0x7fff)]; if(xxx & 1) color >>= 4; else color &= 0x0F; if(color) { lineOBJWin[sx] = 1; } } // } sx = (sx+1)&511;; realX += dx; realY += dy; } } } } } else { int t = VCOUNT - sy; if((t >= 0) && (t < sizeY)) { int sx = (a1 & 0x1FF); if(((sx < 240)||(((sx+sizeX)&511)<240)) && !(a0 & 0x0200)) { if(a0 & 0x2000) { if(a1 & 0x2000) t = sizeY - t - 1; int c = (a2 & 0x3FF); if((DISPCNT & 7) > 2 && (c < 512)) continue; int inc = 32; if(DISPCNT & 0x40) { inc = sizeX >> 2; } else { c &= 0x3FE; } int xxx = 0; if(a1 & 0x1000) xxx = sizeX-1; int address = 0x10000 + ((((c+ (t>>3) * inc) << 5) + ((t & 7) << 3) + ((xxx>>3)<<6) + (xxx & 7))&0x7fff); if(a1 & 0x1000) xxx = 7; // uint32 prio = (((a2 >> 10) & 3) << 25) | ((a0 & 0x0c00)<<6); for(int xx = 0; xx < sizeX; xx++) { if(sx < 240) { uint8 color = vram[address]; if(color) { lineOBJWin[sx] = 1; } } sx = (sx+1) & 511; if(a1 & 0x1000) { xxx--; address--; if(xxx == -1) { address -= 56; xxx = 7; } if(address < 0x10000) address += 0x8000; } else { xxx++; address++; if(xxx == 8) { address += 56; xxx = 0; } if(address > 0x17fff) address -= 0x8000; } } } else { if(a1 & 0x2000) t = sizeY - t - 1; int c = (a2 & 0x3FF); if((DISPCNT & 7) > 2 && (c < 512)) continue; int inc = 32; if(DISPCNT & 0x40) { inc = sizeX >> 3; } int xxx = 0; if(a1 & 0x1000) xxx = sizeX - 1; int address = 0x10000 + ((((c + (t>>3) * inc)<<5) + ((t & 7)<<2) + ((xxx>>3)<<5) + ((xxx & 7) >> 1))&0x7fff); // uint32 prio = (((a2 >> 10) & 3) << 25) | ((a0 & 0x0c00)<<6); // int palette = (a2 >> 8) & 0xF0; if(a1 & 0x1000) { xxx = 7; for(int xx = sizeX - 1; xx >= 0; xx--) { if(sx < 240) { uint8 color = vram[address]; if(xx & 1) { color = (color >> 4); } else color &= 0x0F; if(color) { lineOBJWin[sx] = 1; } } sx = (sx+1) & 511; xxx--; if(!(xx & 1)) address--; if(xxx == -1) { xxx = 7; address -= 28; } if(address < 0x10000) address += 0x8000; } } else { for(int xx = 0; xx < sizeX; xx++) { if(sx < 240) { uint8 color = vram[address]; if(xx & 1) { color = (color >> 4); } else color &= 0x0F; if(color) { lineOBJWin[sx] = 1; } } sx = (sx+1) & 511; xxx++; if(xx & 1) address++; if(xxx == 8) { address += 28; xxx = 0; } if(address > 0x17fff) address -= 0x8000; } } } } } } } } } }
/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "mvdQtWidgetView.h" /*****************************************************************************/ /* INCLUDE SECTION */ // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) #include <functional> // // ITK includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) #include "otbWrapperApplicationHtmlDocGenerator.h" // #include "otbWrapperComplexOutputImageParameter.h" #include "otbWrapperOutputFilenameParameter.h" // #include "otbWrapperOutputImageParameter.h" #include "otbWrapperOutputVectorDataParameter.h" // #include "otbWrapperQtWidgetOutputImageParameter.h" // #include "otbWrapperQtWidgetProgressReport.h" #include "otbWrapperQtWidgetSimpleProgressReport.h" // #include "otbWrapperTypes.h" // // Monteverdi includes (sorted by alphabetic order) #include "mvdAbstractLayerModel.h" #include "mvdFilenameInterface.h" #include "mvdI18nCoreApplication.h" #include "mvdStackedLayerModel.h" #include "mvdQtWidgetParameterInitializers.h" namespace mvd { namespace Wrapper { /* TRANSLATOR mvd::Wrapper::QtWidgetView Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*****************************************************************************/ /* INTERNAL TYPES */ class KeyLayerAccumulator : public std::unary_function< StackedLayerModel::ConstIterator::value_type, void > { public: typedef std::unary_function< StackedLayerModel::ConstIterator::value_type, void > SuperType; typedef std::list< SuperType::argument_type > KeyLayerPairList; KeyLayerAccumulator( const std::string & filename, KeyLayerPairList & klp ) : m_KeyLayerPairs( klp ), m_Filename( FromStdString( filename ) ), m_Count( 0 ) { } void operator () ( const SuperType::argument_type & pair ) { const FilenameInterface * interface = dynamic_cast< const FilenameInterface * >( pair.second ); if( interface!=NULL && m_Filename.compare( interface->GetFilename() )==0 ) { qDebug() << m_Filename << "==" << interface->GetFilename(); m_KeyLayerPairs.push_back( pair ); ++ m_Count; } } std::size_t GetCount() const { return m_Count; } public: KeyLayerPairList & m_KeyLayerPairs; private: QString m_Filename; std::size_t m_Count; }; /*****************************************************************************/ /* CONSTANTS */ char const * const QtWidgetView ::OBJECT_NAME = "mvd::Wrapper::QtWidgetView"; /*****************************************************************************/ /* STATIC IMPLEMENTATION SECTION */ /*****************************************************************************/ /* CLASS IMPLEMENTATION SECTION */ /*****************************************************************************/ QtWidgetView ::QtWidgetView( const otb::Wrapper::Application::Pointer & otbApp, QWidget* p, Qt::WindowFlags flags ) : QWidget( p, flags ), m_Application( otbApp ), m_Model( NULL ), m_ExecButton( NULL ), m_QuitButton( NULL ), m_Message( NULL ), m_IsClosable( true ) { setObjectName( QtWidgetView::OBJECT_NAME ); m_Model = new otb::Wrapper::QtWidgetModel( otbApp ); m_QuitShortcut = new QShortcut(QKeySequence("Ctrl+Q"), this); QObject::connect( m_Model, SIGNAL( SetProgressReportBegin() ), this, SLOT( OnProgressReportBegin() ) ); QObject::connect( m_Model, SIGNAL( SetProgressReportDone( int ) ), this, SLOT( OnProgressReportEnd( int ) ) ); QObject::connect( m_Model, SIGNAL( ExceptionRaised( QString ) ), this, SLOT( OnExceptionRaised( QString ) ) ); } /*******************************************************************************/ QtWidgetView ::~QtWidgetView() { // m_Application is smart-pointed and will be automatically deleted. delete m_Model; m_Model = NULL; } /*******************************************************************************/ void QtWidgetView ::CreateGui() { // Create a VBoxLayout with the header, the input widgets, and the footer QVBoxLayout *mainLayout = new QVBoxLayout(); QTabWidget *tab = new QTabWidget(); tab->addTab(CreateInputWidgets(), "Parameters"); //otb::Wrapper::QtWidgetProgressReport* prog = new otb::Wrapper::QtWidgetProgressReport(m_Model); //prog->SetApplication(m_Application); //tab->addTab(prog, "Progress"); tab->addTab(CreateDoc(), "Documentation"); mainLayout->addWidget(tab); QTextEdit *log = new QTextEdit(); connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) ); tab->addTab(log, "Logs"); m_Message = new QLabel("<center><font color=\"#FF0000\">Select parameters</font></center>"); connect( m_Model, SIGNAL( SetApplicationReady( bool ) ), this, SLOT( UpdateMessageAfterApplicationReady( bool ) ) ); mainLayout->addWidget(m_Message); otb::Wrapper::QtWidgetSimpleProgressReport* progressReport = new otb::Wrapper::QtWidgetSimpleProgressReport(m_Model); progressReport->SetApplication(m_Application); QHBoxLayout *footLayout = new QHBoxLayout; footLayout->addWidget(progressReport); footLayout->addWidget(CreateFooter()); mainLayout->addLayout(footLayout); QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(mainLayout); QVBoxLayout *finalLayout = new QVBoxLayout(); finalLayout->addWidget(mainGroup); // Make the final layout to the widget this->setLayout(finalLayout); } /*******************************************************************************/ QWidget* QtWidgetView ::CreateInputWidgets() { QScrollArea *scrollArea = new QScrollArea; QWidget * widget = otb::Wrapper::QtWidgetParameterFactory::CreateQtWidget( m_Model->GetApplication()->GetParameterList(), m_Model ); scrollArea->setWidget( widget ); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setWidgetResizable(true); // // need to be connected to the end of a process QObject::connect( m_Model, SIGNAL( SetProgressReportDone( int ) ), // to: this, SLOT ( OnApplicationExecutionDone( int ) ) ); SetupParameterWidgets( widget ); return scrollArea; } /*******************************************************************************/ QWidget* QtWidgetView ::CreateFooter() { // an HLayout with two buttons : Execute and Quit QGroupBox *footerGroup = new QGroupBox; QHBoxLayout *footerLayout = new QHBoxLayout; footerGroup->setFixedHeight(40); footerGroup->setContentsMargins(0, 0, 0, 0); footerLayout->setContentsMargins(5, 5, 5, 5); m_ExecButton = new QPushButton(footerGroup); m_ExecButton->setDefault(true); m_ExecButton->setEnabled(false); m_ExecButton->setText(QObject::tr("Execute")); connect( m_Model, SIGNAL( SetApplicationReady( bool ) ), m_ExecButton, SLOT( setEnabled( bool ) ) ); QObject::connect( m_ExecButton, SIGNAL( clicked() ), // to: this, SLOT( OnExecButtonClicked() ) ); QObject::connect( this, SIGNAL( ExecuteAndWriteOutput() ), // to: m_Model, SLOT( ExecuteAndWriteOutputSlot() ) ); m_QuitButton = new QPushButton(footerGroup); m_QuitButton->setText(QObject::tr("Quit")); connect( m_QuitButton, SIGNAL( clicked() ), // to: this, SLOT( close() ) ); // Add Ctrl-Q shortcut to quit connect( m_QuitShortcut, SIGNAL(activated()), this, SLOT(close()) ); // Put the buttons on the right footerLayout->addStretch(); footerLayout->addWidget(m_ExecButton); footerLayout->addWidget(m_QuitButton); footerGroup->setLayout(footerLayout); return footerGroup; } /*******************************************************************************/ QWidget* QtWidgetView ::CreateDoc() { QTextEdit *text = new QTextEdit; text->setReadOnly(true); QTextDocument * doc = new QTextDocument(); std::string docContain; otb::Wrapper::ApplicationHtmlDocGenerator::GenerateDoc( m_Application, docContain); doc->setHtml(docContain.c_str()); text->setDocument(doc); return text; } /*******************************************************************************/ void QtWidgetView ::SetupParameterWidgets( QWidget * widget ) { assert( widget!=NULL ); SetupWidget( widget, InputFilenameInitializer() ); SetupWidget( widget, InputFilenameListInitializer( this ) ); SetupWidget( widget, InputImageInitializer() ); SetupWidget( widget, InputImageListInitializer( this ) ); SetupWidget( widget, ComplexInputImageInitializer() ); SetupWidget( widget, InputProcessXMLInitializer() ); SetupWidget( widget, InputVectorDataInitializer() ); SetupWidget( widget, InputVectorDataListInitializer( this ) ); #if defined( OTB_DEBUG ) SetupWidget( widget, ToolTipInitializer() ); #endif SetupWidget( widget, OutputFilenameInitializer() ); SetupWidget( widget, OutputProcessXMLInitializer() ); SetupWidget( widget, OutputImageInitializer( m_Application->GetName() ) ); SetupWidget( widget, ComplexOutputImageInitializer( m_Application->GetName() ) ); SetupWidget( widget, OutputVectorDataInitializer() ); } /*******************************************************************************/ void QtWidgetView ::SetupFileSelectionWidget( QWidget * widget ) { assert( widget!=NULL ); assert( qobject_cast< FileSelectionInitializer::argument_type >( widget )!=NULL ); FileSelectionInitializer initialize; initialize( qobject_cast< FileSelectionInitializer::argument_type >( widget ) ); } /*******************************************************************************/ void QtWidgetView ::closeEvent( QCloseEvent * e ) { assert( e!=NULL ); if( !IsClosable() ) { assert( !m_Application.IsNull() ); QMessageBox::warning( this, tr( "Warning!" ), tr( "OTB-Application '%1' cannot be closed while running!") .arg( m_Application->GetDocName() ) ); e->ignore(); return; } QWidget::closeEvent( e ); emit QuitSignal(); deleteLater(); } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ void QtWidgetView ::OnExecButtonClicked() { assert( m_Model!=NULL ); assert( m_Model->GetApplication()!=NULL ); assert( I18nCoreApplication::Instance()!=NULL ); // // Get layer-stack, if any. StackedLayerModel * layerStack = I18nCoreApplication::Instance()->GetModel< StackedLayerModel >(); otb::Wrapper::Application::Pointer otbApp( m_Model->GetApplication() ); // // Check output parameters of OTB-application. StringVector paramKeys( otbApp->GetParametersKeys() ); QStringList filenames1; KeyLayerAccumulator::KeyLayerPairList layers; QStringList filenames2; for( StringVector::const_iterator it( paramKeys.begin() ); it!=paramKeys.end(); ++it ) { if( otbApp->IsParameterEnabled( *it, true ) && otbApp->HasValue( *it ) ) { otb::Wrapper::Parameter::Pointer param( otbApp->GetParameterByKey( *it ) ); assert( !param.IsNull() ); // qDebug() // << it->c_str() << ": type" << otbApp->GetParameterType( *it ); // const char* filename = NULL; std::string filename; switch( otbApp->GetParameterType( *it ) ) { case otb::Wrapper::ParameterType_OutputFilename: filename = otb::DynamicCast< otb::Wrapper::OutputFilenameParameter >( param ) ->GetValue(); break; // // FILENAME. // // IMAGE. case otb::Wrapper::ParameterType_OutputImage: filename = otb::DynamicCast< otb::Wrapper::OutputImageParameter >( param ) ->GetFileName(); break; // // VECTOR-DATA. case otb::Wrapper::ParameterType_OutputVectorData: filename = otb::DynamicCast< otb::Wrapper::OutputVectorDataParameter >( param ) ->GetFileName(); break; // // COMPLEX IMAGE. case otb::Wrapper::ParameterType_ComplexOutputImage: filename = otb::DynamicCast< otb::Wrapper::ComplexOutputImageParameter >( param ) ->GetFileName(); break; // // NONE. default: break; } if( QFileInfo( filename.c_str() ).exists() ) filenames1.push_back( filename.c_str() ); if( layerStack!=NULL ) { KeyLayerAccumulator accumulator( std::for_each( layerStack->Begin(), layerStack->End(), KeyLayerAccumulator( filename, layers ) ) ); if( accumulator.GetCount()>0 ) filenames2.push_back( filename.c_str() ); } } } { QString message; if( filenames1.size()==1 ) { // qDebug() // << it->c_str() << ":" << QString( filename.c_str() ); message = tr( "Are you sure you want to overwrite file '%1'?" ) .arg( filenames1.front() ); } else if( filenames1.size()>1 ) { message = tr( "Following files will be overwritten. Are you sure you want to continue?\n- %1" ) .arg( filenames1.join( "\n- " ) ); } if( !message.isEmpty() ) { QMessageBox::StandardButton button = QMessageBox::question( this, PROJECT_NAME, message, QMessageBox::Yes | QMessageBox::No, QMessageBox::No ); if( button==QMessageBox::No ) return; } } { QString message; if( filenames2.size()==1 ) { // qDebug() // << it->c_str() << ":" << QString( filename.c_str() ); message = tr( "File '%1' is being viewed in " PROJECT_NAME " and will be concurrently overwritten by running this %2. File will be removed from layer-stack before running %2 and reloaded after.\n\nDo you want to continue?" ) .arg( filenames2.front() ) .arg( otbApp->GetDocName() ); } else if( filenames2.size()>1 ) { message = tr( "Following files are being viewed in " PROJECT_NAME " and will be concurrently overwritter by running %2. Files will be removed from layer-stack before running %2. Do you want to continue?\n- %1" ) .arg( filenames2.join( "\n- " ) ) .arg( otbApp->GetDocName() ); } if( !message.isEmpty() ) { QMessageBox::StandardButton button = QMessageBox::question( this, PROJECT_NAME, message, QMessageBox::Yes | QMessageBox::No, QMessageBox::No ); if( button==QMessageBox::No ) return; while( !layers.empty() ) { layerStack->Delete( layers.front().first ); layers.pop_front(); } } } /* U N S A F E // BUGFIX: Mantis-750 // // Remove files which will be overwritten in order to use // file-existence to check whether to emit the OutputImageChanged // signal (see ::OnApplicationExecutionDone()). for( FileInfoVector::const_iterator it( fileInfos.begin() ); it!=fileInfos.end(); ++it ) { qDebug() << "Removing:" << it->filePath(); it->dir().remove( it->fileName() ); } */ m_Message->setText("<center><font color=\"#FF0000\">Running</font></center>"); emit ExecuteAndWriteOutput(); } /*******************************************************************************/ void QtWidgetView ::UpdateMessageAfterApplicationReady( bool val ) { if(val == true) m_Message->setText("<center><font color=\"#00FF00\">Ready to run</font></center>"); else m_Message->setText("<center><font color=\"#FF0000\">Select parameters</font></center>"); } /*******************************************************************************/ void QtWidgetView ::OnExceptionRaised( QString what ) { qWarning() << what; #if defined( OTB_DEBUG ) QMessageBox::warning( this, PROJECT_NAME, what, QMessageBox::Ok ); #endif } /*******************************************************************************/ void QtWidgetView ::OnApplicationExecutionDone( int status ) { otb::Wrapper::Application::Pointer otbApp( m_Model->GetApplication() ); if( status!=0 ) { QMessageBox::information( this, PROJECT_NAME, tr( "'%1' has failed with return status %2.\n" "Please refer to '%1' documentation and check log tab." ) .arg( otbApp->GetName() ) .arg( status ), QMessageBox::Ok ); emit ExecutionDone( status ); return; } /* // Removed as per MVDX-259. QMessageBox::information( this, PROJECT_NAME, tr( "'%1' has succeeded.\n" "Result(s) will be imported as dataset(s).\n") .arg( otbApp->GetName() ), QMessageBox::Ok ); */ CountType count = 0; // // detect if this application has outputImageParameter. emit // the output filenames if any StringVector paramList( otbApp->GetParametersKeys( true ) ); // iterate on the application parameters for ( StringVector::const_iterator it( paramList.begin() ); it!=paramList.end(); ++it ) { // parameter key const std::string& key = *it; // get a valid outputParameter if( otbApp->GetParameterType( key ) ==otb::Wrapper::ParameterType_OutputImage && otbApp->IsParameterEnabled( key, true ) && otbApp->HasValue( key ) ) { // get the parameter otb::Wrapper::Parameter* param = otbApp->GetParameterByKey( key ); // try to cast it otb::Wrapper::OutputImageParameter* outputParam = dynamic_cast< otb::Wrapper::OutputImageParameter* >( param ); // emit the output image filename selected if( outputParam!=NULL ) { QFileInfo fileInfo( outputParam->GetFileName() ); /* U N S A F E // BUGFIX: Mantis-750 // // If output image-exists, it's sure that it has been output // from the OTB-application process because overwritten // files are first deleted (see OnExecButtonClicked()). if( fileInfo.exists() ) { */ ++ count; emit OTBApplicationOutputImageChanged( QString( otbApp->GetName() ), QFile::decodeName( outputParam->GetFileName() ) ); /* } */ } } } emit ExecutionDone( status ); } } }
// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha256.h" #include "crypto/sha512.h" #include "crypto/hmac_sha256.h" #include "crypto/hmac_sha512.h" #include "random.h" #include "utilstrencodings.h" #include "test/test_dinero.h" #include <vector> #include <boost/assign/list_of.hpp> #include <boost/test/unit_test.hpp> #include <openssl/evp.h> BOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicTestingSetup) template<typename Hasher, typename In, typename Out> void TestVector(const Hasher &h, const In &in, const Out &out) { Out hash; BOOST_CHECK(out.size() == h.OUTPUT_SIZE); hash.resize(out.size()); { // Test that writing the whole input string at once works. Hasher(h).Write((unsigned char*)&in[0], in.size()).Finalize(&hash[0]); BOOST_CHECK(hash == out); } for (int i=0; i<32; i++) { // Test that writing the string broken up in random pieces works. Hasher hasher(h); size_t pos = 0; while (pos < in.size()) { size_t len = insecure_rand() % ((in.size() - pos + 1) / 2 + 1); hasher.Write((unsigned char*)&in[pos], len); pos += len; if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) { // Test that writing the rest at once to a copy of a hasher works. Hasher(hasher).Write((unsigned char*)&in[pos], in.size() - pos).Finalize(&hash[0]); BOOST_CHECK(hash == out); } } hasher.Finalize(&hash[0]); BOOST_CHECK(hash == out); } } void TestSHA1(const std::string &in, const std::string &hexout) { TestVector(CSHA1(), in, ParseHex(hexout));} void TestSHA256(const std::string &in, const std::string &hexout) { TestVector(CSHA256(), in, ParseHex(hexout));} void TestSHA512(const std::string &in, const std::string &hexout) { TestVector(CSHA512(), in, ParseHex(hexout));} void TestRIPEMD160(const std::string &in, const std::string &hexout) { TestVector(CRIPEMD160(), in, ParseHex(hexout));} void TestHMACSHA256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); TestVector(CHMAC_SHA256(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout)); } void TestHMACSHA512(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); TestVector(CHMAC_SHA512(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout)); } std::string LongTestString(void) { std::string ret; for (int i=0; i<200000; i++) { ret += (unsigned char)(i); ret += (unsigned char)(i >> 4); ret += (unsigned char)(i >> 8); ret += (unsigned char)(i >> 12); ret += (unsigned char)(i >> 16); } return ret; } const std::string test1 = LongTestString(); BOOST_AUTO_TEST_CASE(ripemd160_testvectors) { TestRIPEMD160("", "9c1185a5c5e9fc54612808977ee8f548b2258d31"); TestRIPEMD160("abc", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"); TestRIPEMD160("message digest", "5d0689ef49d2fae572b881b123a85ffa21595f36"); TestRIPEMD160("secure hash algorithm", "20397528223b6a5f4cbc2808aba0464e645544f9"); TestRIPEMD160("RIPEMD160 is considered to be safe", "a7d78608c7af8a8e728778e81576870734122b66"); TestRIPEMD160("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "12a053384a9c0c88e405a06c27dcf49ada62eb2b"); TestRIPEMD160("For this sample, this 63-byte string will be used as input data", "de90dbfee14b63fb5abf27c2ad4a82aaa5f27a11"); TestRIPEMD160("This is exactly 64 bytes long, not counting the terminating byte", "eda31d51d3a623b81e19eb02e24ff65d27d67b37"); TestRIPEMD160(std::string(1000000, 'a'), "52783243c1697bdbe16d37f97f68f08325dc1528"); TestRIPEMD160(test1, "464243587bd146ea835cdf57bdae582f25ec45f1"); } BOOST_AUTO_TEST_CASE(sha1_testvectors) { TestSHA1("", "da39a3ee5e6b4b0d3255bfef95601890afd80709"); TestSHA1("abc", "a9993e364706816aba3e25717850c26c9cd0d89d"); TestSHA1("message digest", "c12252ceda8be8994d5fa0290a47231c1d16aae3"); TestSHA1("secure hash algorithm", "d4d6d2f0ebe317513bbd8d967d89bac5819c2f60"); TestSHA1("SHA1 is considered to be safe", "f2b6650569ad3a8720348dd6ea6c497dee3a842a"); TestSHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); TestSHA1("For this sample, this 63-byte string will be used as input data", "4f0ea5cd0585a23d028abdc1a6684e5a8094dc49"); TestSHA1("This is exactly 64 bytes long, not counting the terminating byte", "fb679f23e7d1ce053313e66e127ab1b444397057"); TestSHA1(std::string(1000000, 'a'), "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); TestSHA1(test1, "b7755760681cbfd971451668f32af5774f4656b5"); } BOOST_AUTO_TEST_CASE(sha256_testvectors) { TestSHA256("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); TestSHA256("abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); TestSHA256("message digest", "f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650"); TestSHA256("secure hash algorithm", "f30ceb2bb2829e79e4ca9753d35a8ecc00262d164cc077080295381cbd643f0d"); TestSHA256("SHA256 is considered to be safe", "6819d915c73f4d1e77e4e1b52d1fa0f9cf9beaead3939f15874bd988e2a23630"); TestSHA256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); TestSHA256("For this sample, this 63-byte string will be used as input data", "f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342"); TestSHA256("This is exactly 64 bytes long, not counting the terminating byte", "ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8"); TestSHA256("As Bitcoin relies on 80 byte header hashes, we want to have an example for that.", "7406e8de7d6e4fffc573daef05aefb8806e7790f55eab5576f31349743cca743"); TestSHA256(std::string(1000000, 'a'), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); TestSHA256(test1, "a316d55510b49662420f49d145d42fb83f31ef8dc016aa4e32df049991a91e26"); } BOOST_AUTO_TEST_CASE(sha512_testvectors) { TestSHA512("", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"); TestSHA512("abc", "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"); TestSHA512("message digest", "107dbf389d9e9f71a3a95f6c055b9251bc5268c2be16d6c13492ea45b0199f33" "09e16455ab1e96118e8a905d5597b72038ddb372a89826046de66687bb420e7c"); TestSHA512("secure hash algorithm", "7746d91f3de30c68cec0dd693120a7e8b04d8073cb699bdce1a3f64127bca7a3" "d5db502e814bb63c063a7a5043b2df87c61133395f4ad1edca7fcf4b30c3236e"); TestSHA512("SHA512 is considered to be safe", "099e6468d889e1c79092a89ae925a9499b5408e01b66cb5b0a3bd0dfa51a9964" "6b4a3901caab1318189f74cd8cf2e941829012f2449df52067d3dd5b978456c2"); TestSHA512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335" "96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445"); TestSHA512("For this sample, this 63-byte string will be used as input data", "b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e" "6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766"); TestSHA512("This is exactly 64 bytes long, not counting the terminating byte", "70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38" "7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030"); TestSHA512("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno" "ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"); TestSHA512(std::string(1000000, 'a'), "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"); TestSHA512(test1, "40cac46c147e6131c5193dd5f34e9d8bb4951395f27b08c558c65ff4ba2de594" "37de8c3ef5459d76a52cedc02dc499a3c9ed9dedbfb3281afd9653b8a112fafc"); } BOOST_AUTO_TEST_CASE(hmac_sha256_testvectors) { // test cases 1, 2, 3, 4, 6 and 7 of RFC 4231 TestHMACSHA256("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4869205468657265", "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"); TestHMACSHA256("4a656665", "7768617420646f2079612077616e7420666f72206e6f7468696e673f", "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" "dddddddddddddddddddddddddddddddddddd", "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"); TestHMACSHA256("0102030405060708090a0b0c0d0e0f10111213141516171819", "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a" "65204b6579202d2048617368204b6579204669727374", "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "5468697320697320612074657374207573696e672061206c6172676572207468" "616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074" "68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565" "647320746f20626520686173686564206265666f7265206265696e6720757365" "642062792074686520484d414320616c676f726974686d2e", "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"); } BOOST_AUTO_TEST_CASE(hmac_sha512_testvectors) { // test cases 1, 2, 3, 4, 6 and 7 of RFC 4231 TestHMACSHA512("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4869205468657265", "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde" "daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"); TestHMACSHA512("4a656665", "7768617420646f2079612077616e7420666f72206e6f7468696e673f", "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554" "9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" "dddddddddddddddddddddddddddddddddddd", "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39" "bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb"); TestHMACSHA512("0102030405060708090a0b0c0d0e0f10111213141516171819", "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3db" "a91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a" "65204b6579202d2048617368204b6579204669727374", "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f352" "6b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "5468697320697320612074657374207573696e672061206c6172676572207468" "616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074" "68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565" "647320746f20626520686173686564206265666f7265206265696e6720757365" "642062792074686520484d414320616c676f726974686d2e", "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944" "b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58"); } BOOST_AUTO_TEST_CASE(pbkdf2_hmac_sha512_test) { // test vectors from // https://github.com/trezor/trezor-crypto/blob/87c920a7e747f7ed40b6ae841327868ab914435b/tests.c#L1936-L1957 // https://stackoverflow.com/questions/15593184/pbkdf2-hmac-sha-512-test-vectors uint8_t k[64], s[40]; strcpy((char *)s, "salt"); PKCS5_PBKDF2_HMAC("password", 8, s, 4, 1, EVP_sha512(), 64, k); BOOST_CHECK(HexStr(k, k + 64) == "867f70cf1ade02cff3752599a3a53dc4af34c7a669815ae5d513554e1c8cf252c02d470a285a0501bad999bfe943c08f050235d7d68b1da55e63f73b60a57fce"); strcpy((char *)s, "salt"); PKCS5_PBKDF2_HMAC("password", 8, s, 4, 2, EVP_sha512(), 64, k); BOOST_CHECK(HexStr(k, k + 64) == "e1d9c16aa681708a45f5c7c4e215ceb66e011a2e9f0040713f18aefdb866d53cf76cab2868a39b9f7840edce4fef5a82be67335c77a6068e04112754f27ccf4e"); strcpy((char *)s, "salt"); PKCS5_PBKDF2_HMAC("password", 8, s, 4, 4096, EVP_sha512(), 64, k); BOOST_CHECK(HexStr(k, k + 64) == "d197b1b33db0143e018b12f3d1d1479e6cdebdcc97c5c0f87f6902e072f457b5143f30602641b3d55cd335988cb36b84376060ecd532e039b742a239434af2d5"); strcpy((char *)s, "saltSALTsaltSALTsaltSALTsaltSALTsalt"); PKCS5_PBKDF2_HMAC("passwordPASSWORDpassword", 3*8, s, 9*4, 4096, EVP_sha512(), 64, k); BOOST_CHECK(HexStr(k, k + 64) == "8c0511f4c6e597c6ac6315d8f0362e225f3c501495ba23b868c005174dc4ee71115b59f9e60cd9532fa33e0f75aefe30225c583a186cd82bd4daea9724a3d3b8"); } BOOST_AUTO_TEST_SUITE_END()
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // This file implements conversion of `linalg.tiled_loop` to buffer form. #include "mlir/Dialect/Linalg/IR/LinalgOps.h" // from @llvm-project #include "mlir/Dialect/Linalg/Transforms/Transforms.h" // from @llvm-project #include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project #include "mlir/Dialect/SCF/SCF.h" // from @llvm-project #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/BlockAndValueMapping.h" // from @llvm-project #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/ImplicitLocOpBuilder.h" // from @llvm-project #include "mlir/Transforms/DialectConversion.h" // from @llvm-project #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/chlo_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" #include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" namespace mlir { namespace kernel_gen { namespace transforms { namespace { using linalg::FillOp; using linalg::InitTensorOp; using linalg::TiledLoopOp; using memref::BufferCastOp; using memref::SubViewOp; using memref::TensorLoadOp; using tensor::ExtractSliceOp; using tensor::InsertSliceOp; using vector::TransferReadOp; using vector::TransferWriteOp; /// Convert `tensor.extract_slice` to `memref.subview` in-place. struct BufferizeExtractSliceOp : public OpConversionPattern<ExtractSliceOp> { using OpConversionPattern<ExtractSliceOp>::OpConversionPattern; LogicalResult matchAndRewrite( ExtractSliceOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { if (!op->getParentOfType<TiledLoopOp>()) return failure(); ExtractSliceOp::Adaptor adaptor(operands, op->getAttrDictionary()); rewriter.replaceOpWithNewOp<SubViewOp>( op, adaptor.source(), op.getMixedOffsets(), op.getMixedSizes(), op.getMixedStrides()); return success(); } }; /// Convert `linalg.fill` on tensors to `linalg.fill` on buffers. struct BufferizeFillOp : public OpConversionPattern<FillOp> { using OpConversionPattern<FillOp>::OpConversionPattern; LogicalResult matchAndRewrite( FillOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { if (!op->getParentOfType<TiledLoopOp>()) return failure(); linalg::FillOpAdaptor adaptor(operands, op->getAttrDictionary()); rewriter.create<FillOp>(op.getLoc(), adaptor.value(), adaptor.output()); rewriter.replaceOp(op, adaptor.output()); return success(); } }; /// Convert `linalg.init_tensor` of `memref.alloc`. struct BufferizeInitTensorOp : public OpConversionPattern<InitTensorOp> { using OpConversionPattern<InitTensorOp>::OpConversionPattern; LogicalResult matchAndRewrite( InitTensorOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { if (!op->getParentOfType<TiledLoopOp>()) return failure(); linalg::InitTensorOpAdaptor adaptor(operands, op->getAttrDictionary()); rewriter.replaceOpWithNewOp<memref::AllocOp>( op, getTypeConverter()->convertType(op.getType()).cast<MemRefType>(), adaptor.sizes()); return success(); } }; bool IsBlockArgOfTiledLoop(Value value) { if (auto block_arg = value.dyn_cast<BlockArgument>()) return isa<TiledLoopOp>(block_arg.getOwner()->getParentOp()); return false; } // Attempts to find an existing `memref.subview` of `destMemRef` in the tiled // loop. The assumption is that in `linalg.tiled_loop` the tile of the output // tensor that we read and the tile that we write to are the same. Value FindExistingSubview(Value destMemRef) { if (auto buffer_cast = destMemRef.getDefiningOp<BufferCastOp>()) { if (auto tensor_load = buffer_cast.tensor().getDefiningOp<TensorLoadOp>()) { if (!IsBlockArgOfTiledLoop(tensor_load.memref())) return Value{}; // Scan through users of the block argument to find `subview` op. for (Operation *tensor_user : buffer_cast.tensor().getUsers()) { if (auto another_cast = mlir::dyn_cast<BufferCastOp>(tensor_user)) { for (Operation *memref_user : another_cast.memref().getUsers()) { if (auto subview = mlir::dyn_cast<SubViewOp>(memref_user)) { if (subview.source() == destMemRef) return subview; } } } } } } return Value{}; } /// Convert `tensor.insert_slice` to `memref.subview` in-place. struct BufferizeInsertSliceOp : public OpConversionPattern<InsertSliceOp> { public: using OpConversionPattern<InsertSliceOp>::OpConversionPattern; LogicalResult matchAndRewrite( InsertSliceOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { InsertSliceOp::Adaptor adaptor(operands, op->getAttrDictionary()); Value sourceMemRef = adaptor.source(); assert(sourceMemRef.getType().isa<MemRefType>()); Value destMemRef = adaptor.dest(); assert(destMemRef.getType().isa<MemRefType>()); if (!op->getParentOfType<TiledLoopOp>()) return failure(); Value subview = FindExistingSubview(destMemRef); if (!subview) { subview = rewriter.create<SubViewOp>( op.getLoc(), destMemRef, op.getMixedOffsets(), op.getMixedSizes(), op.getMixedStrides()); } rewriter.create<linalg::CopyOp>(op.getLoc(), sourceMemRef, subview); rewriter.replaceOp(op, destMemRef); return success(); } }; // Bufferize LinalgOps in-place. struct BufferizeLinalgOp : public OpInterfaceConversionPattern<linalg::LinalgOp> { using OpInterfaceConversionPattern< linalg::LinalgOp>::OpInterfaceConversionPattern; LogicalResult matchAndRewrite( linalg::LinalgOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { if (!op->getParentOfType<TiledLoopOp>()) return failure(); // GenericOpAdaptor below expects an `operand_segment_sizes` attribute. if (!op->hasAttr("operand_segment_sizes")) return failure(); // TODO(b/199046880): Replace this with LinalgOp::Adaptor or equivalent. linalg::GenericOpAdaptor adaptor(operands, op->getAttrDictionary()); mlir::linalg::createLinalgOpOnBuffers(rewriter, op, adaptor.inputs(), adaptor.outputs()); rewriter.replaceOp(op, adaptor.outputs()); return success(); } }; // Convert `linalg.yield` terminator of `linalg.tiled_loop` to `linalg.yield` // with no arguments. struct BufferizeLinalgYieldOp : public OpConversionPattern<linalg::YieldOp> { using OpConversionPattern<linalg::YieldOp>::OpConversionPattern; LogicalResult matchAndRewrite( linalg::YieldOp op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { if (!mlir::dyn_cast<TiledLoopOp>(op->getParentOp()) || operands.empty()) return failure(); rewriter.replaceOpWithNewOp<linalg::YieldOp>(op); return success(); } }; // FuncOp-like bufferization pattern for `linalg.tiled_loop` that inserts // `memref.tensor_load` ops for every memref block argument. struct BufferizeTiledLoopOp : public OpConversionPattern<TiledLoopOp> { using OpConversionPattern<TiledLoopOp>::OpConversionPattern; LogicalResult matchAndRewrite( TiledLoopOp loop, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { TiledLoopOp::Adaptor adaptor(operands, loop->getAttrDictionary()); if (loop.getNumResults() == 0) return failure(); // The following code to set distribution_type is due to the following bug // causing distribution_types to return an ArrayAttr instead of an // Optional<ArrayAttr>. https://bugs.llvm.org/show_bug.cgi?id=51622 llvm::Optional<ArrayAttr> distribution_types = adaptor.distribution_types(); if (!distribution_types.getValue()) distribution_types = llvm::None; auto new_loop = rewriter.create<TiledLoopOp>( loop.getLoc(), adaptor.lowerBound(), adaptor.upperBound(), adaptor.step(), adaptor.inputs(), adaptor.outputs(), adaptor.iterator_types(), distribution_types); Location loc = loop.getLoc(); BlockAndValueMapping bvm; bvm.map(loop.getInductionVars(), new_loop.getInductionVars()); OpBuilder innerBuilder = OpBuilder::atBlockEnd(new_loop.getBody(), rewriter.getListener()); // Map input tensors block arguments of the pre-bufferized loop to the // `tensor.tensor_load` results of the bufferized loop. SmallVector<Value, 2> inputs; for (auto en : llvm::zip(new_loop.getRegionInputArgs(), loop.getRegionInputArgs())) { Value newArg = std::get<0>(en); if (!newArg.getType().isa<ShapedType>()) { inputs.push_back(newArg); continue; } inputs.push_back(innerBuilder.create<TensorLoadOp>(loc, std::get<0>(en))); } bvm.map(loop.getRegionInputArgs(), inputs); // Map output tensors block arguments of the pre-bufferized loop to the // `tensor.tensor_load` results of the bufferized loop. SmallVector<Value, 2> outputs; for (auto en : llvm::zip(new_loop.getRegionOutputArgs(), loop.getRegionOutputArgs())) { Value newArg = std::get<0>(en); if (!newArg.getType().isa<ShapedType>()) { outputs.push_back(newArg); continue; } outputs.push_back( innerBuilder.create<TensorLoadOp>(loc, std::get<0>(en))); } bvm.map(loop.getRegionOutputArgs(), outputs); // Clone the region. for (auto &op : loop.getBody()->getOperations()) innerBuilder.clone(op, bvm); rewriter.replaceOp(loop, new_loop.outputs()); return success(); } }; // TODO(b/199045477): The pattern for vector.transfer_read/write have to be // moved out of Linalg bufferization to a VectorOps bufferization pass. struct BufferizeVectorTransferReadOp : public OpConversionPattern<vector::TransferReadOp> { using OpConversionPattern<vector::TransferReadOp>::OpConversionPattern; LogicalResult matchAndRewrite( vector::TransferReadOp readOp, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { if (readOp.getShapedType().isa<MemRefType>()) return failure(); vector::TransferReadOp::Adaptor adaptor(operands, readOp->getAttrDictionary()); rewriter.replaceOpWithNewOp<vector::TransferReadOp>( readOp, readOp.getType(), adaptor.source(), adaptor.indices(), adaptor.permutation_map(), adaptor.padding(), adaptor.mask(), adaptor.in_bounds() ? adaptor.in_bounds() : ArrayAttr()); return success(); } }; struct BufferizeVectorTransferWriteOp : public OpConversionPattern<vector::TransferWriteOp> { using OpConversionPattern<vector::TransferWriteOp>::OpConversionPattern; LogicalResult matchAndRewrite( vector::TransferWriteOp writeOp, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { if (writeOp.getShapedType().isa<MemRefType>()) return failure(); vector::TransferWriteOp::Adaptor adaptor(operands, writeOp->getAttrDictionary()); rewriter.create<vector::TransferWriteOp>( writeOp.getLoc(), adaptor.vector(), adaptor.source(), adaptor.indices(), adaptor.permutation_map(), adaptor.in_bounds() ? adaptor.in_bounds() : ArrayAttr()); rewriter.replaceOp(writeOp, adaptor.source()); return success(); } }; } // namespace void populateTiledLoopBufferizePattern(MLIRContext *context, BufferizeTypeConverter *converter, RewritePatternSet *patterns) { // clang-format off patterns->insert< BufferizeExtractSliceOp, BufferizeFillOp, BufferizeInitTensorOp, BufferizeInsertSliceOp, BufferizeLinalgOp, BufferizeLinalgYieldOp, BufferizeTiledLoopOp, BufferizeVectorTransferReadOp, BufferizeVectorTransferWriteOp >(*converter, context); // clang-format on } } // namespace transforms } // namespace kernel_gen } // namespace mlir
#include "Xiang.h" Xiang::Xiang(QObject *parent, Player player, int x, int y) : ChessPiece(parent, player, player == Player::Black ? "象" : "相", x, y,6) {} bool Xiang::canMoveTo(const IBoard *board, int x, int y) const { if (board->isCrossRiver(_player, y)) { return false; } auto currX = _position.x(); auto currY = _position.y(); if (abs(currX - x) != 2 || abs(currY - y) != 2) { return false; } auto deltaXToBlock = (x - currX) / 2; auto deltaYToBlock = (y - currY) / 2; auto blockX = currX + deltaXToBlock; auto blockY = currY + deltaYToBlock; auto p = board->getPlayer(blockX, blockY); return p == Player::None; }
/** @file @author Shin'ichiro Nakaoka */ #include "MultiAffine3Seq.h" #include "PlainSeqFormatLoader.h" #include "ValueTree.h" #include "YAMLWriter.h" #include "EigenUtil.h" #include <boost/format.hpp> using namespace std; using namespace cnoid; MultiAffine3Seq::MultiAffine3Seq() : MultiAffine3Seq::BaseSeqType("MultiAffine3Seq") { } MultiAffine3Seq::MultiAffine3Seq(int numFrames, int numParts) : MultiAffine3Seq::BaseSeqType("MultiAffine3Seq", numFrames, numParts) { } MultiAffine3Seq::MultiAffine3Seq(const MultiAffine3Seq& org) : MultiAffine3Seq::BaseSeqType(org) { } MultiAffine3Seq::~MultiAffine3Seq() { } AbstractSeqPtr MultiAffine3Seq::cloneSeq() const { return std::make_shared<MultiAffine3Seq>(*this); } bool MultiAffine3Seq::loadPlainFormat(const std::string& filename) { clearSeqMessage(); PlainSeqFileLoader loader; if(!loader.load(filename)){ addSeqMessage(loader.errorMessage()); return false; } if(loader.numParts() < 12){ addSeqMessage(filename + "does not have 12-columns " "(3 for position vectors, 9 for attitde matrices)"); return false; } setDimension(loader.numFrames(), 1); setTimeStep(loader.timeStep()); int i = 0; Part base = part(0); for(PlainSeqFileLoader::iterator it = loader.begin(); it != loader.end(); ++it){ vector<double>& data = *it; base[i].translation() << data[1], data[2], data[3]; base[i].linear() << data[ 4], data[ 5], data[ 6], data[ 7], data[ 8], data[ 9], data[10], data[11], data[12]; ++i; } return true; } bool MultiAffine3Seq::saveTopPartAsPlainFormat(const std::string& filename) { clearSeqMessage(); boost::format f("%1$.4f"); const int nFrames = numFrames(); if(nFrames > 0 && numParts() > 0){ ofstream os(filename.c_str()); if(!os){ addSeqMessage(filename + " cannot be opened."); return false; } const double r = frameRate(); Part base = part(0); for(int i=0; i < nFrames; ++i){ os << (f % (i / r)); const Affine3& T = base[i]; for(int j=0; j < 3; ++j){ os << " " << T.translation()[j]; } for(int j=0; j < 3; ++j){ for(int k=0; k < 3; ++k){ double m = T.linear()(j, k); if(fabs(m) < 1.0e-14){ m = 0.0; } os << " " << m; } } os << " 0 0 0 0 0 0"; // velocity elements (dv, omega) os << "\n"; } return true; } return false; } static inline void writeAffine3(YAMLWriter& writer, const Affine3& value) { writer.startFlowStyleListing(); writer.putScalar(value.translation().x()); writer.putScalar(value.translation().y()); writer.putScalar(value.translation().z()); Vector3 rpy(rpyFromRot(value.linear())); writer.putScalar(rpy[0]); writer.putScalar(rpy[1]); writer.putScalar(rpy[2]); writer.endListing(); } bool MultiAffine3Seq::doWriteSeq(YAMLWriter& writer) { if(BaseSeqType::doWriteSeq(writer)){ writer.putKeyValue("format", "XYZRPY"); writer.putKey("frames"); writer.startListing(); const int m = numParts(); const int n = numFrames(); for(int i=0; i < n; ++i){ Frame f = frame(i); writer.startFlowStyleListing(); for(int j=0; j < m; ++j){ writeAffine3(writer, f[j]); } writer.endListing(); } writer.endListing(); return true; } return false; } static void readAffine3(const Listing& node, Affine3& out_value) { if(node.size() == 6){ Affine3::TranslationPart t = out_value.translation(); t[0] = node[0].toDouble(); t[1] = node[1].toDouble(); t[2] = node[2].toDouble(); const double r = node[3].toDouble(); const double p = node[4].toDouble(); const double y = node[5].toDouble(); out_value.linear() = rotFromRpy(r, p, y); } } bool MultiAffine3Seq::doReadSeq(const Mapping& archive) { if(BaseSeqType::doReadSeq(archive)){ const string& type = archive["type"].toString(); if((type == seqType() || type == "MultiSe3Seq") && (archive["format"].toString() == "XYZRPY")){ const Listing& values = *archive.findListing("frames"); if(values.isValid()){ const int nParts = archive["numParts"].toInt(); const int nFrames = values.size(); setDimension(nFrames, nParts); for(int i=0; i < nFrames; ++i){ const Listing& frameNode = *values[i].toListing(); Frame f = frame(i); const int n = std::min(frameNode.size(), nParts); for(int j=0; j < n; ++j){ readAffine3(*frameNode[j].toListing(), f[j]); } } return true; } } } return false; }
/** * * 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 <utility> #include <string> #include <map> #include <vector> #include <set> #include "core/ConfigurableComponent.h" #include "core/logging/LoggerConfiguration.h" namespace org { namespace apache { namespace nifi { namespace minifi { namespace core { ConfigurableComponent::ConfigurableComponent() : logger_(logging::LoggerFactory<ConfigurableComponent>::getLogger()) { } ConfigurableComponent::ConfigurableComponent(const ConfigurableComponent &&other) : properties_(std::move(other.properties_)), dynamic_properties_(std::move(other.dynamic_properties_)), logger_(logging::LoggerFactory<ConfigurableComponent>::getLogger()) { } ConfigurableComponent::~ConfigurableComponent() { } bool ConfigurableComponent::getProperty(const std::string &name, Property &prop) { std::lock_guard<std::mutex> lock(configuration_mutex_); auto &&it = properties_.find(name); if (it != properties_.end()) { prop = it->second; return true; } else { return false; } } /** * Get property using the provided name. * @param name property name. * @param value value passed in by reference * @return result of getting property. */ bool ConfigurableComponent::getProperty(const std::string name, std::string &value) { std::lock_guard<std::mutex> lock(configuration_mutex_); auto &&it = properties_.find(name); if (it != properties_.end()) { Property item = it->second; value = item.getValue(); logger_->log_debug("Component %s property name %s value %s", name, item.getName(), value); return true; } else { return false; } } /** * Sets the property using the provided name * @param property name * @param value property value. * @return result of setting property. */ bool ConfigurableComponent::setProperty(const std::string name, std::string value) { std::lock_guard<std::mutex> lock(configuration_mutex_); auto &&it = properties_.find(name); if (it != properties_.end()) { Property &orig_property = it->second; Property new_property = orig_property; new_property.setValue(value); properties_[new_property.getName()] = new_property; onPropertyModified(orig_property, new_property); logger_->log_debug("Component %s property name %s value %s", name, new_property.getName(), value); return true; } else { return false; } } /** * Sets the property using the provided name * @param property name * @param value property value. * @return result of setting property. */ bool ConfigurableComponent::updateProperty(const std::string &name, const std::string &value) { std::lock_guard<std::mutex> lock(configuration_mutex_); auto &&it = properties_.find(name); if (it != properties_.end()) { Property &orig_property = it->second; Property new_property = orig_property; new_property.addValue(value); properties_[new_property.getName()] = new_property; onPropertyModified(orig_property, new_property); logger_->log_debug("Component %s property name %s value %s", name, new_property.getName(), value); return true; } else { return false; } } /** * Sets the property using the provided name * @param property name * @param value property value. * @return whether property was set or not */ bool ConfigurableComponent::setProperty(Property &prop, std::string value) { std::lock_guard<std::mutex> lock(configuration_mutex_); auto it = properties_.find(prop.getName()); if (it != properties_.end()) { Property &orig_property = it->second; Property new_property = orig_property; new_property.setValue(value); properties_[new_property.getName()] = new_property; onPropertyModified(orig_property, new_property); logger_->log_debug("property name %s value %s", prop.getName(), new_property.getName(), value); return true; } else { Property new_property(prop); new_property.setValue(value); properties_.insert(std::pair<std::string, Property>(prop.getName(), new_property)); onPropertyModified({}, new_property); return true; } } /** * Sets supported properties for the ConfigurableComponent * @param supported properties * @return result of set operation. */ bool ConfigurableComponent::setSupportedProperties(std::set<Property> properties) { if (!canEdit()) { return false; } std::lock_guard<std::mutex> lock(configuration_mutex_); properties_.clear(); for (auto item : properties) { properties_[item.getName()] = item; } return true; } bool ConfigurableComponent::getDynamicProperty(const std::string name, std::string &value) { std::lock_guard<std::mutex> lock(configuration_mutex_); auto &&it = dynamic_properties_.find(name); if (it != dynamic_properties_.end()) { Property item = it->second; value = item.getValue(); logger_->log_debug("Component %s dynamic property name %s value %s", name, item.getName(), value); return true; } else { return false; } } bool ConfigurableComponent::createDynamicProperty(const std::string &name, const std::string &value) { if (!supportsDynamicProperties()) { logger_->log_debug("Attempted to create dynamic property %s, but this component does not support creation." "of dynamic properties.", name); return false; } Property new_property(name, DEFAULT_DYNAMIC_PROPERTY_DESC, value, false, "", {}, {}); logger_->log_info("Processor %s dynamic property '%s' value '%s'", name.c_str(), new_property.getName().c_str(), value.c_str()); dynamic_properties_[new_property.getName()] = new_property; onDynamicPropertyModified({}, new_property); return true; } bool ConfigurableComponent::setDynamicProperty(const std::string name, std::string value) { std::lock_guard<std::mutex> lock(configuration_mutex_); auto &&it = dynamic_properties_.find(name); if (it != dynamic_properties_.end()) { Property &orig_property = it->second; Property new_property = orig_property; new_property.setValue(value); dynamic_properties_[new_property.getName()] = new_property; onDynamicPropertyModified(orig_property, new_property); logger_->log_debug("Component %s dynamic property name %s value %s", name, new_property.getName(), value); return true; } else { return createDynamicProperty(name, value); } } bool ConfigurableComponent::updateDynamicProperty(const std::string &name, const std::string &value) { std::lock_guard<std::mutex> lock(configuration_mutex_); auto &&it = dynamic_properties_.find(name); if (it != dynamic_properties_.end()) { Property &orig_property = it->second; Property new_property = orig_property; new_property.addValue(value); dynamic_properties_[new_property.getName()] = new_property; onDynamicPropertyModified(orig_property, new_property); logger_->log_debug("Component %s dynamic property name %s value %s", name, new_property.getName(), value); return true; } else { return createDynamicProperty(name, value); } } std::vector<std::string> ConfigurableComponent::getDynamicPropertyKeys() { std::lock_guard<std::mutex> lock(configuration_mutex_); std::vector<std::string> result; for (const auto &pair : dynamic_properties_) { result.emplace_back(pair.first); } return result; } std::map<std::string, Property> ConfigurableComponent::getProperties() { std::lock_guard<std::mutex> lock(configuration_mutex_); std::map<std::string, Property> result; for (const auto &pair : properties_) { result.insert({pair.first, pair.second}); } for (const auto &pair : dynamic_properties_) { result.insert({pair.first, pair.second}); } return result; } } /* namespace core */ } /* namespace minifi */ } /* namespace nifi */ } /* namespace apache */ } /* namespace org */
#include<iostream> using namespace std; int main() { int range; int result; cout<<"Enter a number range to sum: "; cin>>range; for ( int z=1;z<=range;z++) { result+=z; } cout<<"Sum from 1 to "<<z<<" is "<<z; return 0; }
// // Copyright 2015 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include <gtest/gtest.h> #include "test_utils/ANGLETest.h" using namespace angle; class EGLQueryContextTest : public ANGLETest { public: void testSetUp() override { int clientVersion = GetParam().majorVersion; EGLint dispattrs[] = {EGL_PLATFORM_ANGLE_TYPE_ANGLE, GetParam().getRenderer(), EGL_NONE}; mDisplay = eglGetPlatformDisplayEXT( EGL_PLATFORM_ANGLE_ANGLE, reinterpret_cast<void *>(EGL_DEFAULT_DISPLAY), dispattrs); EXPECT_TRUE(mDisplay != EGL_NO_DISPLAY); EXPECT_TRUE(eglInitialize(mDisplay, nullptr, nullptr) != EGL_FALSE); EGLint ncfg; EGLint cfgattrs[] = {EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_RENDERABLE_TYPE, clientVersion == 3 ? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_NONE}; EXPECT_TRUE(eglChooseConfig(mDisplay, cfgattrs, &mConfig, 1, &ncfg) != EGL_FALSE); EXPECT_TRUE(ncfg == 1); EGLint ctxattrs[] = {EGL_CONTEXT_CLIENT_VERSION, clientVersion, EGL_NONE}; mContext = eglCreateContext(mDisplay, mConfig, nullptr, ctxattrs); EXPECT_TRUE(mContext != EGL_NO_CONTEXT); EGLint surfattrs[] = {EGL_WIDTH, 16, EGL_HEIGHT, 16, EGL_NONE}; mSurface = eglCreatePbufferSurface(mDisplay, mConfig, surfattrs); EXPECT_TRUE(mSurface != EGL_NO_SURFACE); } void testTearDown() override { if (mDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(mDisplay, mContext); eglDestroySurface(mDisplay, mSurface); eglTerminate(mDisplay); } ASSERT_EGL_SUCCESS() << "Error during test TearDown"; } EGLDisplay mDisplay; EGLConfig mConfig; EGLContext mContext; EGLSurface mSurface; }; TEST_P(EGLQueryContextTest, GetConfigID) { EGLint configId, contextConfigId; EXPECT_TRUE(eglGetConfigAttrib(mDisplay, mConfig, EGL_CONFIG_ID, &configId) != EGL_FALSE); EXPECT_TRUE(eglQueryContext(mDisplay, mContext, EGL_CONFIG_ID, &contextConfigId) != EGL_FALSE); EXPECT_TRUE(configId == contextConfigId); } TEST_P(EGLQueryContextTest, GetClientType) { EGLint clientType; EXPECT_TRUE(eglQueryContext(mDisplay, mContext, EGL_CONTEXT_CLIENT_TYPE, &clientType) != EGL_FALSE); EXPECT_TRUE(clientType == EGL_OPENGL_ES_API); } TEST_P(EGLQueryContextTest, GetClientVersion) { EGLint clientVersion; EXPECT_TRUE(eglQueryContext(mDisplay, mContext, EGL_CONTEXT_CLIENT_VERSION, &clientVersion) != EGL_FALSE); EXPECT_GE(clientVersion, GetParam().majorVersion); } TEST_P(EGLQueryContextTest, GetRenderBufferNoSurface) { EGLint renderBuffer; EXPECT_TRUE(eglQueryContext(mDisplay, mContext, EGL_RENDER_BUFFER, &renderBuffer) != EGL_FALSE); EXPECT_TRUE(renderBuffer == EGL_NONE); } TEST_P(EGLQueryContextTest, GetRenderBufferBoundSurface) { EGLint renderBuffer, contextRenderBuffer; EXPECT_TRUE(eglQuerySurface(mDisplay, mSurface, EGL_RENDER_BUFFER, &renderBuffer) != EGL_FALSE); EXPECT_TRUE(eglMakeCurrent(mDisplay, mSurface, mSurface, mContext) != EGL_FALSE); EXPECT_TRUE(eglQueryContext(mDisplay, mContext, EGL_RENDER_BUFFER, &contextRenderBuffer) != EGL_FALSE); EXPECT_TRUE(renderBuffer == contextRenderBuffer); ASSERT_EGL_SUCCESS(); } TEST_P(EGLQueryContextTest, BadDisplay) { EGLint val; EXPECT_TRUE(eglQueryContext(EGL_NO_DISPLAY, mContext, EGL_CONTEXT_CLIENT_TYPE, &val) == EGL_FALSE); EXPECT_TRUE(eglGetError() == EGL_BAD_DISPLAY); } TEST_P(EGLQueryContextTest, NotInitialized) { EGLint val; testTearDown(); EXPECT_TRUE(eglQueryContext(mDisplay, mContext, EGL_CONTEXT_CLIENT_TYPE, &val) == EGL_FALSE); EXPECT_TRUE(eglGetError() == EGL_NOT_INITIALIZED); mDisplay = EGL_NO_DISPLAY; mSurface = EGL_NO_SURFACE; mContext = EGL_NO_CONTEXT; } TEST_P(EGLQueryContextTest, BadContext) { EGLint val; EXPECT_TRUE(eglQueryContext(mDisplay, EGL_NO_CONTEXT, EGL_CONTEXT_CLIENT_TYPE, &val) == EGL_FALSE); EXPECT_TRUE(eglGetError() == EGL_BAD_CONTEXT); } TEST_P(EGLQueryContextTest, BadAttribute) { EGLint val; EXPECT_TRUE(eglQueryContext(mDisplay, mContext, EGL_HEIGHT, &val) == EGL_FALSE); EXPECT_TRUE(eglGetError() == EGL_BAD_ATTRIBUTE); } ANGLE_INSTANTIATE_TEST(EGLQueryContextTest, WithNoFixture(ES2_D3D9()), WithNoFixture(ES2_D3D11()), WithNoFixture(ES2_OPENGL()), WithNoFixture(ES2_VULKAN()), WithNoFixture(ES3_D3D11()), WithNoFixture(ES3_OPENGL()));
/** * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 20220523 * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QVariantMap> #include <QDebug> #include "OAILocationAreaApiHandler.h" #include "OAILocationAreaApiRequest.h" namespace OpenAPI { OAILocationAreaApiHandler::OAILocationAreaApiHandler(){ } OAILocationAreaApiHandler::~OAILocationAreaApiHandler(){ } void OAILocationAreaApiHandler::locationAreaList(qint32 limit, qint32 offset) { Q_UNUSED(limit); Q_UNUSED(offset); auto reqObj = qobject_cast<OAILocationAreaApiRequest*>(sender()); if( reqObj != nullptr ) { QString res; reqObj->locationAreaListResponse(res); } } void OAILocationAreaApiHandler::locationAreaRead(qint32 id) { Q_UNUSED(id); auto reqObj = qobject_cast<OAILocationAreaApiRequest*>(sender()); if( reqObj != nullptr ) { QString res; reqObj->locationAreaReadResponse(res); } } }
// Copyright (c) Christopher Di Bella. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // #ifndef CJDB_TEST_FUNCTIONAL_RANGECMP_IS_ASYMMETRIC_HPP #define CJDB_TEST_FUNCTIONAL_RANGECMP_IS_ASYMMETRIC_HPP #include "cjdb/concepts/callable/relation.hpp" #include "cjdb/concepts/comparison/equality_comparable.hpp" #include "cjdb/test/constexpr_check.hpp" #include "cjdb/test/functional/rangecmp/is_antisymmetric.hpp" #include "cjdb/test/functional/rangecmp/is_irreflexive.hpp" #include <utility> namespace cjdb_test { template<class R> class is_asymmetric : private is_irreflexive<R> , private is_antisymmetric<R> { public: constexpr explicit is_asymmetric(R r) noexcept : is_irreflexive<R>(r) , is_antisymmetric<R>(r) {} template<class A, cjdb::equality_comparable_with<A> B> requires cjdb::relation<R, A, B> [[nodiscard]] constexpr bool asymmetric(A const& a, B const& b) noexcept { return asymmetric_impl(*this, a, b); } template<class A, cjdb::equality_comparable_with<A> B> requires cjdb::relation<R, A, B> [[nodiscard]] constexpr bool asymmetric(A const& a, B const& b) const noexcept { return asymmetric_impl(*this, a, b); } private: template<class Self, class A, class B> [[nodiscard]] constexpr bool asymmetric_impl(Self& self, A const& a, B const& b) noexcept { return self.irreflexive(a) and self.irreflexive(b) and self.antisymmetric(a, b); } }; } // namespace cjdb_test #define CHECK_IS_ASYMMETRIC(r, a, b) \ CJDB_CONSTEXPR_CHECK(cjdb_test::is_asymmetric{r}.asymmetric(a, b)) #endif // CJDB_TEST_FUNCTIONAL_RANGECMP_IS_ASYMMETRIC_HPP
/********************************************************************** Audacity: A Digital Audio Editor SilentBlockFile.cpp Joshua Haberman **********************************************************************/ #include "SilentBlockFile.h" #include "../FileFormats.h" SilentBlockFile::SilentBlockFile(sampleCount sampleLen): BlockFile(wxFileName(), sampleLen) { mMin = 0.; mMax = 0.; mRMS = 0.; } SilentBlockFile::~SilentBlockFile() { } bool SilentBlockFile::ReadSummary(void *data) { memset(data, 0, (size_t)mSummaryInfo.totalSummaryBytes); return true; } int SilentBlockFile::ReadData(samplePtr data, sampleFormat format, sampleCount start, sampleCount len) { ClearSamples(data, format, 0, len); return len; } void SilentBlockFile::SaveXML(XMLWriter &xmlFile) { xmlFile.StartTag(wxT("silentblockfile")); xmlFile.WriteAttr(wxT("len"), mLen); xmlFile.EndTag(wxT("silentblockfile")); } // BuildFromXML methods should always return a BlockFile, not NULL, // even if the result is flawed (e.g., refers to nonexistent file), // as testing will be done in DirManager::ProjectFSCK(). /// static BlockFile *SilentBlockFile::BuildFromXML(DirManager &dm, const wxChar **attrs) { long nValue; sampleCount len = 0; while(*attrs) { const wxChar *attr = *attrs++; const wxChar *value = *attrs++; if (!value) break; const wxString strValue = value; if (!wxStrcmp(attr, wxT("len")) && XMLValueChecker::IsGoodInt(strValue) && strValue.ToLong(&nValue) && nValue > 0) len = nValue; } return new SilentBlockFile(len); } /// Create a copy of this BlockFile BlockFile *SilentBlockFile::Copy(wxFileName newFileName) { BlockFile *newBlockFile = new SilentBlockFile(mLen); return newBlockFile; } wxLongLong SilentBlockFile::GetSpaceUsage() { return 0; }
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/common_shape_fns.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/lib/strings/strcat.h" namespace tensorflow { namespace { constexpr auto kRNNModeAttrs = "rnn_mode: {'rnn_relu', 'rnn_tanh', 'lstm', 'gru'} = 'lstm'"; constexpr auto kRNNInputModeAttrs = "input_mode: {'linear_input', 'skip_input', 'auto_select'} = " "'linear_input'"; constexpr auto kRNNDirectionAttrs = "direction: {'unidirectional', 'bidirectional'} = 'unidirectional'"; } // namespace using shape_inference::DimensionHandle; using shape_inference::InferenceContext; using shape_inference::ShapeHandle; REGISTER_OP("CudnnRNNParamsSize") .Input("num_layers: int32") .Input("num_units: int32") .Input("input_size: int32") .Attr("T: {float16, float32, float64}") .Attr("S: {int32, int64}") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .Attr("num_proj: int = 0") .Output("params_size: S") .SetShapeFn([](InferenceContext* c) { ShapeHandle unused; // num_layers, num_units, and input_size should be scalars. TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &unused)); TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 0, &unused)); TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 0, &unused)); c->set_output(0, c->Vector(1)); return Status::OK(); }); REGISTER_OP("CudnnRNN") .Input("input: T") .Input("input_h: T") .Input("input_c: T") .Input("params: T") .SetIsStateful() .Output("output: T") .Output("output_h: T") .Output("output_c: T") .Output("reserve_space: T") .Attr("T: {float16, float32, float64}") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .Attr("is_training: bool = true") .SetShapeFn([](InferenceContext* c) { ShapeHandle unused; auto input_shape = c->input(0); auto input_h_shape = c->input(1); TF_RETURN_IF_ERROR(c->WithRank(input_shape, 3, &unused)); TF_RETURN_IF_ERROR(c->WithRank(input_h_shape, 3, &unused)); TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &unused)); auto seq_length = c->Dim(input_shape, 0); auto batch_size = c->Dim(input_shape, 1); auto num_units = c->Dim(input_h_shape, 2); string direction; TF_RETURN_IF_ERROR(c->GetAttr("direction", &direction)); string rnn_mode; TF_RETURN_IF_ERROR(c->GetAttr("rnn_mode", &rnn_mode)); int dir_count = (direction == "bidirectional") ? 2 : 1; DimensionHandle output_size; TF_RETURN_IF_ERROR(c->Multiply(num_units, dir_count, &output_size)); auto output_shape = c->MakeShape({seq_length, batch_size, output_size}); auto output_h_shape = input_h_shape; auto output_c_shape TF_ATTRIBUTE_UNUSED = (rnn_mode == "lstm") ? output_h_shape : c->MakeShape({}); c->set_output(0, output_shape); c->set_output(1, output_h_shape); c->set_output(2, output_c_shape); c->set_output(3, c->UnknownShape()); return Status::OK(); }); REGISTER_OP("CudnnRNNV2") .Input("input: T") .Input("input_h: T") .Input("input_c: T") .Input("params: T") .SetIsStateful() .Output("output: T") .Output("output_h: T") .Output("output_c: T") .Output("reserve_space: T") .Output("host_reserved: int8") .Attr("T: {float16, float32, float64}") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .Attr("is_training: bool = true") .SetShapeFn([](InferenceContext* c) { ShapeHandle unused; auto input_shape = c->input(0); auto input_h_shape = c->input(1); TF_RETURN_IF_ERROR(c->WithRank(input_shape, 3, &unused)); TF_RETURN_IF_ERROR(c->WithRank(input_h_shape, 3, &unused)); TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &unused)); auto seq_length = c->Dim(input_shape, 0); auto batch_size = c->Dim(input_shape, 1); auto num_units = c->Dim(input_h_shape, 2); string direction; TF_RETURN_IF_ERROR(c->GetAttr("direction", &direction)); string rnn_mode; TF_RETURN_IF_ERROR(c->GetAttr("rnn_mode", &rnn_mode)); int dir_count = (direction == "bidirectional") ? 2 : 1; DimensionHandle output_size; TF_RETURN_IF_ERROR(c->Multiply(num_units, dir_count, &output_size)); auto output_shape = c->MakeShape({seq_length, batch_size, output_size}); auto output_h_shape = input_h_shape; auto output_c_shape TF_ATTRIBUTE_UNUSED = (rnn_mode == "lstm") ? output_h_shape : c->MakeShape({}); c->set_output(0, output_shape); c->set_output(1, output_h_shape); c->set_output(2, output_c_shape); c->set_output(3, c->UnknownShape()); c->set_output(4, c->UnknownShape()); return Status::OK(); }); REGISTER_OP("CudnnRNNV3") .Input("input: T") .Input("input_h: T") .Input("input_c: T") .Input("params: T") .Input("sequence_lengths: int32") .SetIsStateful() .Output("output: T") .Output("output_h: T") .Output("output_c: T") .Output("reserve_space: T") .Output("host_reserved: int8") .Attr("T: {float16, float32, float64}") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .Attr("num_proj: int = 0") .Attr("is_training: bool = true") .Attr("time_major: bool = true") .SetShapeFn([](InferenceContext* c) { ShapeHandle unused; auto input_shape = c->input(0); auto input_h_shape = c->input(1); auto input_c_shape = c->input(2); TF_RETURN_IF_ERROR(c->WithRank(input_shape, 3, &unused)); TF_RETURN_IF_ERROR(c->WithRank(input_h_shape, 3, &unused)); TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &unused)); TF_RETURN_IF_ERROR(c->WithRank(c->input(4), 1, &unused)); auto max_seq_length = c->Dim(input_shape, 0); auto batch_size = c->Dim(input_shape, 1); auto num_units = c->Dim(input_h_shape, 2); string direction; TF_RETURN_IF_ERROR(c->GetAttr("direction", &direction)); string rnn_mode; TF_RETURN_IF_ERROR(c->GetAttr("rnn_mode", &rnn_mode)); if (rnn_mode == "lstm") { TF_RETURN_IF_ERROR(c->WithRank(input_c_shape, 3, &unused)); } int dir_count = (direction == "bidirectional") ? 2 : 1; DimensionHandle output_size; TF_RETURN_IF_ERROR(c->Multiply(num_units, dir_count, &output_size)); auto output_shape = c->MakeShape({max_seq_length, batch_size, output_size}); auto output_h_shape = input_h_shape; auto output_c_shape TF_ATTRIBUTE_UNUSED = (rnn_mode == "lstm") ? input_c_shape : c->MakeShape({}); c->set_output(0, output_shape); c->set_output(1, output_h_shape); c->set_output(2, output_c_shape); c->set_output(3, c->UnknownShape()); c->set_output(4, c->UnknownShape()); return Status::OK(); }); REGISTER_OP("CudnnRNNBackprop") .Input("input: T") .Input("input_h: T") .Input("input_c: T") .Input("params: T") .Input("output: T") .Input("output_h: T") .Input("output_c: T") .Input("output_backprop: T") .Input("output_h_backprop: T") .Input("output_c_backprop: T") .Input("reserve_space: T") .SetIsStateful() .Output("input_backprop: T") .Output("input_h_backprop: T") .Output("input_c_backprop: T") .Output("params_backprop: T") .Attr("T: {float16, float32, float64}") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .SetShapeFn([](InferenceContext* c) { auto input_shape = c->input(0); auto input_h_shape = c->input(1); auto input_c_shape = c->input(2); auto params_shape = c->input(3); c->set_output(0, input_shape); c->set_output(1, input_h_shape); c->set_output(2, input_c_shape); c->set_output(3, params_shape); return Status::OK(); }); REGISTER_OP("CudnnRNNBackpropV2") .Input("input: T") .Input("input_h: T") .Input("input_c: T") .Input("params: T") .Input("output: T") .Input("output_h: T") .Input("output_c: T") .Input("output_backprop: T") .Input("output_h_backprop: T") .Input("output_c_backprop: T") .Input("reserve_space: T") .Input("host_reserved: int8") .SetIsStateful() .Output("input_backprop: T") .Output("input_h_backprop: T") .Output("input_c_backprop: T") .Output("params_backprop: T") .Attr("T: {float16, float32, float64}") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .SetShapeFn([](InferenceContext* c) { auto input_shape = c->input(0); auto input_h_shape = c->input(1); auto input_c_shape = c->input(2); auto params_shape = c->input(3); c->set_output(0, input_shape); c->set_output(1, input_h_shape); c->set_output(2, input_c_shape); c->set_output(3, params_shape); return Status::OK(); }); REGISTER_OP("CudnnRNNBackpropV3") .Input("input: T") .Input("input_h: T") .Input("input_c: T") .Input("params: T") .Input("sequence_lengths: int32") .Input("output: T") .Input("output_h: T") .Input("output_c: T") .Input("output_backprop: T") .Input("output_h_backprop: T") .Input("output_c_backprop: T") .Input("reserve_space: T") .Input("host_reserved: int8") .SetIsStateful() .Output("input_backprop: T") .Output("input_h_backprop: T") .Output("input_c_backprop: T") .Output("params_backprop: T") .Attr("T: {float16, float32, float64}") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .Attr("num_proj: int = 0") .Attr("time_major: bool = true") .SetShapeFn([](InferenceContext* c) { auto input_shape = c->input(0); auto input_h_shape = c->input(1); auto input_c_shape = c->input(2); auto params_shape = c->input(3); c->set_output(0, input_shape); c->set_output(1, input_h_shape); c->set_output(2, input_c_shape); c->set_output(3, params_shape); return Status::OK(); }); REGISTER_OP("CudnnRNNParamsToCanonical") .Input("num_layers: int32") .Input("num_units: int32") .Input("input_size: int32") .Input("params: T") .Output("weights: num_params * T") .Output("biases: num_params * T") .Attr("T: {float16, float32, float64}") .Attr("num_params: int") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .SetShapeFn([](InferenceContext* c) { ShapeHandle unused; TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &unused)); int num_params; TF_RETURN_IF_ERROR(c->GetAttr("num_params", &num_params)); // Set shape for weight matrices for (int i = 0; i < num_params; i++) { c->set_output(i, c->Matrix(InferenceContext::kUnknownDim, InferenceContext::kUnknownDim)); } // Set shape for bias vectors for (int i = 0; i < num_params; i++) { c->set_output(num_params + i, c->Vector(InferenceContext::kUnknownDim)); } return Status::OK(); }); REGISTER_OP("CudnnRNNParamsToCanonicalV2") .Input("num_layers: int32") .Input("num_units: int32") .Input("input_size: int32") .Input("params: T") .Output("weights: num_params_weights * T") .Output("biases: num_params_biases * T") .Attr("T: {float16, float32, float64}") .Attr("num_params_weights: int") .Attr("num_params_biases: int") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .Attr("num_proj: int = 0") .SetShapeFn([](InferenceContext* c) { ShapeHandle unused; TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &unused)); int num_params_weights; int num_params_biases; TF_RETURN_IF_ERROR(c->GetAttr("num_params_weights", &num_params_weights)); TF_RETURN_IF_ERROR(c->GetAttr("num_params_biases", &num_params_biases)); // Set shape for weight matrices for (int i = 0; i < num_params_weights; i++) { c->set_output(i, c->Matrix(InferenceContext::kUnknownDim, InferenceContext::kUnknownDim)); } // Set shape for bias vectors for (int i = 0; i < num_params_biases; i++) { c->set_output(num_params_weights + i, c->Vector(InferenceContext::kUnknownDim)); } return Status::OK(); }); REGISTER_OP("CudnnRNNCanonicalToParams") .Input("num_layers: int32") .Input("num_units: int32") .Input("input_size: int32") .Input("weights: num_params * T") .Input("biases: num_params * T") .Output("params: T") .Attr("T: {float16, float32, float64}") .Attr("num_params: int") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->Vector(InferenceContext::kUnknownDim)); return Status::OK(); }); REGISTER_OP("CudnnRNNCanonicalToParamsV2") .Input("num_layers: int32") .Input("num_units: int32") .Input("input_size: int32") .Input("weights: num_params_weights * T") .Input("biases: num_params_biases * T") .Output("params: T") .Attr("T: {float16, float32, float64}") .Attr("num_params_weights: int") .Attr("num_params_biases: int") .Attr(kRNNModeAttrs) .Attr(kRNNInputModeAttrs) .Attr(kRNNDirectionAttrs) .Attr("dropout: float = 0.0") .Attr("seed: int = 0") .Attr("seed2: int = 0") .Attr("num_proj: int = 0") .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->Vector(InferenceContext::kUnknownDim)); return Status::OK(); }); } // namespace tensorflow
#ifndef ORIGEN_UTILS_INCLUDED #define ORIGEN_UTILS_INCLUDED #include "utils/version.hpp" namespace Origen { namespace Utils {} } #endif
#include "SignalDescriptor.hpp" SignalDescriptor::SignalDescriptor(int row, int col, int radius, double variance, cv::Mat signal, cv::Mat signalPCA) : fRow(row), fCol(col), fRadius(radius), fVariance(variance), fSignal(signal){ } SignalDescriptor::~SignalDescriptor(){ } int SignalDescriptor::getRadius(){ return fRadius; } int SignalDescriptor::getRow(){ return fRow; } int SignalDescriptor::getCol(){ return fCol; } double SignalDescriptor::getVariance(){ return fVariance; } cv::Mat SignalDescriptor::getSignal(){ return fSignal; } void SignalDescriptor::setFarthestRing(cv::vector<cv::Point2i> &ring){ fFarthestRing=ring; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Calculates the distance between two points as follows: /// find distance of row coordinates /// find distance of col coordinates /// return largest distance of the two </summary> /// /// <remarks> majeek, 12/16/2013. </remarks> /// /// <param name="other"> [in,out] The other. </param> /// /// <returns> The calculated distance. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// int SignalDescriptor::calculateDistance(SignalDescriptor& other){ int rowDifference = std::abs(fRow-other.fRow); int colDifference = std::abs(fCol-other.fCol); if (rowDifference > colDifference) return rowDifference; else return colDifference; } void SignalDescriptor::setCluster(int cluster){ fCluster = cluster; } int SignalDescriptor::getCluster(){ return fCluster; }
#include "engine/api/json_factory.hpp" #include "guidance/turn_instruction.hpp" #include <boost/test/test_case_template.hpp> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(json_factory) BOOST_AUTO_TEST_CASE(instructionTypeToString_test_size) { using namespace osrm::engine::api::json::detail; using namespace osrm::guidance; BOOST_CHECK_EQUAL(instructionTypeToString(TurnType::Sliproad), "invalid"); } BOOST_AUTO_TEST_SUITE_END()
// Copyright (c) 2017 Sony Corporation. 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 NBLA_FUNCTION_FLOOR_HPP #define NBLA_FUNCTION_FLOOR_HPP #include <nbla/function/utils/base_transform_unary.hpp> #include <cmath> namespace nbla { /** @class Floor @brief Flooring value, defined as @f[ y_i = floor(x_i), @f] Inputs: - N-D array. Outputs: - N-D array. @tparam T Data type for computation. \ingroup FunctionImplGrp */ NBLA_DEFINE_TRANSFORM_UNARY(Floor, std::floor(x), dy, false); } #endif
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkConvolutionImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" int itkConvolutionImageFilterDeltaFunctionTest(int argc, char * argv[]) { if ( argc < 3 ) { std::cout << "Usage: " << argv[0] << " kernelImage outputImage" << std::endl; return EXIT_FAILURE; } constexpr unsigned int ImageDimension = 2; using PixelType = unsigned char; using ImageType = itk::Image< PixelType, ImageDimension >; using ReaderType = itk::ImageFileReader< ImageType >; // Read kernel image. ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); reader->Update(); // Set up delta function image. ImageType::RegionType region = reader->GetOutput()->GetLargestPossibleRegion(); ImageType::Pointer deltaFunctionImage = ImageType::New(); deltaFunctionImage->SetRegions( region ); deltaFunctionImage->Allocate(true); // initialize // buffer // to zero // Set the middle pixel (rounded up) to 1. ImageType::IndexType middleIndex; for ( unsigned int i = 0; i < ImageDimension; ++i ) { ImageType::SizeValueType sizeInDimension = region.GetSize()[i]; middleIndex[i] = itk::Math::Floor< ImageType::IndexValueType >( 0.5 * sizeInDimension ); } deltaFunctionImage->SetPixel( middleIndex, 1 ); using ConvolutionFilterType = itk::ConvolutionImageFilter<ImageType>; ConvolutionFilterType::Pointer convolver = ConvolutionFilterType::New(); convolver->SetInput( deltaFunctionImage ); convolver->SetKernelImage( reader->GetOutput() ); using WriterType = itk::ImageFileWriter<ImageType>; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput( convolver->GetOutput() ); try { writer->Update(); } catch ( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
//===-- AArch64ISelLowering.cpp - AArch64 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 implements the AArch64TargetLowering class. // //===----------------------------------------------------------------------===// #include "AArch64ExpandImm.h" #include "AArch64ISelLowering.h" #include "AArch64CallingConvention.h" #include "AArch64MachineFunctionInfo.h" #include "AArch64PerfectShuffle.h" #include "AArch64RegisterInfo.h" #include "AArch64Subtarget.h" #include "MCTargetDesc/AArch64AddressingModes.h" #include "Utils/AArch64BaseInfo.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/Twine.h" #include "llvm/Analysis/VectorUtils.h" #include "llvm/CodeGen/CallingConvLower.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineMemOperand.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/RuntimeLibcalls.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/SelectionDAGNodes.h" #include "llvm/CodeGen/TargetCallingConv.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GetElementPtrTypeIterator.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Module.h" #include "llvm/IR/OperandTraits.h" #include "llvm/IR/PatternMatch.h" #include "llvm/IR/Type.h" #include "llvm/IR/Use.h" #include "llvm/IR/Value.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/KnownBits.h" #include "llvm/Support/MachineValueType.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <cstdint> #include <cstdlib> #include <iterator> #include <limits> #include <tuple> #include <utility> #include <vector> using namespace llvm; using namespace llvm::PatternMatch; #define DEBUG_TYPE "aarch64-lower" STATISTIC(NumTailCalls, "Number of tail calls"); STATISTIC(NumShiftInserts, "Number of vector shift inserts"); STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); static cl::opt<bool> EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, cl::desc("Allow AArch64 SLI/SRI formation"), cl::init(false)); // FIXME: The necessary dtprel relocations don't seem to be supported // well in the GNU bfd and gold linkers at the moment. Therefore, by // default, for now, fall back to GeneralDynamic code generation. cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( "aarch64-elf-ldtls-generation", cl::Hidden, cl::desc("Allow AArch64 Local Dynamic TLS code generation"), cl::init(false)); static cl::opt<bool> EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, cl::desc("Enable AArch64 logical imm instruction " "optimization"), cl::init(true)); /// Value type used for condition codes. static const MVT MVT_CC = MVT::i32; AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, const AArch64Subtarget &STI) : TargetLowering(TM), Subtarget(&STI) { // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so // we have to make something up. Arbitrarily, choose ZeroOrOne. setBooleanContents(ZeroOrOneBooleanContent); // When comparing vectors the result sets the different elements in the // vector to all-one or all-zero. setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); // Set up the register classes. addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); if (Subtarget->hasFPARMv8()) { addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); } if (Subtarget->hasNEON()) { addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); // Someone set us up the NEON. addDRTypeForNEON(MVT::v2f32); addDRTypeForNEON(MVT::v8i8); addDRTypeForNEON(MVT::v4i16); addDRTypeForNEON(MVT::v2i32); addDRTypeForNEON(MVT::v1i64); addDRTypeForNEON(MVT::v1f64); addDRTypeForNEON(MVT::v4f16); addQRTypeForNEON(MVT::v4f32); addQRTypeForNEON(MVT::v2f64); addQRTypeForNEON(MVT::v16i8); addQRTypeForNEON(MVT::v8i16); addQRTypeForNEON(MVT::v4i32); addQRTypeForNEON(MVT::v2i64); addQRTypeForNEON(MVT::v8f16); } // Compute derived properties from the register classes computeRegisterProperties(Subtarget->getRegisterInfo()); // Provide all sorts of operation actions setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); setOperationAction(ISD::SETCC, MVT::i32, Custom); setOperationAction(ISD::SETCC, MVT::i64, Custom); setOperationAction(ISD::SETCC, MVT::f16, Custom); setOperationAction(ISD::SETCC, MVT::f32, Custom); setOperationAction(ISD::SETCC, MVT::f64, Custom); setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); setOperationAction(ISD::BRCOND, MVT::Other, Expand); setOperationAction(ISD::BR_CC, MVT::i32, Custom); setOperationAction(ISD::BR_CC, MVT::i64, Custom); setOperationAction(ISD::BR_CC, MVT::f16, Custom); setOperationAction(ISD::BR_CC, MVT::f32, Custom); setOperationAction(ISD::BR_CC, MVT::f64, Custom); setOperationAction(ISD::SELECT, MVT::i32, Custom); setOperationAction(ISD::SELECT, MVT::i64, Custom); setOperationAction(ISD::SELECT, MVT::f16, Custom); setOperationAction(ISD::SELECT, MVT::f32, Custom); setOperationAction(ISD::SELECT, MVT::f64, Custom); setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); setOperationAction(ISD::BR_JT, MVT::Other, Custom); setOperationAction(ISD::JumpTable, MVT::i64, Custom); setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); setOperationAction(ISD::FREM, MVT::f32, Expand); setOperationAction(ISD::FREM, MVT::f64, Expand); setOperationAction(ISD::FREM, MVT::f80, Expand); setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); // Custom lowering hooks are needed for XOR // to fold it into CSINC/CSINV. setOperationAction(ISD::XOR, MVT::i32, Custom); setOperationAction(ISD::XOR, MVT::i64, Custom); // Virtually no operation on f128 is legal, but LLVM can't expand them when // there's a valid register class, so we need custom operations in most cases. setOperationAction(ISD::FABS, MVT::f128, Expand); setOperationAction(ISD::FADD, MVT::f128, Custom); setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); setOperationAction(ISD::FCOS, MVT::f128, Expand); setOperationAction(ISD::FDIV, MVT::f128, Custom); setOperationAction(ISD::FMA, MVT::f128, Expand); setOperationAction(ISD::FMUL, MVT::f128, Custom); setOperationAction(ISD::FNEG, MVT::f128, Expand); setOperationAction(ISD::FPOW, MVT::f128, Expand); setOperationAction(ISD::FREM, MVT::f128, Expand); setOperationAction(ISD::FRINT, MVT::f128, Expand); setOperationAction(ISD::FSIN, MVT::f128, Expand); setOperationAction(ISD::FSINCOS, MVT::f128, Expand); setOperationAction(ISD::FSQRT, MVT::f128, Expand); setOperationAction(ISD::FSUB, MVT::f128, Custom); setOperationAction(ISD::FTRUNC, MVT::f128, Expand); setOperationAction(ISD::SETCC, MVT::f128, Custom); setOperationAction(ISD::BR_CC, MVT::f128, Custom); setOperationAction(ISD::SELECT, MVT::f128, Custom); setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); // Lowering for many of the conversions is actually specified by the non-f128 // type. The LowerXXX function will be trivial when f128 isn't involved. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); // Variable arguments. setOperationAction(ISD::VASTART, MVT::Other, Custom); setOperationAction(ISD::VAARG, MVT::Other, Custom); setOperationAction(ISD::VACOPY, MVT::Other, Custom); setOperationAction(ISD::VAEND, MVT::Other, Expand); // Variable-sized objects. setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); if (Subtarget->isTargetWindows()) setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); else setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); // Constant pool entries setOperationAction(ISD::ConstantPool, MVT::i64, Custom); // BlockAddress setOperationAction(ISD::BlockAddress, MVT::i64, Custom); // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. setOperationAction(ISD::ADDC, MVT::i32, Custom); setOperationAction(ISD::ADDE, MVT::i32, Custom); setOperationAction(ISD::SUBC, MVT::i32, Custom); setOperationAction(ISD::SUBE, MVT::i32, Custom); setOperationAction(ISD::ADDC, MVT::i64, Custom); setOperationAction(ISD::ADDE, MVT::i64, Custom); setOperationAction(ISD::SUBC, MVT::i64, Custom); setOperationAction(ISD::SUBE, MVT::i64, Custom); // AArch64 lacks both left-rotate and popcount instructions. setOperationAction(ISD::ROTL, MVT::i32, Expand); setOperationAction(ISD::ROTL, MVT::i64, Expand); for (MVT VT : MVT::vector_valuetypes()) { setOperationAction(ISD::ROTL, VT, Expand); setOperationAction(ISD::ROTR, VT, Expand); } // AArch64 doesn't have {U|S}MUL_LOHI. setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); setOperationAction(ISD::CTPOP, MVT::i32, Custom); setOperationAction(ISD::CTPOP, MVT::i64, Custom); setOperationAction(ISD::SDIVREM, MVT::i32, Expand); setOperationAction(ISD::SDIVREM, MVT::i64, Expand); for (MVT VT : MVT::vector_valuetypes()) { setOperationAction(ISD::SDIVREM, VT, Expand); setOperationAction(ISD::UDIVREM, VT, Expand); } setOperationAction(ISD::SREM, MVT::i32, Expand); setOperationAction(ISD::SREM, MVT::i64, Expand); setOperationAction(ISD::UDIVREM, MVT::i32, Expand); setOperationAction(ISD::UDIVREM, MVT::i64, Expand); setOperationAction(ISD::UREM, MVT::i32, Expand); setOperationAction(ISD::UREM, MVT::i64, Expand); // Custom lower Add/Sub/Mul with overflow. setOperationAction(ISD::SADDO, MVT::i32, Custom); setOperationAction(ISD::SADDO, MVT::i64, Custom); setOperationAction(ISD::UADDO, MVT::i32, Custom); setOperationAction(ISD::UADDO, MVT::i64, Custom); setOperationAction(ISD::SSUBO, MVT::i32, Custom); setOperationAction(ISD::SSUBO, MVT::i64, Custom); setOperationAction(ISD::USUBO, MVT::i32, Custom); setOperationAction(ISD::USUBO, MVT::i64, Custom); setOperationAction(ISD::SMULO, MVT::i32, Custom); setOperationAction(ISD::SMULO, MVT::i64, Custom); setOperationAction(ISD::UMULO, MVT::i32, Custom); setOperationAction(ISD::UMULO, MVT::i64, Custom); setOperationAction(ISD::FSIN, MVT::f32, Expand); setOperationAction(ISD::FSIN, MVT::f64, Expand); setOperationAction(ISD::FCOS, MVT::f32, Expand); setOperationAction(ISD::FCOS, MVT::f64, Expand); setOperationAction(ISD::FPOW, MVT::f32, Expand); setOperationAction(ISD::FPOW, MVT::f64, Expand); setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); if (Subtarget->hasFullFP16()) setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); else setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); setOperationAction(ISD::FREM, MVT::f16, Promote); setOperationAction(ISD::FREM, MVT::v4f16, Expand); setOperationAction(ISD::FREM, MVT::v8f16, Expand); setOperationAction(ISD::FPOW, MVT::f16, Promote); setOperationAction(ISD::FPOW, MVT::v4f16, Expand); setOperationAction(ISD::FPOW, MVT::v8f16, Expand); setOperationAction(ISD::FPOWI, MVT::f16, Promote); setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); setOperationAction(ISD::FCOS, MVT::f16, Promote); setOperationAction(ISD::FCOS, MVT::v4f16, Expand); setOperationAction(ISD::FCOS, MVT::v8f16, Expand); setOperationAction(ISD::FSIN, MVT::f16, Promote); setOperationAction(ISD::FSIN, MVT::v4f16, Expand); setOperationAction(ISD::FSIN, MVT::v8f16, Expand); setOperationAction(ISD::FSINCOS, MVT::f16, Promote); setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); setOperationAction(ISD::FEXP, MVT::f16, Promote); setOperationAction(ISD::FEXP, MVT::v4f16, Expand); setOperationAction(ISD::FEXP, MVT::v8f16, Expand); setOperationAction(ISD::FEXP2, MVT::f16, Promote); setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); setOperationAction(ISD::FLOG, MVT::f16, Promote); setOperationAction(ISD::FLOG, MVT::v4f16, Expand); setOperationAction(ISD::FLOG, MVT::v8f16, Expand); setOperationAction(ISD::FLOG2, MVT::f16, Promote); setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); setOperationAction(ISD::FLOG10, MVT::f16, Promote); setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); if (!Subtarget->hasFullFP16()) { setOperationAction(ISD::SELECT, MVT::f16, Promote); setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); setOperationAction(ISD::SETCC, MVT::f16, Promote); setOperationAction(ISD::BR_CC, MVT::f16, Promote); setOperationAction(ISD::FADD, MVT::f16, Promote); setOperationAction(ISD::FSUB, MVT::f16, Promote); setOperationAction(ISD::FMUL, MVT::f16, Promote); setOperationAction(ISD::FDIV, MVT::f16, Promote); setOperationAction(ISD::FMA, MVT::f16, Promote); setOperationAction(ISD::FNEG, MVT::f16, Promote); setOperationAction(ISD::FABS, MVT::f16, Promote); setOperationAction(ISD::FCEIL, MVT::f16, Promote); setOperationAction(ISD::FSQRT, MVT::f16, Promote); setOperationAction(ISD::FFLOOR, MVT::f16, Promote); setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); setOperationAction(ISD::FRINT, MVT::f16, Promote); setOperationAction(ISD::FROUND, MVT::f16, Promote); setOperationAction(ISD::FTRUNC, MVT::f16, Promote); setOperationAction(ISD::FMINNUM, MVT::f16, Promote); setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); // promote v4f16 to v4f32 when that is known to be safe. setOperationAction(ISD::FADD, MVT::v4f16, Promote); setOperationAction(ISD::FSUB, MVT::v4f16, Promote); setOperationAction(ISD::FMUL, MVT::v4f16, Promote); setOperationAction(ISD::FDIV, MVT::v4f16, Promote); setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); setOperationAction(ISD::FABS, MVT::v4f16, Expand); setOperationAction(ISD::FNEG, MVT::v4f16, Expand); setOperationAction(ISD::FROUND, MVT::v4f16, Expand); setOperationAction(ISD::FMA, MVT::v4f16, Expand); setOperationAction(ISD::SETCC, MVT::v4f16, Expand); setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); setOperationAction(ISD::SELECT, MVT::v4f16, Expand); setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); setOperationAction(ISD::FRINT, MVT::v4f16, Expand); setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); setOperationAction(ISD::FABS, MVT::v8f16, Expand); setOperationAction(ISD::FADD, MVT::v8f16, Expand); setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); setOperationAction(ISD::FDIV, MVT::v8f16, Expand); setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); setOperationAction(ISD::FMA, MVT::v8f16, Expand); setOperationAction(ISD::FMUL, MVT::v8f16, Expand); setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); setOperationAction(ISD::FNEG, MVT::v8f16, Expand); setOperationAction(ISD::FROUND, MVT::v8f16, Expand); setOperationAction(ISD::FRINT, MVT::v8f16, Expand); setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); setOperationAction(ISD::FSUB, MVT::v8f16, Expand); setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); setOperationAction(ISD::SETCC, MVT::v8f16, Expand); setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); setOperationAction(ISD::SELECT, MVT::v8f16, Expand); setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); } // AArch64 has implementations of a lot of rounding-like FP operations. for (MVT Ty : {MVT::f32, MVT::f64}) { setOperationAction(ISD::FFLOOR, Ty, Legal); setOperationAction(ISD::FNEARBYINT, Ty, Legal); setOperationAction(ISD::FCEIL, Ty, Legal); setOperationAction(ISD::FRINT, Ty, Legal); setOperationAction(ISD::FTRUNC, Ty, Legal); setOperationAction(ISD::FROUND, Ty, Legal); setOperationAction(ISD::FMINNUM, Ty, Legal); setOperationAction(ISD::FMAXNUM, Ty, Legal); setOperationAction(ISD::FMINIMUM, Ty, Legal); setOperationAction(ISD::FMAXIMUM, Ty, Legal); } if (Subtarget->hasFullFP16()) { setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); setOperationAction(ISD::FFLOOR, MVT::f16, Legal); setOperationAction(ISD::FCEIL, MVT::f16, Legal); setOperationAction(ISD::FRINT, MVT::f16, Legal); setOperationAction(ISD::FTRUNC, MVT::f16, Legal); setOperationAction(ISD::FROUND, MVT::f16, Legal); setOperationAction(ISD::FMINNUM, MVT::f16, Legal); setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); } setOperationAction(ISD::PREFETCH, MVT::Other, Custom); setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. // This requires the Performance Monitors extension. if (Subtarget->hasPerfMon()) setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { // Issue __sincos_stret if available. setOperationAction(ISD::FSINCOS, MVT::f64, Custom); setOperationAction(ISD::FSINCOS, MVT::f32, Custom); } else { setOperationAction(ISD::FSINCOS, MVT::f64, Expand); setOperationAction(ISD::FSINCOS, MVT::f32, Expand); } // Make floating-point constants legal for the large code model, so they don't // become loads from the constant pool. if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { setOperationAction(ISD::ConstantFP, MVT::f32, Legal); setOperationAction(ISD::ConstantFP, MVT::f64, Legal); } // AArch64 does not have floating-point extending loads, i1 sign-extending // load, floating-point truncating stores, or v2i32->v2i16 truncating store. for (MVT VT : MVT::fp_valuetypes()) { setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); } for (MVT VT : MVT::integer_valuetypes()) setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); setTruncStoreAction(MVT::f32, MVT::f16, Expand); setTruncStoreAction(MVT::f64, MVT::f32, Expand); setTruncStoreAction(MVT::f64, MVT::f16, Expand); setTruncStoreAction(MVT::f128, MVT::f80, Expand); setTruncStoreAction(MVT::f128, MVT::f64, Expand); setTruncStoreAction(MVT::f128, MVT::f32, Expand); setTruncStoreAction(MVT::f128, MVT::f16, Expand); setOperationAction(ISD::BITCAST, MVT::i16, Custom); setOperationAction(ISD::BITCAST, MVT::f16, Custom); // Indexed loads and stores are supported. for (unsigned im = (unsigned)ISD::PRE_INC; im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { setIndexedLoadAction(im, MVT::i8, Legal); setIndexedLoadAction(im, MVT::i16, Legal); setIndexedLoadAction(im, MVT::i32, Legal); setIndexedLoadAction(im, MVT::i64, Legal); setIndexedLoadAction(im, MVT::f64, Legal); setIndexedLoadAction(im, MVT::f32, Legal); setIndexedLoadAction(im, MVT::f16, Legal); setIndexedStoreAction(im, MVT::i8, Legal); setIndexedStoreAction(im, MVT::i16, Legal); setIndexedStoreAction(im, MVT::i32, Legal); setIndexedStoreAction(im, MVT::i64, Legal); setIndexedStoreAction(im, MVT::f64, Legal); setIndexedStoreAction(im, MVT::f32, Legal); setIndexedStoreAction(im, MVT::f16, Legal); } // Trap. setOperationAction(ISD::TRAP, MVT::Other, Legal); // We combine OR nodes for bitfield operations. setTargetDAGCombine(ISD::OR); // Try to create BICs for vector ANDs. setTargetDAGCombine(ISD::AND); // Vector add and sub nodes may conceal a high-half opportunity. // Also, try to fold ADD into CSINC/CSINV.. setTargetDAGCombine(ISD::ADD); setTargetDAGCombine(ISD::SUB); setTargetDAGCombine(ISD::SRL); setTargetDAGCombine(ISD::XOR); setTargetDAGCombine(ISD::SINT_TO_FP); setTargetDAGCombine(ISD::UINT_TO_FP); setTargetDAGCombine(ISD::FP_TO_SINT); setTargetDAGCombine(ISD::FP_TO_UINT); setTargetDAGCombine(ISD::FDIV); setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); setTargetDAGCombine(ISD::ANY_EXTEND); setTargetDAGCombine(ISD::ZERO_EXTEND); setTargetDAGCombine(ISD::SIGN_EXTEND); setTargetDAGCombine(ISD::BITCAST); setTargetDAGCombine(ISD::CONCAT_VECTORS); setTargetDAGCombine(ISD::STORE); if (Subtarget->supportsAddressTopByteIgnored()) setTargetDAGCombine(ISD::LOAD); setTargetDAGCombine(ISD::MUL); setTargetDAGCombine(ISD::SELECT); setTargetDAGCombine(ISD::VSELECT); setTargetDAGCombine(ISD::INTRINSIC_VOID); setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); setTargetDAGCombine(ISD::GlobalAddress); // In case of strict alignment, avoid an excessive number of byte wide stores. MaxStoresPerMemsetOptSize = 8; MaxStoresPerMemset = Subtarget->requiresStrictAlign() ? MaxStoresPerMemsetOptSize : 32; MaxGluedStoresPerMemcpy = 4; MaxStoresPerMemcpyOptSize = 4; MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() ? MaxStoresPerMemcpyOptSize : 16; MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; setStackPointerRegisterToSaveRestore(AArch64::SP); setSchedulingPreference(Sched::Hybrid); EnableExtLdPromotion = true; // Set required alignment. setMinFunctionAlignment(2); // Set preferred alignments. setPrefFunctionAlignment(STI.getPrefFunctionAlignment()); setPrefLoopAlignment(STI.getPrefLoopAlignment()); // Only change the limit for entries in a jump table if specified by // the sub target, but not at the command line. unsigned MaxJT = STI.getMaximumJumpTableSize(); if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) setMaximumJumpTableSize(MaxJT); setHasExtractBitsInsn(true); setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); if (Subtarget->hasNEON()) { // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to // silliness like this: setOperationAction(ISD::FABS, MVT::v1f64, Expand); setOperationAction(ISD::FADD, MVT::v1f64, Expand); setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); setOperationAction(ISD::FCOS, MVT::v1f64, Expand); setOperationAction(ISD::FDIV, MVT::v1f64, Expand); setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); setOperationAction(ISD::FMA, MVT::v1f64, Expand); setOperationAction(ISD::FMUL, MVT::v1f64, Expand); setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); setOperationAction(ISD::FNEG, MVT::v1f64, Expand); setOperationAction(ISD::FPOW, MVT::v1f64, Expand); setOperationAction(ISD::FREM, MVT::v1f64, Expand); setOperationAction(ISD::FROUND, MVT::v1f64, Expand); setOperationAction(ISD::FRINT, MVT::v1f64, Expand); setOperationAction(ISD::FSIN, MVT::v1f64, Expand); setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); setOperationAction(ISD::FSUB, MVT::v1f64, Expand); setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); setOperationAction(ISD::SETCC, MVT::v1f64, Expand); setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); setOperationAction(ISD::SELECT, MVT::v1f64, Expand); setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); setOperationAction(ISD::MUL, MVT::v1i64, Expand); // AArch64 doesn't have a direct vector ->f32 conversion instructions for // elements smaller than i32, so promote the input to i32 first. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); // i8 vector elements also need promotion to i32 for v8i8 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); // Similarly, there is no direct i32 -> f64 vector conversion instruction. setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); // Or, direct i32 -> f16 vector conversion. Set it so custom, so the // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); if (Subtarget->hasFullFP16()) { setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); } else { // when AArch64 doesn't have fullfp16 support, promote the input // to i32 first. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); } setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); // AArch64 doesn't have MUL.2d: setOperationAction(ISD::MUL, MVT::v2i64, Expand); // Custom handling for some quad-vector types to detect MULL. setOperationAction(ISD::MUL, MVT::v8i16, Custom); setOperationAction(ISD::MUL, MVT::v4i32, Custom); setOperationAction(ISD::MUL, MVT::v2i64, Custom); // Vector reductions for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); } for (MVT VT : { MVT::v4f16, MVT::v2f32, MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); } setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); // Likewise, narrowing and extending vector loads/stores aren't handled // directly. for (MVT VT : MVT::vector_valuetypes()) { setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { setOperationAction(ISD::MULHS, VT, Legal); setOperationAction(ISD::MULHU, VT, Legal); } else { setOperationAction(ISD::MULHS, VT, Expand); setOperationAction(ISD::MULHU, VT, Expand); } setOperationAction(ISD::SMUL_LOHI, VT, Expand); setOperationAction(ISD::UMUL_LOHI, VT, Expand); setOperationAction(ISD::BSWAP, VT, Expand); setOperationAction(ISD::CTTZ, VT, Expand); for (MVT InnerVT : MVT::vector_valuetypes()) { setTruncStoreAction(VT, InnerVT, Expand); setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); } } // AArch64 has implementations of a lot of rounding-like FP operations. for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { setOperationAction(ISD::FFLOOR, Ty, Legal); setOperationAction(ISD::FNEARBYINT, Ty, Legal); setOperationAction(ISD::FCEIL, Ty, Legal); setOperationAction(ISD::FRINT, Ty, Legal); setOperationAction(ISD::FTRUNC, Ty, Legal); setOperationAction(ISD::FROUND, Ty, Legal); } if (Subtarget->hasFullFP16()) { for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { setOperationAction(ISD::FFLOOR, Ty, Legal); setOperationAction(ISD::FNEARBYINT, Ty, Legal); setOperationAction(ISD::FCEIL, Ty, Legal); setOperationAction(ISD::FRINT, Ty, Legal); setOperationAction(ISD::FTRUNC, Ty, Legal); setOperationAction(ISD::FROUND, Ty, Legal); } } setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); } PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); } void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { assert(VT.isVector() && "VT should be a vector type"); if (VT.isFloatingPoint()) { MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); setOperationPromotedToType(ISD::STORE, VT, PromoteTo); } // Mark vector float intrinsics as expand. if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { setOperationAction(ISD::FSIN, VT, Expand); setOperationAction(ISD::FCOS, VT, Expand); setOperationAction(ISD::FPOW, VT, Expand); setOperationAction(ISD::FLOG, VT, Expand); setOperationAction(ISD::FLOG2, VT, Expand); setOperationAction(ISD::FLOG10, VT, Expand); setOperationAction(ISD::FEXP, VT, Expand); setOperationAction(ISD::FEXP2, VT, Expand); // But we do support custom-lowering for FCOPYSIGN. setOperationAction(ISD::FCOPYSIGN, VT, Custom); } setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); setOperationAction(ISD::BUILD_VECTOR, VT, Custom); setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); setOperationAction(ISD::SRA, VT, Custom); setOperationAction(ISD::SRL, VT, Custom); setOperationAction(ISD::SHL, VT, Custom); setOperationAction(ISD::OR, VT, Custom); setOperationAction(ISD::SETCC, VT, Custom); setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); setOperationAction(ISD::SELECT, VT, Expand); setOperationAction(ISD::SELECT_CC, VT, Expand); setOperationAction(ISD::VSELECT, VT, Expand); for (MVT InnerVT : MVT::all_valuetypes()) setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); // CNT supports only B element sizes, then use UADDLP to widen. if (VT != MVT::v8i8 && VT != MVT::v16i8) setOperationAction(ISD::CTPOP, VT, Custom); setOperationAction(ISD::UDIV, VT, Expand); setOperationAction(ISD::SDIV, VT, Expand); setOperationAction(ISD::UREM, VT, Expand); setOperationAction(ISD::SREM, VT, Expand); setOperationAction(ISD::FREM, VT, Expand); setOperationAction(ISD::FP_TO_SINT, VT, Custom); setOperationAction(ISD::FP_TO_UINT, VT, Custom); if (!VT.isFloatingPoint()) setOperationAction(ISD::ABS, VT, Legal); // [SU][MIN|MAX] are available for all NEON types apart from i64. if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) setOperationAction(Opcode, VT, Legal); // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. if (VT.isFloatingPoint() && (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) for (unsigned Opcode : {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) setOperationAction(Opcode, VT, Legal); if (Subtarget->isLittleEndian()) { for (unsigned im = (unsigned)ISD::PRE_INC; im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { setIndexedLoadAction(im, VT, Legal); setIndexedStoreAction(im, VT, Legal); } } } void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { addRegisterClass(VT, &AArch64::FPR64RegClass); addTypeForNEON(VT, MVT::v2i32); } void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { addRegisterClass(VT, &AArch64::FPR128RegClass); addTypeForNEON(VT, MVT::v4i32); } EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, EVT VT) const { if (!VT.isVector()) return MVT::i32; return VT.changeVectorElementTypeToInteger(); } static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, const APInt &Demanded, TargetLowering::TargetLoweringOpt &TLO, unsigned NewOpc) { uint64_t OldImm = Imm, NewImm, Enc; uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; // Return if the immediate is already all zeros, all ones, a bimm32 or a // bimm64. if (Imm == 0 || Imm == Mask || AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) return false; unsigned EltSize = Size; uint64_t DemandedBits = Demanded.getZExtValue(); // Clear bits that are not demanded. Imm &= DemandedBits; while (true) { // The goal here is to set the non-demanded bits in a way that minimizes // the number of switching between 0 and 1. In order to achieve this goal, // we set the non-demanded bits to the value of the preceding demanded bits. // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a // non-demanded bit), we copy bit0 (1) to the least significant 'x', // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. // The final result is 0b11000011. uint64_t NonDemandedBits = ~DemandedBits; uint64_t InvertedImm = ~Imm & DemandedBits; uint64_t RotatedImm = ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & NonDemandedBits; uint64_t Sum = RotatedImm + NonDemandedBits; bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); uint64_t Ones = (Sum + Carry) & NonDemandedBits; NewImm = (Imm | Ones) & Mask; // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate // or all-ones or all-zeros, in which case we can stop searching. Otherwise, // we halve the element size and continue the search. if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) break; // We cannot shrink the element size any further if it is 2-bits. if (EltSize == 2) return false; EltSize /= 2; Mask >>= EltSize; uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; // Return if there is mismatch in any of the demanded bits of Imm and Hi. if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) return false; // Merge the upper and lower halves of Imm and DemandedBits. Imm |= Hi; DemandedBits |= DemandedBitsHi; } ++NumOptimizedImms; // Replicate the element across the register width. while (EltSize < Size) { NewImm |= NewImm << EltSize; EltSize *= 2; } (void)OldImm; assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && "demanded bits should never be altered"); assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); // Create the new constant immediate node. EVT VT = Op.getValueType(); SDLoc DL(Op); SDValue New; // If the new constant immediate is all-zeros or all-ones, let the target // independent DAG combine optimize this node. if (NewImm == 0 || NewImm == OrigMask) { New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), TLO.DAG.getConstant(NewImm, DL, VT)); // Otherwise, create a machine node so that target independent DAG combine // doesn't undo this optimization. } else { Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); New = SDValue( TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); } return TLO.CombineTo(Op, New); } bool AArch64TargetLowering::targetShrinkDemandedConstant( SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const { // Delay this optimization to as late as possible. if (!TLO.LegalOps) return false; if (!EnableOptimizeLogicalImm) return false; EVT VT = Op.getValueType(); if (VT.isVector()) return false; unsigned Size = VT.getSizeInBits(); assert((Size == 32 || Size == 64) && "i32 or i64 is expected after legalization."); // Exit early if we demand all bits. if (Demanded.countPopulation() == Size) return false; unsigned NewOpc; switch (Op.getOpcode()) { default: return false; case ISD::AND: NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; break; case ISD::OR: NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; break; case ISD::XOR: NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; break; } ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); if (!C) return false; uint64_t Imm = C->getZExtValue(); return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc); } /// computeKnownBitsForTargetNode - Determine which of the bits specified in /// Mask are known to be either zero or one and return them Known. void AArch64TargetLowering::computeKnownBitsForTargetNode( const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { switch (Op.getOpcode()) { default: break; case AArch64ISD::CSEL: { KnownBits Known2; Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); Known.Zero &= Known2.Zero; Known.One &= Known2.One; break; } case ISD::INTRINSIC_W_CHAIN: { ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); switch (IntID) { default: return; case Intrinsic::aarch64_ldaxr: case Intrinsic::aarch64_ldxr: { unsigned BitWidth = Known.getBitWidth(); EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); unsigned MemBits = VT.getScalarSizeInBits(); Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); return; } } break; } case ISD::INTRINSIC_WO_CHAIN: case ISD::INTRINSIC_VOID: { unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); switch (IntNo) { default: break; case Intrinsic::aarch64_neon_umaxv: case Intrinsic::aarch64_neon_uminv: { // Figure out the datatype of the vector operand. The UMINV instruction // will zero extend the result, so we can mark as known zero all the // bits larger than the element datatype. 32-bit or larget doesn't need // this as those are legal types and will be handled by isel directly. MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); unsigned BitWidth = Known.getBitWidth(); if (VT == MVT::v8i8 || VT == MVT::v16i8) { assert(BitWidth >= 8 && "Unexpected width!"); APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); Known.Zero |= Mask; } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { assert(BitWidth >= 16 && "Unexpected width!"); APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); Known.Zero |= Mask; } break; } break; } } } } MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, EVT) const { return MVT::i64; } bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace, unsigned Align, bool *Fast) const { if (Subtarget->requiresStrictAlign()) return false; if (Fast) { // Some CPUs are fine with unaligned stores except for 128-bit ones. *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || // See comments in performSTORECombine() for more details about // these conditions. // Code that uses clang vector extensions can mark that it // wants unaligned accesses to be treated as fast by // underspecifying alignment to be 1 or 2. Align <= 2 || // Disregard v2i64. Memcpy lowering produces those and splitting // them regresses performance on micro-benchmarks and olden/bh. VT == MVT::v2i64; } return true; } FastISel * AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo) const { return AArch64::createFastISel(funcInfo, libInfo); } const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { switch ((AArch64ISD::NodeType)Opcode) { case AArch64ISD::FIRST_NUMBER: break; case AArch64ISD::CALL: return "AArch64ISD::CALL"; case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; case AArch64ISD::ADR: return "AArch64ISD::ADR"; case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; case AArch64ISD::ADC: return "AArch64ISD::ADC"; case AArch64ISD::SBC: return "AArch64ISD::SBC"; case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; case AArch64ISD::DUP: return "AArch64ISD::DUP"; case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; case AArch64ISD::BICi: return "AArch64ISD::BICi"; case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; case AArch64ISD::BSL: return "AArch64ISD::BSL"; case AArch64ISD::NEG: return "AArch64ISD::NEG"; case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; case AArch64ISD::REV16: return "AArch64ISD::REV16"; case AArch64ISD::REV32: return "AArch64ISD::REV32"; case AArch64ISD::REV64: return "AArch64ISD::REV64"; case AArch64ISD::EXT: return "AArch64ISD::EXT"; case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; case AArch64ISD::NOT: return "AArch64ISD::NOT"; case AArch64ISD::BIT: return "AArch64ISD::BIT"; case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; } return nullptr; } MachineBasicBlock * AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, MachineBasicBlock *MBB) const { // We materialise the F128CSEL pseudo-instruction as some control flow and a // phi node: // OrigBB: // [... previous instrs leading to comparison ...] // b.ne TrueBB // b EndBB // TrueBB: // ; Fallthrough // EndBB: // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] MachineFunction *MF = MBB->getParent(); const TargetInstrInfo *TII = Subtarget->getInstrInfo(); const BasicBlock *LLVM_BB = MBB->getBasicBlock(); DebugLoc DL = MI.getDebugLoc(); MachineFunction::iterator It = ++MBB->getIterator(); unsigned DestReg = MI.getOperand(0).getReg(); unsigned IfTrueReg = MI.getOperand(1).getReg(); unsigned IfFalseReg = MI.getOperand(2).getReg(); unsigned CondCode = MI.getOperand(3).getImm(); bool NZCVKilled = MI.getOperand(4).isKill(); MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); MF->insert(It, TrueBB); MF->insert(It, EndBB); // Transfer rest of current basic-block to EndBB EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), MBB->end()); EndBB->transferSuccessorsAndUpdatePHIs(MBB); BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); MBB->addSuccessor(TrueBB); MBB->addSuccessor(EndBB); // TrueBB falls through to the end. TrueBB->addSuccessor(EndBB); if (!NZCVKilled) { TrueBB->addLiveIn(AArch64::NZCV); EndBB->addLiveIn(AArch64::NZCV); } BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) .addReg(IfTrueReg) .addMBB(TrueBB) .addReg(IfFalseReg) .addMBB(MBB); MI.eraseFromParent(); return EndBB; } MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( MachineInstr &MI, MachineBasicBlock *BB) const { assert(!isAsynchronousEHPersonality(classifyEHPersonality( BB->getParent()->getFunction().getPersonalityFn())) && "SEH does not use catchret!"); return BB; } MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad( MachineInstr &MI, MachineBasicBlock *BB) const { MI.eraseFromParent(); return BB; } MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( MachineInstr &MI, MachineBasicBlock *BB) const { switch (MI.getOpcode()) { default: #ifndef NDEBUG MI.dump(); #endif llvm_unreachable("Unexpected instruction for custom inserter!"); case AArch64::F128CSEL: return EmitF128CSEL(MI, BB); case TargetOpcode::STACKMAP: case TargetOpcode::PATCHPOINT: return emitPatchPoint(MI, BB); case AArch64::CATCHRET: return EmitLoweredCatchRet(MI, BB); case AArch64::CATCHPAD: return EmitLoweredCatchPad(MI, BB); } } //===----------------------------------------------------------------------===// // AArch64 Lowering private implementation. //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Lowering Code //===----------------------------------------------------------------------===// /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 /// CC static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { switch (CC) { default: llvm_unreachable("Unknown condition code!"); case ISD::SETNE: return AArch64CC::NE; case ISD::SETEQ: return AArch64CC::EQ; case ISD::SETGT: return AArch64CC::GT; case ISD::SETGE: return AArch64CC::GE; case ISD::SETLT: return AArch64CC::LT; case ISD::SETLE: return AArch64CC::LE; case ISD::SETUGT: return AArch64CC::HI; case ISD::SETUGE: return AArch64CC::HS; case ISD::SETULT: return AArch64CC::LO; case ISD::SETULE: return AArch64CC::LS; } } /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. static void changeFPCCToAArch64CC(ISD::CondCode CC, AArch64CC::CondCode &CondCode, AArch64CC::CondCode &CondCode2) { CondCode2 = AArch64CC::AL; switch (CC) { default: llvm_unreachable("Unknown FP condition!"); case ISD::SETEQ: case ISD::SETOEQ: CondCode = AArch64CC::EQ; break; case ISD::SETGT: case ISD::SETOGT: CondCode = AArch64CC::GT; break; case ISD::SETGE: case ISD::SETOGE: CondCode = AArch64CC::GE; break; case ISD::SETOLT: CondCode = AArch64CC::MI; break; case ISD::SETOLE: CondCode = AArch64CC::LS; break; case ISD::SETONE: CondCode = AArch64CC::MI; CondCode2 = AArch64CC::GT; break; case ISD::SETO: CondCode = AArch64CC::VC; break; case ISD::SETUO: CondCode = AArch64CC::VS; break; case ISD::SETUEQ: CondCode = AArch64CC::EQ; CondCode2 = AArch64CC::VS; break; case ISD::SETUGT: CondCode = AArch64CC::HI; break; case ISD::SETUGE: CondCode = AArch64CC::PL; break; case ISD::SETLT: case ISD::SETULT: CondCode = AArch64CC::LT; break; case ISD::SETLE: case ISD::SETULE: CondCode = AArch64CC::LE; break; case ISD::SETNE: case ISD::SETUNE: CondCode = AArch64CC::NE; break; } } /// Convert a DAG fp condition code to an AArch64 CC. /// This differs from changeFPCCToAArch64CC in that it returns cond codes that /// should be AND'ed instead of OR'ed. static void changeFPCCToANDAArch64CC(ISD::CondCode CC, AArch64CC::CondCode &CondCode, AArch64CC::CondCode &CondCode2) { CondCode2 = AArch64CC::AL; switch (CC) { default: changeFPCCToAArch64CC(CC, CondCode, CondCode2); assert(CondCode2 == AArch64CC::AL); break; case ISD::SETONE: // (a one b) // == ((a olt b) || (a ogt b)) // == ((a ord b) && (a une b)) CondCode = AArch64CC::VC; CondCode2 = AArch64CC::NE; break; case ISD::SETUEQ: // (a ueq b) // == ((a uno b) || (a oeq b)) // == ((a ule b) && (a uge b)) CondCode = AArch64CC::PL; CondCode2 = AArch64CC::LE; break; } } /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 /// CC usable with the vector instructions. Fewer operations are available /// without a real NZCV register, so we have to use less efficient combinations /// to get the same effect. static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, AArch64CC::CondCode &CondCode, AArch64CC::CondCode &CondCode2, bool &Invert) { Invert = false; switch (CC) { default: // Mostly the scalar mappings work fine. changeFPCCToAArch64CC(CC, CondCode, CondCode2); break; case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH; case ISD::SETO: CondCode = AArch64CC::MI; CondCode2 = AArch64CC::GE; break; case ISD::SETUEQ: case ISD::SETULT: case ISD::SETULE: case ISD::SETUGT: case ISD::SETUGE: // All of the compare-mask comparisons are ordered, but we can switch // between the two by a double inversion. E.g. ULE == !OGT. Invert = true; changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); break; } } static bool isLegalArithImmed(uint64_t C) { // Matches AArch64DAGToDAGISel::SelectArithImmed(). bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); LLVM_DEBUG(dbgs() << "Is imm " << C << " legal: " << (IsLegal ? "yes\n" : "no\n")); return IsLegal; } // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags // can be set differently by this operation. It comes down to whether // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then // everything is fine. If not then the optimization is wrong. Thus general // comparisons are only valid if op2 != 0. // // So, finally, the only LLVM-native comparisons that don't mention C and V // are SETEQ and SETNE. They're the only ones we can safely use CMN for in // the absence of information about op2. static bool isCMN(SDValue Op, ISD::CondCode CC) { return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && (CC == ISD::SETEQ || CC == ISD::SETNE); } static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, const SDLoc &dl, SelectionDAG &DAG) { EVT VT = LHS.getValueType(); const bool FullFP16 = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); if (VT.isFloatingPoint()) { assert(VT != MVT::f128); if (VT == MVT::f16 && !FullFP16) { LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); VT = MVT::f32; } return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); } // The CMP instruction is just an alias for SUBS, and representing it as // SUBS means that it's possible to get CSE with subtract operations. // A later phase can perform the optimization of setting the destination // register to WZR/XZR if it ends up being unused. unsigned Opcode = AArch64ISD::SUBS; if (isCMN(RHS, CC)) { // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? Opcode = AArch64ISD::ADDS; RHS = RHS.getOperand(1); } else if (isCMN(LHS, CC)) { // As we are looking for EQ/NE compares, the operands can be commuted ; can // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? Opcode = AArch64ISD::ADDS; LHS = LHS.getOperand(1); } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) { // Similarly, (CMP (and X, Y), 0) can be implemented with a TST // (a.k.a. ANDS) except that the flags are only guaranteed to work for one // of the signed comparisons. Opcode = AArch64ISD::ANDS; RHS = LHS.getOperand(1); LHS = LHS.getOperand(0); } return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) .getValue(1); } /// \defgroup AArch64CCMP CMP;CCMP matching /// /// These functions deal with the formation of CMP;CCMP;... sequences. /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of /// a comparison. They set the NZCV flags to a predefined value if their /// predicate is false. This allows to express arbitrary conjunctions, for /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" /// expressed as: /// cmp A /// ccmp B, inv(CB), CA /// check for CB flags /// /// This naturally lets us implement chains of AND operations with SETCC /// operands. And we can even implement some other situations by transforming /// them: /// - We can implement (NEG SETCC) i.e. negating a single comparison by /// negating the flags used in a CCMP/FCCMP operations. /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations /// by negating the flags we test for afterwards. i.e. /// NEG (CMP CCMP CCCMP ...) can be implemented. /// - Note that we can only ever negate all previously processed results. /// What we can not implement by flipping the flags to test is a negation /// of two sub-trees (because the negation affects all sub-trees emitted so /// far, so the 2nd sub-tree we emit would also affect the first). /// With those tools we can implement some OR operations: /// - (OR (SETCC A) (SETCC B)) can be implemented via: /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) /// - After transforming OR to NEG/AND combinations we may be able to use NEG /// elimination rules from earlier to implement the whole thing as a /// CCMP/FCCMP chain. /// /// As complete example: /// or (or (setCA (cmp A)) (setCB (cmp B))) /// (and (setCC (cmp C)) (setCD (cmp D)))" /// can be reassociated to: /// or (and (setCC (cmp C)) setCD (cmp D)) // (or (setCA (cmp A)) (setCB (cmp B))) /// can be transformed to: /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" /// which can be implemented as: /// cmp C /// ccmp D, inv(CD), CC /// ccmp A, CA, inv(CD) /// ccmp B, CB, inv(CA) /// check for CB flags /// /// A counterexample is "or (and A B) (and C D)" which translates to /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we /// can only implement 1 of the inner (not) operations, but not both! /// @{ /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDValue CCOp, AArch64CC::CondCode Predicate, AArch64CC::CondCode OutCC, const SDLoc &DL, SelectionDAG &DAG) { unsigned Opcode = 0; const bool FullFP16 = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); if (LHS.getValueType().isFloatingPoint()) { assert(LHS.getValueType() != MVT::f128); if (LHS.getValueType() == MVT::f16 && !FullFP16) { LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); } Opcode = AArch64ISD::FCCMP; } else if (RHS.getOpcode() == ISD::SUB) { SDValue SubOp0 = RHS.getOperand(0); if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { // See emitComparison() on why we can only do this for SETEQ and SETNE. Opcode = AArch64ISD::CCMN; RHS = RHS.getOperand(1); } } if (Opcode == 0) Opcode = AArch64ISD::CCMP; SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); } /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be /// expressed as a conjunction. See \ref AArch64CCMP. /// \param CanNegate Set to true if we can negate the whole sub-tree just by /// changing the conditions on the SETCC tests. /// (this means we can call emitConjunctionRec() with /// Negate==true on this sub-tree) /// \param MustBeFirst Set to true if this subtree needs to be negated and we /// cannot do the negation naturally. We are required to /// emit the subtree first in this case. /// \param WillNegate Is true if are called when the result of this /// subexpression must be negated. This happens when the /// outer expression is an OR. We can use this fact to know /// that we have a double negation (or (or ...) ...) that /// can be implemented for free. static bool canEmitConjunction(const SDValue Val, bool &CanNegate, bool &MustBeFirst, bool WillNegate, unsigned Depth = 0) { if (!Val.hasOneUse()) return false; unsigned Opcode = Val->getOpcode(); if (Opcode == ISD::SETCC) { if (Val->getOperand(0).getValueType() == MVT::f128) return false; CanNegate = true; MustBeFirst = false; return true; } // Protect against exponential runtime and stack overflow. if (Depth > 6) return false; if (Opcode == ISD::AND || Opcode == ISD::OR) { bool IsOR = Opcode == ISD::OR; SDValue O0 = Val->getOperand(0); SDValue O1 = Val->getOperand(1); bool CanNegateL; bool MustBeFirstL; if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) return false; bool CanNegateR; bool MustBeFirstR; if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) return false; if (MustBeFirstL && MustBeFirstR) return false; if (IsOR) { // For an OR expression we need to be able to naturally negate at least // one side or we cannot do the transformation at all. if (!CanNegateL && !CanNegateR) return false; // If we the result of the OR will be negated and we can naturally negate // the leafs, then this sub-tree as a whole negates naturally. CanNegate = WillNegate && CanNegateL && CanNegateR; // If we cannot naturally negate the whole sub-tree, then this must be // emitted first. MustBeFirst = !CanNegate; } else { assert(Opcode == ISD::AND && "Must be OR or AND"); // We cannot naturally negate an AND operation. CanNegate = false; MustBeFirst = MustBeFirstL || MustBeFirstR; } return true; } return false; } /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain /// of CCMP/CFCMP ops. See @ref AArch64CCMP. /// Tries to transform the given i1 producing node @p Val to a series compare /// and conditional compare operations. @returns an NZCV flags producing node /// and sets @p OutCC to the flags that should be tested or returns SDValue() if /// transformation was not possible. /// \p Negate is true if we want this sub-tree being negated just by changing /// SETCC conditions. static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, AArch64CC::CondCode Predicate) { // We're at a tree leaf, produce a conditional comparison operation. unsigned Opcode = Val->getOpcode(); if (Opcode == ISD::SETCC) { SDValue LHS = Val->getOperand(0); SDValue RHS = Val->getOperand(1); ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); bool isInteger = LHS.getValueType().isInteger(); if (Negate) CC = getSetCCInverse(CC, isInteger); SDLoc DL(Val); // Determine OutCC and handle FP special case. if (isInteger) { OutCC = changeIntCCToAArch64CC(CC); } else { assert(LHS.getValueType().isFloatingPoint()); AArch64CC::CondCode ExtraCC; changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); // Some floating point conditions can't be tested with a single condition // code. Construct an additional comparison in this case. if (ExtraCC != AArch64CC::AL) { SDValue ExtraCmp; if (!CCOp.getNode()) ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); else ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, ExtraCC, DL, DAG); CCOp = ExtraCmp; Predicate = ExtraCC; } } // Produce a normal comparison if we are first in the chain if (!CCOp) return emitComparison(LHS, RHS, CC, DL, DAG); // Otherwise produce a ccmp. return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, DAG); } assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); bool IsOR = Opcode == ISD::OR; SDValue LHS = Val->getOperand(0); bool CanNegateL; bool MustBeFirstL; bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); assert(ValidL && "Valid conjunction/disjunction tree"); (void)ValidL; SDValue RHS = Val->getOperand(1); bool CanNegateR; bool MustBeFirstR; bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); assert(ValidR && "Valid conjunction/disjunction tree"); (void)ValidR; // Swap sub-tree that must come first to the right side. if (MustBeFirstL) { assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); std::swap(LHS, RHS); std::swap(CanNegateL, CanNegateR); std::swap(MustBeFirstL, MustBeFirstR); } bool NegateR; bool NegateAfterR; bool NegateL; bool NegateAfterAll; if (Opcode == ISD::OR) { // Swap the sub-tree that we can negate naturally to the left. if (!CanNegateL) { assert(CanNegateR && "at least one side must be negatable"); assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); assert(!Negate); std::swap(LHS, RHS); NegateR = false; NegateAfterR = true; } else { // Negate the left sub-tree if possible, otherwise negate the result. NegateR = CanNegateR; NegateAfterR = !CanNegateR; } NegateL = true; NegateAfterAll = !Negate; } else { assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); assert(!Negate && "Valid conjunction/disjunction tree"); NegateL = false; NegateR = false; NegateAfterR = false; NegateAfterAll = false; } // Emit sub-trees. AArch64CC::CondCode RHSCC; SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); if (NegateAfterR) RHSCC = AArch64CC::getInvertedCondCode(RHSCC); SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); if (NegateAfterAll) OutCC = AArch64CC::getInvertedCondCode(OutCC); return CmpL; } /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). /// In some cases this is even possible with OR operations in the expression. /// See \ref AArch64CCMP. /// \see emitConjunctionRec(). static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, AArch64CC::CondCode &OutCC) { bool DummyCanNegate; bool DummyMustBeFirst; if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) return SDValue(); return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); } /// @} /// Returns how profitable it is to fold a comparison's operand's shift and/or /// extension operations. static unsigned getCmpOperandFoldingProfit(SDValue Op) { auto isSupportedExtend = [&](SDValue V) { if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) return true; if (V.getOpcode() == ISD::AND) if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { uint64_t Mask = MaskCst->getZExtValue(); return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); } return false; }; if (!Op.hasOneUse()) return 0; if (isSupportedExtend(Op)) return 1; unsigned Opc = Op.getOpcode(); if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { uint64_t Shift = ShiftCst->getZExtValue(); if (isSupportedExtend(Op.getOperand(0))) return (Shift <= 4) ? 2 : 1; EVT VT = Op.getValueType(); if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) return 1; } return 0; } static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDValue &AArch64cc, SelectionDAG &DAG, const SDLoc &dl) { if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { EVT VT = RHS.getValueType(); uint64_t C = RHSC->getZExtValue(); if (!isLegalArithImmed(C)) { // Constant does not fit, try adjusting it by one? switch (CC) { default: break; case ISD::SETLT: case ISD::SETGE: if ((VT == MVT::i32 && C != 0x80000000 && isLegalArithImmed((uint32_t)(C - 1))) || (VT == MVT::i64 && C != 0x80000000ULL && isLegalArithImmed(C - 1ULL))) { CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; RHS = DAG.getConstant(C, dl, VT); } break; case ISD::SETULT: case ISD::SETUGE: if ((VT == MVT::i32 && C != 0 && isLegalArithImmed((uint32_t)(C - 1))) || (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; RHS = DAG.getConstant(C, dl, VT); } break; case ISD::SETLE: case ISD::SETGT: if ((VT == MVT::i32 && C != INT32_MAX && isLegalArithImmed((uint32_t)(C + 1))) || (VT == MVT::i64 && C != INT64_MAX && isLegalArithImmed(C + 1ULL))) { CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; RHS = DAG.getConstant(C, dl, VT); } break; case ISD::SETULE: case ISD::SETUGT: if ((VT == MVT::i32 && C != UINT32_MAX && isLegalArithImmed((uint32_t)(C + 1))) || (VT == MVT::i64 && C != UINT64_MAX && isLegalArithImmed(C + 1ULL))) { CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; RHS = DAG.getConstant(C, dl, VT); } break; } } } // Comparisons are canonicalized so that the RHS operand is simpler than the // LHS one, the extreme case being when RHS is an immediate. However, AArch64 // can fold some shift+extend operations on the RHS operand, so swap the // operands if that can be done. // // For example: // lsl w13, w11, #1 // cmp w13, w12 // can be turned into: // cmp w12, w11, lsl #1 if (!isa<ConstantSDNode>(RHS) || !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { std::swap(LHS, RHS); CC = ISD::getSetCCSwappedOperands(CC); } } SDValue Cmp; AArch64CC::CondCode AArch64CC; if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. // For the i8 operand, the largest immediate is 255, so this can be easily // encoded in the compare instruction. For the i16 operand, however, the // largest immediate cannot be encoded in the compare. // Therefore, use a sign extending load and cmn to avoid materializing the // -1 constant. For example, // movz w1, #65535 // ldrh w0, [x0, #0] // cmp w0, w1 // > // ldrsh w0, [x0, #0] // cmn w0, #1 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) // if and only if (sext LHS) == (sext RHS). The checks are in place to // ensure both the LHS and RHS are truly zero extended and to make sure the // transformation is profitable. if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && LHS.getNode()->hasNUsesOfValue(1, 0)) { int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, DAG.getValueType(MVT::i16)); Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, RHS.getValueType()), CC, dl, DAG); AArch64CC = changeIntCCToAArch64CC(CC); } } if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); } } } if (!Cmp) { Cmp = emitComparison(LHS, RHS, CC, dl, DAG); AArch64CC = changeIntCCToAArch64CC(CC); } AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); return Cmp; } static std::pair<SDValue, SDValue> getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && "Unsupported value type"); SDValue Value, Overflow; SDLoc DL(Op); SDValue LHS = Op.getOperand(0); SDValue RHS = Op.getOperand(1); unsigned Opc = 0; switch (Op.getOpcode()) { default: llvm_unreachable("Unknown overflow instruction!"); case ISD::SADDO: Opc = AArch64ISD::ADDS; CC = AArch64CC::VS; break; case ISD::UADDO: Opc = AArch64ISD::ADDS; CC = AArch64CC::HS; break; case ISD::SSUBO: Opc = AArch64ISD::SUBS; CC = AArch64CC::VS; break; case ISD::USUBO: Opc = AArch64ISD::SUBS; CC = AArch64CC::LO; break; // Multiply needs a little bit extra work. case ISD::SMULO: case ISD::UMULO: { CC = AArch64CC::NE; bool IsSigned = Op.getOpcode() == ISD::SMULO; if (Op.getValueType() == MVT::i32) { unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; // For a 32 bit multiply with overflow check we want the instruction // selector to generate a widening multiply (SMADDL/UMADDL). For that we // need to generate the following pattern: // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, DAG.getConstant(0, DL, MVT::i64)); // On AArch64 the upper 32 bits are always zero extended for a 32 bit // operation. We need to clear out the upper 32 bits, because we used a // widening multiply that wrote all 64 bits. In the end this should be a // noop. Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); if (IsSigned) { // The signed overflow check requires more than just a simple check for // any bit set in the upper 32 bits of the result. These bits could be // just the sign bits of a negative number. To perform the overflow // check we have to arithmetic shift right the 32nd bit of the result by // 31 bits. Then we compare the result to the upper 32 bits. SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, DAG.getConstant(32, DL, MVT::i64)); UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, DAG.getConstant(31, DL, MVT::i64)); // It is important that LowerBits is last, otherwise the arithmetic // shift will not be folded into the compare (SUBS). SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) .getValue(1); } else { // The overflow check for unsigned multiply is easy. We only need to // check if any of the upper 32 bits are set. This can be done with a // CMP (shifted register). For that we need to generate the following // pattern: // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, DAG.getConstant(32, DL, MVT::i64)); SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, DL, MVT::i64), UpperBits).getValue(1); } break; } assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); // For the 64 bit multiply Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); if (IsSigned) { SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, DAG.getConstant(63, DL, MVT::i64)); // It is important that LowerBits is last, otherwise the arithmetic // shift will not be folded into the compare (SUBS). SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) .getValue(1); } else { SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, DL, MVT::i64), UpperBits).getValue(1); } break; } } // switch (...) if (Opc) { SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); // Emit the AArch64 operation with overflow check. Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); Overflow = Value.getValue(1); } return std::make_pair(Value, Overflow); } SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, RTLIB::Libcall Call) const { SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first; } // Returns true if the given Op is the overflow flag result of an overflow // intrinsic operation. static bool isOverflowIntrOpRes(SDValue Op) { unsigned Opc = Op.getOpcode(); return (Op.getResNo() == 1 && (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)); } static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { SDValue Sel = Op.getOperand(0); SDValue Other = Op.getOperand(1); SDLoc dl(Sel); // If the operand is an overflow checking operation, invert the condition // code and kill the Not operation. I.e., transform: // (xor (overflow_op_bool, 1)) // --> // (csel 1, 0, invert(cc), overflow_op_bool) // ... which later gets transformed to just a cset instruction with an // inverted condition code, rather than a cset + eor sequence. if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) { // Only lower legal XALUO ops. if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) return SDValue(); SDValue TVal = DAG.getConstant(1, dl, MVT::i32); SDValue FVal = DAG.getConstant(0, dl, MVT::i32); AArch64CC::CondCode CC; SDValue Value, Overflow; std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, CCVal, Overflow); } // If neither operand is a SELECT_CC, give up. if (Sel.getOpcode() != ISD::SELECT_CC) std::swap(Sel, Other); if (Sel.getOpcode() != ISD::SELECT_CC) return Op; // The folding we want to perform is: // (xor x, (select_cc a, b, cc, 0, -1) ) // --> // (csel x, (xor x, -1), cc ...) // // The latter will get matched to a CSINV instruction. ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); SDValue LHS = Sel.getOperand(0); SDValue RHS = Sel.getOperand(1); SDValue TVal = Sel.getOperand(2); SDValue FVal = Sel.getOperand(3); // FIXME: This could be generalized to non-integer comparisons. if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) return Op; ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); // The values aren't constants, this isn't the pattern we're looking for. if (!CFVal || !CTVal) return Op; // We can commute the SELECT_CC by inverting the condition. This // might be needed to make this fit into a CSINV pattern. if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { std::swap(TVal, FVal); std::swap(CTVal, CFVal); CC = ISD::getSetCCInverse(CC, true); } // If the constants line up, perform the transform! if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { SDValue CCVal; SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); FVal = Other; TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, DAG.getConstant(-1ULL, dl, Other.getValueType())); return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, CCVal, Cmp); } return Op; } static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { EVT VT = Op.getValueType(); // Let legalize expand this if it isn't a legal type yet. if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) return SDValue(); SDVTList VTs = DAG.getVTList(VT, MVT::i32); unsigned Opc; bool ExtraOp = false; switch (Op.getOpcode()) { default: llvm_unreachable("Invalid code"); case ISD::ADDC: Opc = AArch64ISD::ADDS; break; case ISD::SUBC: Opc = AArch64ISD::SUBS; break; case ISD::ADDE: Opc = AArch64ISD::ADCS; ExtraOp = true; break; case ISD::SUBE: Opc = AArch64ISD::SBCS; ExtraOp = true; break; } if (!ExtraOp) return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), Op.getOperand(2)); } static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { // Let legalize expand this if it isn't a legal type yet. if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) return SDValue(); SDLoc dl(Op); AArch64CC::CondCode CC; // The actual operation that sets the overflow or carry flag. SDValue Value, Overflow; std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); // We use 0 and 1 as false and true values. SDValue TVal = DAG.getConstant(1, dl, MVT::i32); SDValue FVal = DAG.getConstant(0, dl, MVT::i32); // We use an inverted condition, because the conditional select is inverted // too. This will allow it to be selected to a single instruction: // CSINC Wd, WZR, WZR, invert(cond). SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, CCVal, Overflow); SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); } // Prefetch operands are: // 1: Address to prefetch // 2: bool isWrite // 3: int locality (0 = no locality ... 3 = extreme locality) // 4: bool isDataCache static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { SDLoc DL(Op); unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); bool IsStream = !Locality; // When the locality number is set if (Locality) { // The front-end should have filtered out the out-of-range values assert(Locality <= 3 && "Prefetch locality out-of-range"); // The locality degree is the opposite of the cache speed. // Put the number the other way around. // The encoding starts at 0 for level 1 Locality = 3 - Locality; } // built the mask value encoding the expected behavior. unsigned PrfOp = (IsWrite << 4) | // Load/Store bit (!IsData << 3) | // IsDataCache bit (Locality << 1) | // Cache level bits (unsigned)IsStream; // Stream bit return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); } SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const { assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); RTLIB::Libcall LC; LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); return LowerF128Call(Op, DAG, LC); } SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { if (Op.getOperand(0).getValueType() != MVT::f128) { // It's legal except when f128 is involved return Op; } RTLIB::Libcall LC; LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); // FP_ROUND node has a second operand indicating whether it is known to be // precise. That doesn't take part in the LibCall so we can't directly use // LowerF128Call. SDValue SrcVal = Op.getOperand(0); return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, SDLoc(Op)).first; } SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. // Any additional optimization in this function should be recorded // in the cost tables. EVT InVT = Op.getOperand(0).getValueType(); EVT VT = Op.getValueType(); unsigned NumElts = InVT.getVectorNumElements(); // f16 conversions are promoted to f32 when full fp16 is not supported. if (InVT.getVectorElementType() == MVT::f16 && !Subtarget->hasFullFP16()) { MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); SDLoc dl(Op); return DAG.getNode( Op.getOpcode(), dl, Op.getValueType(), DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); } if (VT.getSizeInBits() < InVT.getSizeInBits()) { SDLoc dl(Op); SDValue Cv = DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), Op.getOperand(0)); return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); } if (VT.getSizeInBits() > InVT.getSizeInBits()) { SDLoc dl(Op); MVT ExtVT = MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), VT.getVectorNumElements()); SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); return DAG.getNode(Op.getOpcode(), dl, VT, Ext); } // Type changing conversions are illegal. return Op; } SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const { if (Op.getOperand(0).getValueType().isVector()) return LowerVectorFP_TO_INT(Op, DAG); // f16 conversions are promoted to f32 when full fp16 is not supported. if (Op.getOperand(0).getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { SDLoc dl(Op); return DAG.getNode( Op.getOpcode(), dl, Op.getValueType(), DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); } if (Op.getOperand(0).getValueType() != MVT::f128) { // It's legal except when f128 is involved return Op; } RTLIB::Libcall LC; if (Op.getOpcode() == ISD::FP_TO_SINT) LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); else LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; } static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. // Any additional optimization in this function should be recorded // in the cost tables. EVT VT = Op.getValueType(); SDLoc dl(Op); SDValue In = Op.getOperand(0); EVT InVT = In.getValueType(); if (VT.getSizeInBits() < InVT.getSizeInBits()) { MVT CastVT = MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), InVT.getVectorNumElements()); In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); } if (VT.getSizeInBits() > InVT.getSizeInBits()) { unsigned CastOpc = Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; EVT CastVT = VT.changeVectorElementTypeToInteger(); In = DAG.getNode(CastOpc, dl, CastVT, In); return DAG.getNode(Op.getOpcode(), dl, VT, In); } return Op; } SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { if (Op.getValueType().isVector()) return LowerVectorINT_TO_FP(Op, DAG); // f16 conversions are promoted to f32 when full fp16 is not supported. if (Op.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { SDLoc dl(Op); return DAG.getNode( ISD::FP_ROUND, dl, MVT::f16, DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), DAG.getIntPtrConstant(0, dl)); } // i128 conversions are libcalls. if (Op.getOperand(0).getValueType() == MVT::i128) return SDValue(); // Other conversions are legal, unless it's to the completely software-based // fp128. if (Op.getValueType() != MVT::f128) return Op; RTLIB::Libcall LC; if (Op.getOpcode() == ISD::SINT_TO_FP) LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); else LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); return LowerF128Call(Op, DAG, LC); } SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const { // For iOS, we want to call an alternative entry point: __sincos_stret, // which returns the values in two S / D registers. SDLoc dl(Op); SDValue Arg = Op.getOperand(0); EVT ArgVT = Arg.getValueType(); Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); ArgListTy Args; ArgListEntry Entry; Entry.Node = Arg; Entry.Ty = ArgTy; Entry.IsSExt = false; Entry.IsZExt = false; Args.push_back(Entry); RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32; const char *LibcallName = getLibcallName(LC); SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); StructType *RetTy = StructType::get(ArgTy, ArgTy); TargetLowering::CallLoweringInfo CLI(DAG); CLI.setDebugLoc(dl) .setChain(DAG.getEntryNode()) .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); return CallResult.first; } static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { if (Op.getValueType() != MVT::f16) return SDValue(); assert(Op.getOperand(0).getValueType() == MVT::i16); SDLoc DL(Op); Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); return SDValue( DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 0); } static EVT getExtensionTo64Bits(const EVT &OrigVT) { if (OrigVT.getSizeInBits() >= 64) return OrigVT; assert(OrigVT.isSimple() && "Expecting a simple value type"); MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; switch (OrigSimpleTy) { default: llvm_unreachable("Unexpected Vector Type"); case MVT::v2i8: case MVT::v2i16: return MVT::v2i32; case MVT::v4i8: return MVT::v4i16; } } static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, const EVT &OrigTy, const EVT &ExtTy, unsigned ExtOpcode) { // The vector originally had a size of OrigTy. It was then extended to ExtTy. // We expect the ExtTy to be 128-bits total. If the OrigTy is less than // 64-bits we need to insert a new extension so that it will be 64-bits. assert(ExtTy.is128BitVector() && "Unexpected extension size"); if (OrigTy.getSizeInBits() >= 64) return N; // Must extend size to at least 64 bits to be used as an operand for VMULL. EVT NewVT = getExtensionTo64Bits(OrigTy); return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); } static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, bool isSigned) { EVT VT = N->getValueType(0); if (N->getOpcode() != ISD::BUILD_VECTOR) return false; for (const SDValue &Elt : N->op_values()) { if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { unsigned EltSize = VT.getScalarSizeInBits(); unsigned HalfSize = EltSize / 2; if (isSigned) { if (!isIntN(HalfSize, C->getSExtValue())) return false; } else { if (!isUIntN(HalfSize, C->getZExtValue())) return false; } continue; } return false; } return true; } static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, N->getOperand(0)->getValueType(0), N->getValueType(0), N->getOpcode()); assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); EVT VT = N->getValueType(0); SDLoc dl(N); unsigned EltSize = VT.getScalarSizeInBits() / 2; unsigned NumElts = VT.getVectorNumElements(); MVT TruncVT = MVT::getIntegerVT(EltSize); SmallVector<SDValue, 8> Ops; for (unsigned i = 0; i != NumElts; ++i) { ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); const APInt &CInt = C->getAPIntValue(); // Element types smaller than 32 bits are not legal, so use i32 elements. // The values are implicitly truncated so sext vs. zext doesn't matter. Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); } return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); } static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { return N->getOpcode() == ISD::SIGN_EXTEND || isExtendedBUILD_VECTOR(N, DAG, true); } static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { return N->getOpcode() == ISD::ZERO_EXTEND || isExtendedBUILD_VECTOR(N, DAG, false); } static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { unsigned Opcode = N->getOpcode(); if (Opcode == ISD::ADD || Opcode == ISD::SUB) { SDNode *N0 = N->getOperand(0).getNode(); SDNode *N1 = N->getOperand(1).getNode(); return N0->hasOneUse() && N1->hasOneUse() && isSignExtended(N0, DAG) && isSignExtended(N1, DAG); } return false; } static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { unsigned Opcode = N->getOpcode(); if (Opcode == ISD::ADD || Opcode == ISD::SUB) { SDNode *N0 = N->getOperand(0).getNode(); SDNode *N1 = N->getOperand(1).getNode(); return N0->hasOneUse() && N1->hasOneUse() && isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); } return false; } SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) const { // The rounding mode is in bits 23:22 of the FPSCR. // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) // so that the shift + and get folded into a bitfield extract. SDLoc dl(Op); SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)); SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, DAG.getConstant(1U << 22, dl, MVT::i32)); SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, DAG.getConstant(22, dl, MVT::i32)); return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, DAG.getConstant(3, dl, MVT::i32)); } static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { // Multiplications are only custom-lowered for 128-bit vectors so that // VMULL can be detected. Otherwise v2i64 multiplications are not legal. EVT VT = Op.getValueType(); assert(VT.is128BitVector() && VT.isInteger() && "unexpected type for custom-lowering ISD::MUL"); SDNode *N0 = Op.getOperand(0).getNode(); SDNode *N1 = Op.getOperand(1).getNode(); unsigned NewOpc = 0; bool isMLA = false; bool isN0SExt = isSignExtended(N0, DAG); bool isN1SExt = isSignExtended(N1, DAG); if (isN0SExt && isN1SExt) NewOpc = AArch64ISD::SMULL; else { bool isN0ZExt = isZeroExtended(N0, DAG); bool isN1ZExt = isZeroExtended(N1, DAG); if (isN0ZExt && isN1ZExt) NewOpc = AArch64ISD::UMULL; else if (isN1SExt || isN1ZExt) { // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these // into (s/zext A * s/zext C) + (s/zext B * s/zext C) if (isN1SExt && isAddSubSExt(N0, DAG)) { NewOpc = AArch64ISD::SMULL; isMLA = true; } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { NewOpc = AArch64ISD::UMULL; isMLA = true; } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { std::swap(N0, N1); NewOpc = AArch64ISD::UMULL; isMLA = true; } } if (!NewOpc) { if (VT == MVT::v2i64) // Fall through to expand this. It is not legal. return SDValue(); else // Other vector multiplications are legal. return Op; } } // Legalize to a S/UMULL instruction SDLoc DL(Op); SDValue Op0; SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); if (!isMLA) { Op0 = skipExtensionForVectorMULL(N0, DAG); assert(Op0.getValueType().is64BitVector() && Op1.getValueType().is64BitVector() && "unexpected types for extended operands to VMULL"); return DAG.getNode(NewOpc, DL, VT, Op0, Op1); } // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during // isel lowering to take advantage of no-stall back to back s/umul + s/umla. // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); EVT Op1VT = Op1.getValueType(); return DAG.getNode(N0->getOpcode(), DL, VT, DAG.getNode(NewOpc, DL, VT, DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), DAG.getNode(NewOpc, DL, VT, DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); } SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); SDLoc dl(Op); switch (IntNo) { default: return SDValue(); // Don't custom lower most intrinsics. case Intrinsic::thread_pointer: { EVT PtrVT = getPointerTy(DAG.getDataLayout()); return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); } case Intrinsic::aarch64_neon_abs: { EVT Ty = Op.getValueType(); if (Ty == MVT::i64) { SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Op.getOperand(1)); Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); } else { report_fatal_error("Unexpected type for AArch64 NEON intrinic"); } } case Intrinsic::aarch64_neon_smax: return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), Op.getOperand(1), Op.getOperand(2)); case Intrinsic::aarch64_neon_umax: return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), Op.getOperand(1), Op.getOperand(2)); case Intrinsic::aarch64_neon_smin: return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), Op.getOperand(1), Op.getOperand(2)); case Intrinsic::aarch64_neon_umin: return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), Op.getOperand(1), Op.getOperand(2)); case Intrinsic::localaddress: { const auto &MF = DAG.getMachineFunction(); const auto *RegInfo = Subtarget->getRegisterInfo(); unsigned Reg = RegInfo->getLocalAddressRegister(MF); return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, Op.getSimpleValueType()); } case Intrinsic::eh_recoverfp: { // FIXME: This needs to be implemented to correctly handle highly aligned // stack objects. For now we simply return the incoming FP. Refer D53541 // for more details. SDValue FnOp = Op.getOperand(1); SDValue IncomingFPOp = Op.getOperand(2); GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); if (!Fn) report_fatal_error( "llvm.eh.recoverfp must take a function as the first argument"); return IncomingFPOp; } } } // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, EVT VT, EVT MemVT, SelectionDAG &DAG) { assert(VT.isVector() && "VT should be a vector type"); assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); SDValue Value = ST->getValue(); // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract // the word lane which represent the v4i8 subvector. It optimizes the store // to: // // xtn v0.8b, v0.8h // str s0, [x0] SDValue Undef = DAG.getUNDEF(MVT::i16); SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, {Undef, Undef, Undef, Undef}); SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, Value, UndefVec); SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Trunc, DAG.getConstant(0, DL, MVT::i64)); return DAG.getStore(ST->getChain(), DL, ExtractTrunc, ST->getBasePtr(), ST->getMemOperand()); } // Custom lowering for any store, vector or scalar and/or default or with // a truncate operations. Currently only custom lower truncate operation // from vector v4i16 to v4i8. SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { SDLoc Dl(Op); StoreSDNode *StoreNode = cast<StoreSDNode>(Op); assert (StoreNode && "Can only custom lower store nodes"); SDValue Value = StoreNode->getValue(); EVT VT = Value.getValueType(); EVT MemVT = StoreNode->getMemoryVT(); assert (VT.isVector() && "Can only custom lower vector store types"); unsigned AS = StoreNode->getAddressSpace(); unsigned Align = StoreNode->getAlignment(); if (Align < MemVT.getStoreSize() && !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) { return scalarizeVectorStore(StoreNode, DAG); } if (StoreNode->isTruncatingStore()) { return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); } return SDValue(); } SDValue AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { LLVM_DEBUG(dbgs() << "Custom lowering: "); LLVM_DEBUG(Op.dump()); switch (Op.getOpcode()) { default: llvm_unreachable("unimplemented operand"); return SDValue(); case ISD::BITCAST: return LowerBITCAST(Op, DAG); case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); case ISD::SETCC: return LowerSETCC(Op, DAG); case ISD::BR_CC: return LowerBR_CC(Op, DAG); case ISD::SELECT: return LowerSELECT(Op, DAG); case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); case ISD::JumpTable: return LowerJumpTable(Op, DAG); case ISD::BR_JT: return LowerBR_JT(Op, DAG); case ISD::ConstantPool: return LowerConstantPool(Op, DAG); case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); case ISD::VASTART: return LowerVASTART(Op, DAG); case ISD::VACOPY: return LowerVACOPY(Op, DAG); case ISD::VAARG: return LowerVAARG(Op, DAG); case ISD::ADDC: case ISD::ADDE: case ISD::SUBC: case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); case ISD::SADDO: case ISD::UADDO: case ISD::SSUBO: case ISD::USUBO: case ISD::SMULO: case ISD::UMULO: return LowerXALUO(Op, DAG); case ISD::FADD: return LowerF128Call(Op, DAG, RTLIB::ADD_F128); case ISD::FSUB: return LowerF128Call(Op, DAG, RTLIB::SUB_F128); case ISD::FMUL: return LowerF128Call(Op, DAG, RTLIB::MUL_F128); case ISD::FDIV: return LowerF128Call(Op, DAG, RTLIB::DIV_F128); case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG); case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG); case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); case ISD::SPONENTRY: return LowerSPONENTRY(Op, DAG); case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); case ISD::ADDROFRETURNADDR: return LowerADDROFRETURNADDR(Op, DAG); case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG); case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG); case ISD::SRA: case ISD::SRL: case ISD::SHL: return LowerVectorSRA_SRL_SHL(Op, DAG); case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG); case ISD::SRL_PARTS: case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG); case ISD::CTPOP: return LowerCTPOP(Op, DAG); case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG); case ISD::OR: return LowerVectorOR(Op, DAG); case ISD::XOR: return LowerXOR(Op, DAG); case ISD::PREFETCH: return LowerPREFETCH(Op, DAG); case ISD::SINT_TO_FP: case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG); case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG); case ISD::FSINCOS: return LowerFSINCOS(Op, DAG); case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); case ISD::MUL: return LowerMUL(Op, DAG); case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); case ISD::STORE: return LowerSTORE(Op, DAG); case ISD::VECREDUCE_ADD: case ISD::VECREDUCE_SMAX: case ISD::VECREDUCE_SMIN: case ISD::VECREDUCE_UMAX: case ISD::VECREDUCE_UMIN: case ISD::VECREDUCE_FMAX: case ISD::VECREDUCE_FMIN: return LowerVECREDUCE(Op, DAG); case ISD::ATOMIC_LOAD_SUB: return LowerATOMIC_LOAD_SUB(Op, DAG); case ISD::ATOMIC_LOAD_AND: return LowerATOMIC_LOAD_AND(Op, DAG); case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG); } } //===----------------------------------------------------------------------===// // Calling Convention Implementation //===----------------------------------------------------------------------===// /// Selects the correct CCAssignFn for a given CallingConvention value. CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, bool IsVarArg) const { switch (CC) { default: report_fatal_error("Unsupported calling convention."); case CallingConv::WebKit_JS: return CC_AArch64_WebKit_JS; case CallingConv::GHC: return CC_AArch64_GHC; case CallingConv::C: case CallingConv::Fast: case CallingConv::PreserveMost: case CallingConv::CXX_FAST_TLS: case CallingConv::Swift: if (Subtarget->isTargetWindows() && IsVarArg) return CC_AArch64_Win64_VarArg; if (!Subtarget->isTargetDarwin()) return CC_AArch64_AAPCS; return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; case CallingConv::Win64: return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; case CallingConv::AArch64_VectorCall: return CC_AArch64_AAPCS; } } CCAssignFn * AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS : RetCC_AArch64_AAPCS; } SDValue AArch64TargetLowering::LowerFormalArguments( SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo &MFI = MF.getFrameInfo(); bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); // Assign locations to all of the incoming arguments. SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext()); // At this point, Ins[].VT may already be promoted to i32. To correctly // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here // we use a special version of AnalyzeFormalArguments to pass in ValVT and // LocVT. unsigned NumArgs = Ins.size(); Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); unsigned CurArgIdx = 0; for (unsigned i = 0; i != NumArgs; ++i) { MVT ValVT = Ins[i].VT; if (Ins[i].isOrigArg()) { std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); CurArgIdx = Ins[i].getOrigArgIndex(); // Get type of the original argument. EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), /*AllowUnknown*/ true); MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) ValVT = MVT::i8; else if (ActualMVT == MVT::i16) ValVT = MVT::i16; } CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); assert(!Res && "Call operand has unhandled type"); (void)Res; } assert(ArgLocs.size() == Ins.size()); SmallVector<SDValue, 16> ArgValues; for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { CCValAssign &VA = ArgLocs[i]; if (Ins[i].Flags.isByVal()) { // Byval is used for HFAs in the PCS, but the system should work in a // non-compliant manner for larger structs. EVT PtrVT = getPointerTy(DAG.getDataLayout()); int Size = Ins[i].Flags.getByValSize(); unsigned NumRegs = (Size + 7) / 8; // FIXME: This works on big-endian for composite byvals, which are the common // case. It should also work for fundamental types too. unsigned FrameIdx = MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); InVals.push_back(FrameIdxN); continue; } if (VA.isRegLoc()) { // Arguments stored in registers. EVT RegVT = VA.getLocVT(); SDValue ArgValue; const TargetRegisterClass *RC; if (RegVT == MVT::i32) RC = &AArch64::GPR32RegClass; else if (RegVT == MVT::i64) RC = &AArch64::GPR64RegClass; else if (RegVT == MVT::f16) RC = &AArch64::FPR16RegClass; else if (RegVT == MVT::f32) RC = &AArch64::FPR32RegClass; else if (RegVT == MVT::f64 || RegVT.is64BitVector()) RC = &AArch64::FPR64RegClass; else if (RegVT == MVT::f128 || RegVT.is128BitVector()) RC = &AArch64::FPR128RegClass; else llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); // Transform the arguments in physical registers into virtual ones. unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); // If this is an 8, 16 or 32-bit value, it is really passed promoted // to 64 bits. Insert an assert[sz]ext to capture this, then // truncate to the right size. switch (VA.getLocInfo()) { default: llvm_unreachable("Unknown loc info!"); case CCValAssign::Full: break; case CCValAssign::BCvt: ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); break; case CCValAssign::AExt: case CCValAssign::SExt: case CCValAssign::ZExt: // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt // nodes after our lowering. assert(RegVT == Ins[i].VT && "incorrect register location selected"); break; } InVals.push_back(ArgValue); } else { // VA.isRegLoc() assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); unsigned ArgOffset = VA.getLocMemOffset(); unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; uint32_t BEAlign = 0; if (!Subtarget->isLittleEndian() && ArgSize < 8 && !Ins[i].Flags.isInConsecutiveRegs()) BEAlign = 8 - ArgSize; int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); // Create load nodes to retrieve arguments from the stack. SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); SDValue ArgValue; // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; MVT MemVT = VA.getValVT(); switch (VA.getLocInfo()) { default: break; case CCValAssign::BCvt: MemVT = VA.getLocVT(); break; case CCValAssign::SExt: ExtType = ISD::SEXTLOAD; break; case CCValAssign::ZExt: ExtType = ISD::ZEXTLOAD; break; case CCValAssign::AExt: ExtType = ISD::EXTLOAD; break; } ArgValue = DAG.getExtLoad( ExtType, DL, VA.getLocVT(), Chain, FIN, MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), MemVT); InVals.push_back(ArgValue); } } // varargs AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); if (isVarArg) { if (!Subtarget->isTargetDarwin() || IsWin64) { // The AAPCS variadic function ABI is identical to the non-variadic // one. As a result there may be more arguments in registers and we should // save them for future reference. // Win64 variadic functions also pass arguments in registers, but all float // arguments are passed in integer registers. saveVarArgRegisters(CCInfo, DAG, DL, Chain); } // This will point to the next argument passed via stack. unsigned StackOffset = CCInfo.getNextStackOffset(); // We currently pass all varargs at 8-byte alignment. StackOffset = ((StackOffset + 7) & ~7); FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); if (MFI.hasMustTailInVarArgFunc()) { SmallVector<MVT, 2> RegParmTypes; RegParmTypes.push_back(MVT::i64); RegParmTypes.push_back(MVT::f128); // Compute the set of forwarded registers. The rest are scratch. SmallVectorImpl<ForwardedRegister> &Forwards = FuncInfo->getForwardedMustTailRegParms(); CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_AArch64_AAPCS); } } unsigned StackArgSize = CCInfo.getNextStackOffset(); bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { // This is a non-standard ABI so by fiat I say we're allowed to make full // use of the stack area to be popped, which must be aligned to 16 bytes in // any case: StackArgSize = alignTo(StackArgSize, 16); // If we're expected to restore the stack (e.g. fastcc) then we'll be adding // a multiple of 16. FuncInfo->setArgumentStackToRestore(StackArgSize); // This realignment carries over to the available bytes below. Our own // callers will guarantee the space is free by giving an aligned value to // CALLSEQ_START. } // Even if we're not expected to free up the space, it's useful to know how // much is there while considering tail calls (because we can reuse it). FuncInfo->setBytesInStackArgArea(StackArgSize); if (Subtarget->hasCustomCallingConv()) Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); return Chain; } void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, SelectionDAG &DAG, const SDLoc &DL, SDValue &Chain) const { MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo &MFI = MF.getFrameInfo(); AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); auto PtrVT = getPointerTy(DAG.getDataLayout()); bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); SmallVector<SDValue, 8> MemOps; static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4, AArch64::X5, AArch64::X6, AArch64::X7 }; static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); int GPRIdx = 0; if (GPRSaveSize != 0) { if (IsWin64) { GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); if (GPRSaveSize & 15) // The extra size here, if triggered, will always be 8. MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); } else GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); SDValue Store = DAG.getStore( Val.getValue(1), DL, Val, FIN, IsWin64 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), GPRIdx, (i - FirstVariadicGPR) * 8) : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); MemOps.push_back(Store); FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); } } FuncInfo->setVarArgsGPRIndex(GPRIdx); FuncInfo->setVarArgsGPRSize(GPRSaveSize); if (Subtarget->hasFPARMv8() && !IsWin64) { static const MCPhysReg FPRArgRegs[] = { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); int FPRIdx = 0; if (FPRSaveSize != 0) { FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); SDValue Store = DAG.getStore( Val.getValue(1), DL, Val, FIN, MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); MemOps.push_back(Store); FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(16, DL, PtrVT)); } } FuncInfo->setVarArgsFPRIndex(FPRIdx); FuncInfo->setVarArgsFPRSize(FPRSaveSize); } if (!MemOps.empty()) { Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); } } /// LowerCallResult - Lower the result values of a call into the /// appropriate copies out of appropriate physical registers. SDValue AArch64TargetLowering::LowerCallResult( SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, SDValue ThisVal) const { CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS : RetCC_AArch64_AAPCS; // Assign locations to each value returned by this call. SmallVector<CCValAssign, 16> RVLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, *DAG.getContext()); CCInfo.AnalyzeCallResult(Ins, RetCC); // Copy all of the result registers out of their specified physreg. for (unsigned i = 0; i != RVLocs.size(); ++i) { CCValAssign VA = RVLocs[i]; // Pass 'this' value directly from the argument to return value, to avoid // reg unit interference if (i == 0 && isThisReturn) { assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && "unexpected return calling convention register assignment"); InVals.push_back(ThisVal); continue; } SDValue Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); Chain = Val.getValue(1); InFlag = Val.getValue(2); switch (VA.getLocInfo()) { default: llvm_unreachable("Unknown loc info!"); case CCValAssign::Full: break; case CCValAssign::BCvt: Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); break; } InVals.push_back(Val); } return Chain; } /// Return true if the calling convention is one that we can guarantee TCO for. static bool canGuaranteeTCO(CallingConv::ID CC) { return CC == CallingConv::Fast; } /// Return true if we might ever do TCO for calls with this calling convention. static bool mayTailCallThisCC(CallingConv::ID CC) { switch (CC) { case CallingConv::C: case CallingConv::PreserveMost: case CallingConv::Swift: return true; default: return canGuaranteeTCO(CC); } } bool AArch64TargetLowering::isEligibleForTailCallOptimization( SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { if (!mayTailCallThisCC(CalleeCC)) return false; MachineFunction &MF = DAG.getMachineFunction(); const Function &CallerF = MF.getFunction(); CallingConv::ID CallerCC = CallerF.getCallingConv(); bool CCMatch = CallerCC == CalleeCC; // Byval parameters hand the function a pointer directly into the stack area // we want to reuse during a tail call. Working around this *is* possible (see // X86) but less efficient and uglier in LowerCall. for (Function::const_arg_iterator i = CallerF.arg_begin(), e = CallerF.arg_end(); i != e; ++i) if (i->hasByValAttr()) return false; if (getTargetMachine().Options.GuaranteedTailCallOpt) return canGuaranteeTCO(CalleeCC) && CCMatch; // Externally-defined functions with weak linkage should not be // tail-called on AArch64 when the OS does not support dynamic // pre-emption of symbols, as the AAELF spec requires normal calls // to undefined weak functions to be replaced with a NOP or jump to the // next instruction. The behaviour of branch instructions in this // situation (as used for tail calls) is implementation-defined, so we // cannot rely on the linker replacing the tail call with a return. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { const GlobalValue *GV = G->getGlobal(); const Triple &TT = getTargetMachine().getTargetTriple(); if (GV->hasExternalWeakLinkage() && (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) return false; } // Now we search for cases where we can use a tail call without changing the // ABI. Sibcall is used in some places (particularly gcc) to refer to this // concept. // I want anyone implementing a new calling convention to think long and hard // about this assert. assert((!isVarArg || CalleeCC == CallingConv::C) && "Unexpected variadic calling convention"); LLVMContext &C = *DAG.getContext(); if (isVarArg && !Outs.empty()) { // At least two cases here: if caller is fastcc then we can't have any // memory arguments (we'd be expected to clean up the stack afterwards). If // caller is C then we could potentially use its argument area. // FIXME: for now we take the most conservative of these in both cases: // disallow all variadic memory operands. SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); for (const CCValAssign &ArgLoc : ArgLocs) if (!ArgLoc.isRegLoc()) return false; } // Check that the call results are passed in the same way. if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, CCAssignFnForCall(CalleeCC, isVarArg), CCAssignFnForCall(CallerCC, isVarArg))) return false; // The callee has to preserve all registers the caller needs to preserve. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); if (!CCMatch) { const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); if (Subtarget->hasCustomCallingConv()) { TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); } if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) return false; } // Nothing more to check if the callee is taking no arguments if (Outs.empty()) return true; SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); // If the stack arguments for this call do not fit into our own save area then // the call cannot be made tail. if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) return false; const MachineRegisterInfo &MRI = MF.getRegInfo(); if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) return false; return true; } SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, SelectionDAG &DAG, MachineFrameInfo &MFI, int ClobberedFI) const { SmallVector<SDValue, 8> ArgChains; int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; // Include the original chain at the beginning of the list. When this is // used by target LowerCall hooks, this helps legalize find the // CALLSEQ_BEGIN node. ArgChains.push_back(Chain); // Add a chain value for each stack argument corresponding for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U) if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) if (FI->getIndex() < 0) { int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); int64_t InLastByte = InFirstByte; InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || (FirstByte <= InFirstByte && InFirstByte <= LastByte)) ArgChains.push_back(SDValue(L, 1)); } // Build a tokenfactor for all the chains. return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); } bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, bool TailCallOpt) const { return CallCC == CallingConv::Fast && TailCallOpt; } /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, /// and add input and output parameter nodes. SDValue AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, SmallVectorImpl<SDValue> &InVals) const { SelectionDAG &DAG = CLI.DAG; SDLoc &DL = CLI.DL; SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; SmallVector<SDValue, 32> &OutVals = CLI.OutVals; SmallVector<ISD::InputArg, 32> &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(); bool IsThisReturn = false; AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; bool IsSibCall = false; if (IsTailCall) { // Check if it's really possible to do a tail call. IsTailCall = isEligibleForTailCallOptimization( Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) report_fatal_error("failed to perform tail call elimination on a call " "site marked musttail"); // A sibling call is one where we're under the usual C ABI and not planning // to change that but can still do a tail call: if (!TailCallOpt && IsTailCall) IsSibCall = true; if (IsTailCall) ++NumTailCalls; } // Analyze operands of the call, assigning locations to each operand. SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext()); if (IsVarArg) { // Handle fixed and variable vector arguments differently. // Variable vector arguments always go into memory. unsigned NumArgs = Outs.size(); for (unsigned i = 0; i != NumArgs; ++i) { MVT ArgVT = Outs[i].VT; ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/ !Outs[i].IsFixed); bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); assert(!Res && "Call operand has unhandled type"); (void)Res; } } else { // At this point, Outs[].VT may already be promoted to i32. To correctly // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here // we use a special version of AnalyzeCallOperands to pass in ValVT and // LocVT. unsigned NumArgs = Outs.size(); for (unsigned i = 0; i != NumArgs; ++i) { MVT ValVT = Outs[i].VT; // Get type of the original argument. EVT ActualVT = getValueType(DAG.getDataLayout(), CLI.getArgs()[Outs[i].OrigArgIndex].Ty, /*AllowUnknown*/ true); MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) ValVT = MVT::i8; else if (ActualMVT == MVT::i16) ValVT = MVT::i16; CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); assert(!Res && "Call operand has unhandled type"); (void)Res; } } // Get a count of how many bytes are to be pushed on the stack. unsigned NumBytes = CCInfo.getNextStackOffset(); if (IsSibCall) { // Since we're not changing the ABI to make this a tail call, the memory // operands are already available in the caller's incoming argument space. NumBytes = 0; } // FPDiff is the byte offset of the call's argument area from the callee's. // Stores to callee stack arguments will be placed in FixedStackSlots offset // by this amount for a tail call. In a sibling call it must be 0 because the // caller will deallocate the entire stack and the callee still expects its // arguments to begin at SP+0. Completely unused for non-tail calls. int FPDiff = 0; if (IsTailCall && !IsSibCall) { unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); // Since callee will pop argument stack as a tail call, we must keep the // popped size 16-byte aligned. NumBytes = alignTo(NumBytes, 16); // FPDiff will be negative if this tail call requires more space than we // would automatically have in our incoming argument space. Positive if we // can actually shrink the stack. FPDiff = NumReusableBytes - NumBytes; // The stack pointer must be 16-byte aligned at all times it's used for a // memory operation, which in practice means at *all* times and in // particular across call boundaries. Therefore our own arguments started at // a 16-byte aligned SP and the delta applied for the tail call should // satisfy the same constraint. assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); } // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass if (!IsSibCall) Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy(DAG.getDataLayout())); SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; SmallVector<SDValue, 8> MemOpChains; auto PtrVT = getPointerTy(DAG.getDataLayout()); if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) { const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); for (const auto &F : Forwards) { SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val)); } } // Walk the register/memloc assignments, inserting copies/loads. for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; ++i, ++realArgIdx) { CCValAssign &VA = ArgLocs[i]; SDValue Arg = OutVals[realArgIdx]; ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; // 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, DL, VA.getLocVT(), Arg); break; case CCValAssign::ZExt: Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); break; case CCValAssign::AExt: if (Outs[realArgIdx].ArgVT == MVT::i1) { // AAPCS requires i1 to be zero-extended to 8-bits by the caller. Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); } Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); break; case CCValAssign::BCvt: Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); break; case CCValAssign::FPExt: Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); break; } if (VA.isRegLoc()) { if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && Outs[0].VT == MVT::i64) { assert(VA.getLocVT() == MVT::i64 && "unexpected calling convention register assignment"); assert(!Ins.empty() && Ins[0].VT == MVT::i64 && "unexpected use of 'returned'"); IsThisReturn = true; } RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); } else { assert(VA.isMemLoc()); SDValue DstAddr; MachinePointerInfo DstInfo; // FIXME: This works on big-endian for composite byvals, which are the // common case. It should also work for fundamental types too. uint32_t BEAlign = 0; unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 : VA.getValVT().getSizeInBits(); OpSize = (OpSize + 7) / 8; if (!Subtarget->isLittleEndian() && !Flags.isByVal() && !Flags.isInConsecutiveRegs()) { if (OpSize < 8) BEAlign = 8 - OpSize; } unsigned LocMemOffset = VA.getLocMemOffset(); int32_t Offset = LocMemOffset + BEAlign; SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); if (IsTailCall) { Offset = Offset + FPDiff; int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); DstAddr = DAG.getFrameIndex(FI, PtrVT); DstInfo = MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); // Make sure any stack arguments overlapping with where we're storing // are loaded before this eventual operation. Otherwise they'll be // clobbered. Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); } else { SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset); } if (Outs[i].Flags.isByVal()) { SDValue SizeNode = DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); SDValue Cpy = DAG.getMemcpy( Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), /*isVol = */ false, /*AlwaysInline = */ false, /*isTailCall = */ false, DstInfo, MachinePointerInfo()); MemOpChains.push_back(Cpy); } else { // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already // promoted to a legal register type i32, we should truncate Arg back to // i1/i8/i16. if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || VA.getValVT() == MVT::i16) Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); MemOpChains.push_back(Store); } } } if (!MemOpChains.empty()) Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); // Build a sequence of copy-to-reg nodes chained together with token chain // and flag operands which copy the outgoing args into the appropriate regs. SDValue InFlag; for (auto &RegToPass : RegsToPass) { Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, RegToPass.second, InFlag); InFlag = Chain.getValue(1); } // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol // node so that legalize doesn't hack it. if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { auto GV = G->getGlobal(); if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) == AArch64II::MO_GOT) { Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) { assert(Subtarget->isTargetWindows() && "Windows is the only supported COFF target"); Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT); } else { const GlobalValue *GV = G->getGlobal(); Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); } } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { if (getTargetMachine().getCodeModel() == CodeModel::Large && Subtarget->isTargetMachO()) { const char *Sym = S->getSymbol(); Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); } else { const char *Sym = S->getSymbol(); Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); } } // We don't usually want to end the call-sequence here because we would tidy // the frame up *after* the call, however in the ABI-changing tail-call case // we've carefully laid out the parameters so that when sp is reset they'll be // in the correct location. if (IsTailCall && !IsSibCall) { Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), DAG.getIntPtrConstant(0, DL, true), InFlag, DL); InFlag = Chain.getValue(1); } std::vector<SDValue> Ops; Ops.push_back(Chain); Ops.push_back(Callee); if (IsTailCall) { // Each tail call may have to adjust the stack by a different amount, so // this information must travel along with the operation for eventual // consumption by emitEpilogue. Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); } // Add argument registers to the end of the list so that they are known live // into the call. for (auto &RegToPass : RegsToPass) Ops.push_back(DAG.getRegister(RegToPass.first, RegToPass.second.getValueType())); // Add a register mask operand representing the call-preserved registers. const uint32_t *Mask; const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); if (IsThisReturn) { // For 'this' returns, use the X0-preserving mask if applicable Mask = TRI->getThisReturnPreservedMask(MF, CallConv); if (!Mask) { IsThisReturn = false; Mask = TRI->getCallPreservedMask(MF, CallConv); } } else Mask = TRI->getCallPreservedMask(MF, CallConv); if (Subtarget->hasCustomCallingConv()) TRI->UpdateCustomCallPreservedMask(MF, &Mask); if (TRI->isAnyArgRegReserved(MF)) TRI->emitReservedArgRegCallError(MF); assert(Mask && "Missing call preserved mask for calling convention"); Ops.push_back(DAG.getRegisterMask(Mask)); if (InFlag.getNode()) Ops.push_back(InFlag); SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); // If we're doing a tall call, use a TC_RETURN here rather than an // actual call instruction. if (IsTailCall) { MF.getFrameInfo().setHasTailCall(); return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); } // Returns a chain and a flag for retval copy to use. Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); InFlag = Chain.getValue(1); uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), DAG.getIntPtrConstant(CalleePopBytes, DL, true), InFlag, DL); if (!Ins.empty()) InFlag = Chain.getValue(1); // Handle result values, copying them out of physregs into vregs that we // return. return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, InVals, IsThisReturn, IsThisReturn ? OutVals[0] : SDValue()); } bool AArch64TargetLowering::CanLowerReturn( CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS : RetCC_AArch64_AAPCS; SmallVector<CCValAssign, 16> RVLocs; CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); return CCInfo.CheckReturn(Outs, RetCC); } SDValue AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SDLoc &DL, SelectionDAG &DAG) const { CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS : RetCC_AArch64_AAPCS; SmallVector<CCValAssign, 16> RVLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, *DAG.getContext()); CCInfo.AnalyzeReturn(Outs, RetCC); // Copy the result values into the output registers. SDValue Flag; SmallVector<SDValue, 4> RetOps(1, Chain); for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); ++i, ++realRVLocIdx) { CCValAssign &VA = RVLocs[i]; assert(VA.isRegLoc() && "Can only return in registers!"); SDValue Arg = OutVals[realRVLocIdx]; switch (VA.getLocInfo()) { default: llvm_unreachable("Unknown loc info!"); case CCValAssign::Full: if (Outs[i].ArgVT == MVT::i1) { // AAPCS requires i1 to be zero-extended to i8 by the producer of the // value. This is strictly redundant on Darwin (which uses "zeroext // i1"), but will be optimised out before ISel. Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); } break; case CCValAssign::BCvt: Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); break; } Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); Flag = Chain.getValue(1); RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); } const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); const MCPhysReg *I = TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); if (I) { for (; *I; ++I) { if (AArch64::GPR64RegClass.contains(*I)) RetOps.push_back(DAG.getRegister(*I, MVT::i64)); else if (AArch64::FPR64RegClass.contains(*I)) RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); else llvm_unreachable("Unexpected register class in CSRsViaCopy!"); } } RetOps[0] = Chain; // Update chain. // Add the flag if we have it. if (Flag.getNode()) RetOps.push_back(Flag); return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); } //===----------------------------------------------------------------------===// // Other Lowering Code //===----------------------------------------------------------------------===// SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, SelectionDAG &DAG, unsigned Flag) const { return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, N->getOffset(), Flag); } SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, SelectionDAG &DAG, unsigned Flag) const { return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); } SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, SelectionDAG &DAG, unsigned Flag) const { return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), N->getOffset(), Flag); } SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, SelectionDAG &DAG, unsigned Flag) const { return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); } // (loadGOT sym) template <class NodeTy> SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, unsigned Flags) const { LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); SDLoc DL(N); EVT Ty = getPointerTy(DAG.getDataLayout()); SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); // FIXME: Once remat is capable of dealing with instructions with register // operands, expand this into two nodes instead of using a wrapper node. return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); } // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) template <class NodeTy> SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, unsigned Flags) const { LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); SDLoc DL(N); EVT Ty = getPointerTy(DAG.getDataLayout()); const unsigned char MO_NC = AArch64II::MO_NC; return DAG.getNode( AArch64ISD::WrapperLarge, DL, Ty, getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); } // (addlow (adrp %hi(sym)) %lo(sym)) template <class NodeTy> SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, unsigned Flags) const { LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); SDLoc DL(N); EVT Ty = getPointerTy(DAG.getDataLayout()); SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); SDValue Lo = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); } // (adr sym) template <class NodeTy> SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, unsigned Flags) const { LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); SDLoc DL(N); EVT Ty = getPointerTy(DAG.getDataLayout()); SDValue Sym = getTargetNode(N, Ty, DAG, Flags); return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); } SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); const GlobalValue *GV = GN->getGlobal(); unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); if (OpFlags != AArch64II::MO_NO_FLAG) assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && "unexpected offset in global node"); // This also catches the large code model case for Darwin, and tiny code // model with got relocations. if ((OpFlags & AArch64II::MO_GOT) != 0) { return getGOT(GN, DAG, OpFlags); } SDValue Result; if (getTargetMachine().getCodeModel() == CodeModel::Large) { Result = getAddrLarge(GN, DAG, OpFlags); } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { Result = getAddrTiny(GN, DAG, OpFlags); } else { Result = getAddr(GN, DAG, OpFlags); } EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDLoc DL(GN); if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo::getGOT(DAG.getMachineFunction())); return Result; } /// Convert a TLS address reference into the correct sequence of loads /// and calls to compute the variable's address (for Darwin, currently) and /// return an SDValue containing the final node. /// Darwin only has one TLS scheme which must be capable of dealing with the /// fully general situation, in the worst case. This means: /// + "extern __thread" declaration. /// + Defined in a possibly unknown dynamic library. /// /// The general system is that each __thread variable has a [3 x i64] descriptor /// which contains information used by the runtime to calculate the address. The /// only part of this the compiler needs to know about is the first xword, which /// contains a function pointer that must be called with the address of the /// entire descriptor in "x0". /// /// Since this descriptor may be in a different unit, in general even the /// descriptor must be accessed via an indirect load. The "ideal" code sequence /// is: /// adrp x0, _var@TLVPPAGE /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, /// ; the function pointer /// blr x1 ; Uses descriptor address in x0 /// ; Address of _var is now in x0. /// /// If the address of _var's descriptor *is* known to the linker, then it can /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for /// a slight efficiency gain. SDValue AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { assert(Subtarget->isTargetDarwin() && "This function expects a Darwin target"); SDLoc DL(Op); MVT PtrVT = getPointerTy(DAG.getDataLayout()); const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); SDValue TLVPAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); // The first entry in the descriptor is a function pointer that we must call // to obtain the address of the variable. SDValue Chain = DAG.getEntryNode(); SDValue FuncTLVGet = DAG.getLoad( MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(DAG.getMachineFunction()), /* Alignment = */ 8, MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); Chain = FuncTLVGet.getValue(1); MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); MFI.setAdjustsStack(true); // TLS calls preserve all registers except those that absolutely must be // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be // silly). const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); const uint32_t *Mask = TRI->getTLSCallPreservedMask(); if (Subtarget->hasCustomCallingConv()) TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); // Finally, we can make the call. This is just a degenerate version of a // normal AArch64 call node: x0 takes the address of the descriptor, and // returns the address of the variable in this thread. Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); Chain = DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), DAG.getRegisterMask(Mask), Chain.getValue(1)); return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); } /// When accessing thread-local variables under either the general-dynamic or /// local-dynamic system, we make a "TLS-descriptor" call. The variable will /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry /// is a function pointer to carry out the resolution. /// /// The sequence is: /// adrp x0, :tlsdesc:var /// ldr x1, [x0, #:tlsdesc_lo12:var] /// add x0, x0, #:tlsdesc_lo12:var /// .tlsdesccall var /// blr x1 /// (TPIDR_EL0 offset now in x0) /// /// The above sequence must be produced unscheduled, to enable the linker to /// optimize/relax this sequence. /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the /// above sequence, and expanded really late in the compilation flow, to ensure /// the sequence is produced as per above. SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, const SDLoc &DL, SelectionDAG &DAG) const { EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDValue Chain = DAG.getEntryNode(); SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); SDValue Glue = Chain.getValue(1); return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); } SDValue AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { assert(Subtarget->isTargetELF() && "This function expects an ELF target"); if (getTargetMachine().getCodeModel() == CodeModel::Large) report_fatal_error("ELF TLS only supported in small memory model"); // Different choices can be made for the maximum size of the TLS area for a // module. For the small address model, the default TLS size is 16MiB and the // maximum TLS size is 4GiB. // FIXME: add -mtls-size command line option and make it control the 16MiB // vs. 4GiB code sequence generation. // FIXME: add tiny codemodel support. We currently generate the same code as // small, which may be larger than needed. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); if (!EnableAArch64ELFLocalDynamicTLSGeneration) { if (Model == TLSModel::LocalDynamic) Model = TLSModel::GeneralDynamic; } SDValue TPOff; EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDLoc DL(Op); const GlobalValue *GV = GA->getGlobal(); SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); if (Model == TLSModel::LocalExec) { SDValue HiVar = DAG.getTargetGlobalAddress( GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); SDValue LoVar = DAG.getTargetGlobalAddress( GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); SDValue TPWithOff_lo = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, HiVar, DAG.getTargetConstant(0, DL, MVT::i32)), 0); SDValue TPWithOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, LoVar, DAG.getTargetConstant(0, DL, MVT::i32)), 0); return TPWithOff; } else if (Model == TLSModel::InitialExec) { TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); } else if (Model == TLSModel::LocalDynamic) { // Local-dynamic accesses proceed in two phases. A general-dynamic TLS // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate // the beginning of the module's TLS region, followed by a DTPREL offset // calculation. // These accesses will need deduplicating if there's more than one. AArch64FunctionInfo *MFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); MFI->incNumLocalDynamicTLSAccesses(); // The call needs a relocation too for linker relaxation. It doesn't make // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of // the address. SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, AArch64II::MO_TLS); // Now we can calculate the offset from TPIDR_EL0 to this module's // thread-local area. TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); // Now use :dtprel_whatever: operations to calculate this variable's offset // in its thread-storage area. SDValue HiVar = DAG.getTargetGlobalAddress( GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); SDValue LoVar = DAG.getTargetGlobalAddress( GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, DAG.getTargetConstant(0, DL, MVT::i32)), 0); TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, DAG.getTargetConstant(0, DL, MVT::i32)), 0); } else if (Model == TLSModel::GeneralDynamic) { // The call needs a relocation too for linker relaxation. It doesn't make // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of // the address. SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); // Finally we can make a call to calculate the offset from tpidr_el0. TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); } else llvm_unreachable("Unsupported ELF TLS access model"); return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); } SDValue AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); SDValue Chain = DAG.getEntryNode(); EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDLoc DL(Op); SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); // Load the ThreadLocalStoragePointer from the TEB // A pointer to the TLS array is located at offset 0x58 from the TEB. SDValue TLSArray = DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); Chain = TLSArray.getValue(1); // Load the TLS index from the C runtime; // This does the same as getAddr(), but without having a GlobalAddressSDNode. // This also does the same as LOADgot, but using a generic i32 load, // while LOADgot only loads i64. SDValue TLSIndexHi = DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); SDValue TLSIndexLo = DAG.getTargetExternalSymbol( "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); SDValue TLSIndex = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); Chain = TLSIndex.getValue(1); // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 // offset into the TLSArray. TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, DAG.getConstant(3, DL, PtrVT)); SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), MachinePointerInfo()); Chain = TLS.getValue(1); const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); const GlobalValue *GV = GA->getGlobal(); SDValue TGAHi = DAG.getTargetGlobalAddress( GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); SDValue TGALo = DAG.getTargetGlobalAddress( GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); // Add the offset from the start of the .tls section (section base). SDValue Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, DAG.getTargetConstant(0, DL, MVT::i32)), 0); Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); return Addr; } SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); if (DAG.getTarget().useEmulatedTLS()) return LowerToTLSEmulatedModel(GA, DAG); if (Subtarget->isTargetDarwin()) return LowerDarwinGlobalTLSAddress(Op, DAG); if (Subtarget->isTargetELF()) return LowerELFGlobalTLSAddress(Op, DAG); if (Subtarget->isTargetWindows()) return LowerWindowsGlobalTLSAddress(Op, DAG); llvm_unreachable("Unexpected platform trying to use TLS"); } SDValue AArch64TargetLowering::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); MachineFunction &MF = DAG.getMachineFunction(); // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions // will not be produced, as they are conditional branch instructions that do // not set flags. bool ProduceNonFlagSettingCondBr = !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); // Handle f128 first, since lowering it will result in comparing the return // value of a libcall against zero, which is just what the rest of LowerBR_CC // is expecting to deal with. if (LHS.getValueType() == MVT::f128) { softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); // If softenSetCCOperands returned a scalar, we need to compare the result // against zero to select between true and false values. if (!RHS.getNode()) { RHS = DAG.getConstant(0, dl, LHS.getValueType()); CC = ISD::SETNE; } } // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch // instruction. if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { // Only lower legal XALUO ops. if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) return SDValue(); // The actual operation with overflow check. AArch64CC::CondCode OFCC; SDValue Value, Overflow; std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); if (CC == ISD::SETNE) OFCC = getInvertedCondCode(OFCC); SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Overflow); } if (LHS.getValueType().isInteger()) { assert((LHS.getValueType() == RHS.getValueType()) && (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); // If the RHS of the comparison is zero, we can potentially fold this // to a specialized branch. const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { if (CC == ISD::SETEQ) { // See if we can use a TBZ to fold in an AND as well. // TBZ has a smaller branch displacement than CBZ. If the offset is // out of bounds, a late MI-layer pass rewrites branches. // 403.gcc is an example that hits this case. if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(LHS.getOperand(1)) && isPowerOf2_64(LHS.getConstantOperandVal(1))) { SDValue Test = LHS.getOperand(0); uint64_t Mask = LHS.getConstantOperandVal(1); return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, DAG.getConstant(Log2_64(Mask), dl, MVT::i64), Dest); } return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); } else if (CC == ISD::SETNE) { // See if we can use a TBZ to fold in an AND as well. // TBZ has a smaller branch displacement than CBZ. If the offset is // out of bounds, a late MI-layer pass rewrites branches. // 403.gcc is an example that hits this case. if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(LHS.getOperand(1)) && isPowerOf2_64(LHS.getConstantOperandVal(1))) { SDValue Test = LHS.getOperand(0); uint64_t Mask = LHS.getConstantOperandVal(1); return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, DAG.getConstant(Log2_64(Mask), dl, MVT::i64), Dest); } return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { // Don't combine AND since emitComparison converts the AND to an ANDS // (a.k.a. TST) and the test in the test bit and branch instruction // becomes redundant. This would also increase register pressure. uint64_t Mask = LHS.getValueSizeInBits() - 1; return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, DAG.getConstant(Mask, dl, MVT::i64), Dest); } } if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { // Don't combine AND since emitComparison converts the AND to an ANDS // (a.k.a. TST) and the test in the test bit and branch instruction // becomes redundant. This would also increase register pressure. uint64_t Mask = LHS.getValueSizeInBits() - 1; return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, DAG.getConstant(Mask, dl, MVT::i64), Dest); } SDValue CCVal; SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, Cmp); } assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally // clean. Some of them require two branches to implement. SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); AArch64CC::CondCode CC1, CC2; changeFPCCToAArch64CC(CC, CC1, CC2); SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); SDValue BR1 = DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); if (CC2 != AArch64CC::AL) { SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, Cmp); } return BR1; } SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const { EVT VT = Op.getValueType(); SDLoc DL(Op); SDValue In1 = Op.getOperand(0); SDValue In2 = Op.getOperand(1); EVT SrcVT = In2.getValueType(); if (SrcVT.bitsLT(VT)) In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); else if (SrcVT.bitsGT(VT)) In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); EVT VecVT; uint64_t EltMask; SDValue VecVal1, VecVal2; auto setVecVal = [&] (int Idx) { if (!VT.isVector()) { VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, DAG.getUNDEF(VecVT), In1); VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, DAG.getUNDEF(VecVT), In2); } else { VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); } }; if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); EltMask = 0x80000000ULL; setVecVal(AArch64::ssub); } else if (VT == MVT::f64 || VT == MVT::v2f64) { VecVT = MVT::v2i64; // We want to materialize a mask with the high bit set, but the AdvSIMD // immediate moves cannot materialize that in a single instruction for // 64-bit elements. Instead, materialize zero and then negate it. EltMask = 0; setVecVal(AArch64::dsub); } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); EltMask = 0x8000ULL; setVecVal(AArch64::hsub); } else { llvm_unreachable("Invalid type for copysign!"); } SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); // If we couldn't materialize the mask above, then the mask vector will be // the zero vector, and we need to negate it here. if (VT == MVT::f64 || VT == MVT::v2f64) { BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); } SDValue Sel = DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); if (VT == MVT::f16) return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); if (VT == MVT::f32) return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); else if (VT == MVT::f64) return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); else return DAG.getNode(ISD::BITCAST, DL, VT, Sel); } SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { if (DAG.getMachineFunction().getFunction().hasFnAttribute( Attribute::NoImplicitFloat)) return SDValue(); if (!Subtarget->hasNEON()) return SDValue(); // While there is no integer popcount instruction, it can // be more efficiently lowered to the following sequence that uses // AdvSIMD registers/instructions as long as the copies to/from // the AdvSIMD registers are cheap. // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd // CNT V0.8B, V0.8B // 8xbyte pop-counts // ADDV B0, V0.8B // sum 8xbyte pop-counts // UMOV X0, V0.B[0] // copy byte result back to integer reg SDValue Val = Op.getOperand(0); SDLoc DL(Op); EVT VT = Op.getValueType(); if (VT == MVT::i32 || VT == MVT::i64) { if (VT == MVT::i32) Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); SDValue UaddLV = DAG.getNode( ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); if (VT == MVT::i64) UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); return UaddLV; } assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && "Unexpected type for custom ctpop lowering"); EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; Val = DAG.getBitcast(VT8Bit, Val); Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. unsigned EltSize = 8; unsigned NumElts = VT.is64BitVector() ? 8 : 16; while (EltSize != VT.getScalarSizeInBits()) { EltSize *= 2; NumElts /= 2; MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); Val = DAG.getNode( ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); } return Val; } SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG); SDValue LHS = Op.getOperand(0); SDValue RHS = Op.getOperand(1); ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); SDLoc dl(Op); // We chose ZeroOrOneBooleanContents, so use zero and one. EVT VT = Op.getValueType(); SDValue TVal = DAG.getConstant(1, dl, VT); SDValue FVal = DAG.getConstant(0, dl, VT); // Handle f128 first, since one possible outcome is a normal integer // comparison which gets picked up by the next if statement. if (LHS.getValueType() == MVT::f128) { softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); // If softenSetCCOperands returned a scalar, use it. if (!RHS.getNode()) { assert(LHS.getValueType() == Op.getValueType() && "Unexpected setcc expansion!"); return LHS; } } if (LHS.getValueType().isInteger()) { SDValue CCVal; SDValue Cmp = getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); // Note that we inverted the condition above, so we reverse the order of // the true and false operands here. This will allow the setcc to be // matched to a single CSINC instruction. return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); } // Now we know we're dealing with FP values. assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead // and do the comparison. SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); AArch64CC::CondCode CC1, CC2; changeFPCCToAArch64CC(CC, CC1, CC2); if (CC2 == AArch64CC::AL) { changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); // Note that we inverted the condition above, so we reverse the order of // the true and false operands here. This will allow the setcc to be // matched to a single CSINC instruction. return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); } else { // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't // totally clean. Some of them require two CSELs to implement. As is in // this case, we emit the first CSEL and then emit a second using the output // of the first as the RHS. We're effectively OR'ing the two CC's together. // FIXME: It would be nice if we could match the two CSELs to two CSINCs. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); } } SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, SDValue RHS, SDValue TVal, SDValue FVal, const SDLoc &dl, SelectionDAG &DAG) const { // Handle f128 first, because it will result in a comparison of some RTLIB // call result against zero. if (LHS.getValueType() == MVT::f128) { softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); // If softenSetCCOperands returned a scalar, we need to compare the result // against zero to select between true and false values. if (!RHS.getNode()) { RHS = DAG.getConstant(0, dl, LHS.getValueType()); CC = ISD::SETNE; } } // Also handle f16, for which we need to do a f32 comparison. if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); } // Next, handle integers. if (LHS.getValueType().isInteger()) { assert((LHS.getValueType() == RHS.getValueType()) && (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); unsigned Opcode = AArch64ISD::CSEL; // If both the TVal and the FVal are constants, see if we can swap them in // order to for a CSINV or CSINC out of them. ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { std::swap(TVal, FVal); std::swap(CTVal, CFVal); CC = ISD::getSetCCInverse(CC, true); } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { std::swap(TVal, FVal); std::swap(CTVal, CFVal); CC = ISD::getSetCCInverse(CC, true); } else if (TVal.getOpcode() == ISD::XOR) { // If TVal is a NOT we want to swap TVal and FVal so that we can match // with a CSINV rather than a CSEL. if (isAllOnesConstant(TVal.getOperand(1))) { std::swap(TVal, FVal); std::swap(CTVal, CFVal); CC = ISD::getSetCCInverse(CC, true); } } else if (TVal.getOpcode() == ISD::SUB) { // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so // that we can match with a CSNEG rather than a CSEL. if (isNullConstant(TVal.getOperand(0))) { std::swap(TVal, FVal); std::swap(CTVal, CFVal); CC = ISD::getSetCCInverse(CC, true); } } else if (CTVal && CFVal) { const int64_t TrueVal = CTVal->getSExtValue(); const int64_t FalseVal = CFVal->getSExtValue(); bool Swap = false; // If both TVal and FVal are constants, see if FVal is the // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC // instead of a CSEL in that case. if (TrueVal == ~FalseVal) { Opcode = AArch64ISD::CSINV; } else if (TrueVal == -FalseVal) { Opcode = AArch64ISD::CSNEG; } else if (TVal.getValueType() == MVT::i32) { // If our operands are only 32-bit wide, make sure we use 32-bit // arithmetic for the check whether we can use CSINC. This ensures that // the addition in the check will wrap around properly in case there is // an overflow (which would not be the case if we do the check with // 64-bit arithmetic). const uint32_t TrueVal32 = CTVal->getZExtValue(); const uint32_t FalseVal32 = CFVal->getZExtValue(); if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { Opcode = AArch64ISD::CSINC; if (TrueVal32 > FalseVal32) { Swap = true; } } // 64-bit check whether we can use CSINC. } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { Opcode = AArch64ISD::CSINC; if (TrueVal > FalseVal) { Swap = true; } } // Swap TVal and FVal if necessary. if (Swap) { std::swap(TVal, FVal); std::swap(CTVal, CFVal); CC = ISD::getSetCCInverse(CC, true); } if (Opcode != AArch64ISD::CSEL) { // Drop FVal since we can get its value by simply inverting/negating // TVal. FVal = TVal; } } // Avoid materializing a constant when possible by reusing a known value in // a register. However, don't perform this optimization if the known value // is one, zero or negative one in the case of a CSEL. We can always // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the // FVal, respectively. ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to // "a != C ? x : a" to avoid materializing C. if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) TVal = LHS; else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) FVal = LHS; } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { assert (CTVal && CFVal && "Expected constant operands for CSNEG."); // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to // avoid materializing C. AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { Opcode = AArch64ISD::CSINV; TVal = LHS; FVal = DAG.getConstant(0, dl, FVal.getValueType()); } } SDValue CCVal; SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); EVT VT = TVal.getValueType(); return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); } // Now we know we're dealing with FP values. assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); assert(LHS.getValueType() == RHS.getValueType()); EVT VT = TVal.getValueType(); SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally // clean. Some of them require two CSELs to implement. AArch64CC::CondCode CC1, CC2; changeFPCCToAArch64CC(CC, CC1, CC2); if (DAG.getTarget().Options.UnsafeFPMath) { // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); if (RHSVal && RHSVal->isZero()) { ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) TVal = LHS; else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && CFVal && CFVal->isZero() && FVal.getValueType() == LHS.getValueType()) FVal = LHS; } } // Emit first, and possibly only, CSEL. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); // If we need a second CSEL, emit it, using the output of the first as the // RHS. We're effectively OR'ing the two CC's together. if (CC2 != AArch64CC::AL) { SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); } // Otherwise, return the output of the first CSEL. return CS1; } SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); SDValue LHS = Op.getOperand(0); SDValue RHS = Op.getOperand(1); SDValue TVal = Op.getOperand(2); SDValue FVal = Op.getOperand(3); SDLoc DL(Op); return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); } SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { SDValue CCVal = Op->getOperand(0); SDValue TVal = Op->getOperand(1); SDValue FVal = Op->getOperand(2); SDLoc DL(Op); // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select // instruction. if (isOverflowIntrOpRes(CCVal)) { // Only lower legal XALUO ops. if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) return SDValue(); AArch64CC::CondCode OFCC; SDValue Value, Overflow; std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal, Overflow); } // Lower it the same way as we would lower a SELECT_CC node. ISD::CondCode CC; SDValue LHS, RHS; if (CCVal.getOpcode() == ISD::SETCC) { LHS = CCVal.getOperand(0); RHS = CCVal.getOperand(1); CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); } else { LHS = CCVal; RHS = DAG.getConstant(0, DL, CCVal.getValueType()); CC = ISD::SETNE; } return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); } SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { // Jump table entries as PC relative offsets. No additional tweaking // is necessary here. Just get the address of the jump table. JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); if (getTargetMachine().getCodeModel() == CodeModel::Large && !Subtarget->isTargetMachO()) { return getAddrLarge(JT, DAG); } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { return getAddrTiny(JT, DAG); } return getAddr(JT, DAG); } SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const { // Jump table entries as PC relative offsets. No additional tweaking // is necessary here. Just get the address of the jump table. SDLoc DL(Op); SDValue JT = Op.getOperand(1); SDValue Entry = Op.getOperand(2); int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); SDNode *Dest = DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), SDValue(Dest, 0)); } SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); if (getTargetMachine().getCodeModel() == CodeModel::Large) { // Use the GOT for the large code model on iOS. if (Subtarget->isTargetMachO()) { return getGOT(CP, DAG); } return getAddrLarge(CP, DAG); } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { return getAddrTiny(CP, DAG); } else { return getAddr(CP, DAG); } } SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); if (getTargetMachine().getCodeModel() == CodeModel::Large && !Subtarget->isTargetMachO()) { return getAddrLarge(BA, DAG); } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { return getAddrTiny(BA, DAG); } return getAddr(BA, DAG); } SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, SelectionDAG &DAG) const { AArch64FunctionInfo *FuncInfo = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); SDLoc DL(Op); SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy(DAG.getDataLayout())); const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), MachinePointerInfo(SV)); } SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, SelectionDAG &DAG) const { AArch64FunctionInfo *FuncInfo = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); SDLoc DL(Op); SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 ? FuncInfo->getVarArgsGPRIndex() : FuncInfo->getVarArgsStackIndex(), getPointerTy(DAG.getDataLayout())); const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), MachinePointerInfo(SV)); } SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, SelectionDAG &DAG) const { // The layout of the va_list struct is specified in the AArch64 Procedure Call // Standard, section B.3. MachineFunction &MF = DAG.getMachineFunction(); AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); auto PtrVT = getPointerTy(DAG.getDataLayout()); SDLoc DL(Op); SDValue Chain = Op.getOperand(0); SDValue VAList = Op.getOperand(1); const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); SmallVector<SDValue, 4> MemOps; // void *__stack at offset 0 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, MachinePointerInfo(SV), /* Alignment = */ 8)); // void *__gr_top at offset 8 int GPRSize = FuncInfo->getVarArgsGPRSize(); if (GPRSize > 0) { SDValue GRTop, GRTopAddr; GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, DAG.getConstant(GPRSize, DL, PtrVT)); MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, MachinePointerInfo(SV, 8), /* Alignment = */ 8)); } // void *__vr_top at offset 16 int FPRSize = FuncInfo->getVarArgsFPRSize(); if (FPRSize > 0) { SDValue VRTop, VRTopAddr; VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(16, DL, PtrVT)); VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, DAG.getConstant(FPRSize, DL, PtrVT)); MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, MachinePointerInfo(SV, 16), /* Alignment = */ 8)); } // int __gr_offs at offset 24 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); MemOps.push_back(DAG.getStore( Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, MachinePointerInfo(SV, 24), /* Alignment = */ 4)); // int __vr_offs at offset 28 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); MemOps.push_back(DAG.getStore( Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, MachinePointerInfo(SV, 28), /* Alignment = */ 4)); return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); } SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const { MachineFunction &MF = DAG.getMachineFunction(); if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) return LowerWin64_VASTART(Op, DAG); else if (Subtarget->isTargetDarwin()) return LowerDarwin_VASTART(Op, DAG); else return LowerAAPCS_VASTART(Op, DAG); } SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const { // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single // pointer. SDLoc DL(Op); unsigned VaListSize = Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32; const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2), DAG.getConstant(VaListSize, DL, MVT::i32), 8, false, false, false, MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV)); } SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { assert(Subtarget->isTargetDarwin() && "automatic va_arg instruction only works on Darwin"); const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); EVT VT = Op.getValueType(); SDLoc DL(Op); SDValue Chain = Op.getOperand(0); SDValue Addr = Op.getOperand(1); unsigned Align = Op.getConstantOperandVal(3); auto PtrVT = getPointerTy(DAG.getDataLayout()); SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V)); Chain = VAList.getValue(1); if (Align > 8) { assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(Align - 1, DL, PtrVT)); VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, DAG.getConstant(-(int64_t)Align, DL, PtrVT)); } Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); // Scalar integer and FP values smaller than 64 bits are implicitly extended // up to 64 bits. At the very least, we have to increase the striding of the // vaargs list to match this, and for FP values we need to introduce // FP_ROUND nodes as well. if (VT.isInteger() && !VT.isVector()) ArgSize = 8; bool NeedFPTrunc = false; if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { ArgSize = 8; NeedFPTrunc = true; } // Increment the pointer, VAList, to the next vaarg SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(ArgSize, DL, PtrVT)); // Store the incremented VAList to the legalized pointer SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); // Load the actual argument out of the pointer VAList if (NeedFPTrunc) { // Load the value as an f64. SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); // Round the value down to an f32. SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), DAG.getIntPtrConstant(1, DL)); SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; // Merge the rounded value with the chain output of the load. return DAG.getMergeValues(Ops, DL); } return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); } SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); MFI.setFrameAddressIsTaken(true); EVT VT = Op.getValueType(); SDLoc DL(Op); unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); while (Depth--) FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, MachinePointerInfo()); return FrameAddr; } SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const { MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); EVT VT = getPointerTy(DAG.getDataLayout()); SDLoc DL(Op); int FI = MFI.CreateFixedObject(4, 0, false); return DAG.getFrameIndex(FI, VT); } #define GET_REGISTER_MATCHER #include "AArch64GenAsmMatcher.inc" // FIXME? Maybe this could be a TableGen attribute on some registers and // this table could be generated automatically from RegInfo. unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, SelectionDAG &DAG) const { unsigned Reg = MatchRegisterName(RegName); if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); if (!Subtarget->isXRegisterReserved(DwarfRegNum)) Reg = 0; } if (Reg) return Reg; report_fatal_error(Twine("Invalid register name \"" + StringRef(RegName) + "\".")); } SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, SelectionDAG &DAG) const { DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); EVT VT = Op.getValueType(); SDLoc DL(Op); SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); } SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const { MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo &MFI = MF.getFrameInfo(); MFI.setReturnAddressIsTaken(true); EVT VT = Op.getValueType(); SDLoc DL(Op); unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); if (Depth) { SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); return DAG.getLoad(VT, DL, DAG.getEntryNode(), DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo()); } // Return LR, which contains the return address. Mark it an implicit live-in. unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); } /// LowerShiftRightParts - Lower SRA_PARTS, which returns two /// i64 values and take a 2 x i64 value to shift plus a shift amount. SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG) const { assert(Op.getNumOperands() == 3 && "Not a double-shift!"); EVT VT = Op.getValueType(); unsigned VTBits = VT.getSizeInBits(); SDLoc dl(Op); SDValue ShOpLo = Op.getOperand(0); SDValue ShOpHi = Op.getOperand(1); SDValue ShAmt = Op.getOperand(2); unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which // is "undef". We wanted 0, so CSEL it directly. SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETEQ, dl, DAG); SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); HiBitsForLo = DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), HiBitsForLo, CCVal, Cmp); SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, DAG.getConstant(VTBits, dl, MVT::i64)); SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); SDValue LoForNormalShift = DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, dl, DAG); CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, LoForNormalShift, CCVal, Cmp); // AArch64 shifts larger than the register width are wrapped rather than // clamped, so we can't just emit "hi >> x". SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); SDValue HiForBigShift = Opc == ISD::SRA ? DAG.getNode(Opc, dl, VT, ShOpHi, DAG.getConstant(VTBits - 1, dl, MVT::i64)) : DAG.getConstant(0, dl, VT); SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, HiForNormalShift, CCVal, Cmp); SDValue Ops[2] = { Lo, Hi }; return DAG.getMergeValues(Ops, dl); } /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two /// i64 values and take a 2 x i64 value to shift plus a shift amount. SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, SelectionDAG &DAG) const { assert(Op.getNumOperands() == 3 && "Not a double-shift!"); EVT VT = Op.getValueType(); unsigned VTBits = VT.getSizeInBits(); SDLoc dl(Op); SDValue ShOpLo = Op.getOperand(0); SDValue ShOpHi = Op.getOperand(1); SDValue ShAmt = Op.getOperand(2); assert(Op.getOpcode() == ISD::SHL_PARTS); SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which // is "undef". We wanted 0, so CSEL it directly. SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETEQ, dl, DAG); SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); LoBitsForHi = DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), LoBitsForHi, CCVal, Cmp); SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, DAG.getConstant(VTBits, dl, MVT::i64)); SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); SDValue HiForNormalShift = DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, dl, DAG); CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, HiForNormalShift, CCVal, Cmp); // AArch64 shifts of larger than register sizes are wrapped rather than // clamped, so we can't just emit "lo << a" if a is too big. SDValue LoForBigShift = DAG.getConstant(0, dl, VT); SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, LoForNormalShift, CCVal, Cmp); SDValue Ops[2] = { Lo, Hi }; return DAG.getMergeValues(Ops, dl); } bool AArch64TargetLowering::isOffsetFoldingLegal( const GlobalAddressSDNode *GA) const { // Offsets are folded in the DAG combine rather than here so that we can // intelligently choose an offset based on the uses. return false; } bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, bool OptForSize) const { bool IsLegal = false; // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and // 16-bit case when target has full fp16 support. // FIXME: We should be able to handle f128 as well with a clever lowering. const APInt ImmInt = Imm.bitcastToAPInt(); if (VT == MVT::f64) IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); else if (VT == MVT::f32) IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); else if (VT == MVT::f16 && Subtarget->hasFullFP16()) IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to // generate that fmov. // If we can not materialize in immediate field for fmov, check if the // value can be encoded as the immediate operand of a logical instruction. // The immediate value will be created with either MOVZ, MOVN, or ORR. if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; // however the mov+fmov sequence is always better because of the reduced // cache pressure. The timings are still the same if you consider // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the // movw+movk is fused). So we limit up to 2 instrdduction at most. SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), Insn); unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); IsLegal = Insn.size() <= Limit; } LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() << " imm value: "; Imm.dump();); return IsLegal; } //===----------------------------------------------------------------------===// // AArch64 Optimization Hooks //===----------------------------------------------------------------------===// static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, SDValue Operand, SelectionDAG &DAG, int &ExtraSteps) { EVT VT = Operand.getValueType(); if (ST->hasNEON() && (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || VT == MVT::f32 || VT == MVT::v1f32 || VT == MVT::v2f32 || VT == MVT::v4f32)) { if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) // For the reciprocal estimates, convergence is quadratic, so the number // of digits is doubled after each iteration. In ARMv8, the accuracy of // the initial estimate is 2^-8. Thus the number of extra steps to refine // the result for float (23 mantissa bits) is 2 and for double (52 // mantissa bits) is 3. ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); } return SDValue(); } SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &ExtraSteps, bool &UseOneConst, bool Reciprocal) const { if (Enabled == ReciprocalEstimate::Enabled || (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, DAG, ExtraSteps)) { SDLoc DL(Operand); EVT VT = Operand.getValueType(); SDNodeFlags Flags; Flags.setAllowReassociation(true); // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) for (int i = ExtraSteps; i > 0; --i) { SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, Flags); Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); } if (!Reciprocal) { EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); // Correct the result if the operand is 0.0. Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, Eq, Operand, Estimate); } ExtraSteps = 0; return Estimate; } return SDValue(); } SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG, int Enabled, int &ExtraSteps) const { if (Enabled == ReciprocalEstimate::Enabled) if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, DAG, ExtraSteps)) { SDLoc DL(Operand); EVT VT = Operand.getValueType(); SDNodeFlags Flags; Flags.setAllowReassociation(true); // Newton reciprocal iteration: E * (2 - X * E) // AArch64 reciprocal iteration instruction: (2 - M * N) for (int i = ExtraSteps; i > 0; --i) { SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, Estimate, Flags); Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); } ExtraSteps = 0; return Estimate; } return SDValue(); } //===----------------------------------------------------------------------===// // AArch64 Inline Assembly Support //===----------------------------------------------------------------------===// // Table of Constraints // TODO: This is the current set of constraints supported by ARM for the // compiler, not all of them may make sense. // // r - A general register // w - An FP/SIMD register of some size in the range v0-v31 // x - An FP/SIMD register of some size in the range v0-v15 // I - Constant that can be used with an ADD instruction // J - Constant that can be used with a SUB instruction // K - Constant that can be used with a 32-bit logical instruction // L - Constant that can be used with a 64-bit logical instruction // M - Constant that can be used as a 32-bit MOV immediate // N - Constant that can be used as a 64-bit MOV immediate // Q - A memory reference with base register and no offset // S - A symbolic address // Y - Floating point constant zero // Z - Integer constant zero // // Note that general register operands will be output using their 64-bit x // register name, whatever the size of the variable, unless the asm operand // is prefixed by the %w modifier. Floating-point and SIMD register operands // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or // %q modifier. const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { // At this point, we have to lower this constraint to something else, so we // lower it to an "r" or "w". However, by doing this we will force the result // to be in register, while the X constraint is much more permissive. // // Although we are correct (we are free to emit anything, without // constraints), we might break use cases that would expect us to be more // efficient and emit something else. if (!Subtarget->hasFPARMv8()) return "r"; if (ConstraintVT.isFloatingPoint()) return "w"; if (ConstraintVT.isVector() && (ConstraintVT.getSizeInBits() == 64 || ConstraintVT.getSizeInBits() == 128)) return "w"; return "r"; } /// getConstraintType - Given a constraint letter, return the type of /// constraint it is for this target. AArch64TargetLowering::ConstraintType AArch64TargetLowering::getConstraintType(StringRef Constraint) const { if (Constraint.size() == 1) { switch (Constraint[0]) { default: break; case 'z': return C_Other; case 'x': case 'w': return C_RegisterClass; // An address with a single base register. Due to the way we // currently handle addresses it is the same as 'r'. case 'Q': return C_Memory; case 'S': // A symbolic address return C_Other; } } return TargetLowering::getConstraintType(Constraint); } /// Examine constraint type and operand type and determine a weight value. /// This object must already have been set up with the operand type /// and the current alternative constraint selected. TargetLowering::ConstraintWeight AArch64TargetLowering::getSingleConstraintMatchWeight( AsmOperandInfo &info, const char *constraint) const { ConstraintWeight weight = CW_Invalid; Value *CallOperandVal = info.CallOperandVal; // If we don't have a value, we can't do a match, // but allow it at the lowest weight. if (!CallOperandVal) return CW_Default; Type *type = CallOperandVal->getType(); // Look at the constraint type. switch (*constraint) { default: weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); break; case 'x': case 'w': if (type->isFloatingPointTy() || type->isVectorTy()) weight = CW_Register; break; case 'z': weight = CW_Constant; break; } return weight; } std::pair<unsigned, const TargetRegisterClass *> AArch64TargetLowering::getRegForInlineAsmConstraint( const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { if (Constraint.size() == 1) { switch (Constraint[0]) { case 'r': if (VT.getSizeInBits() == 64) return std::make_pair(0U, &AArch64::GPR64commonRegClass); return std::make_pair(0U, &AArch64::GPR32commonRegClass); case 'w': if (!Subtarget->hasFPARMv8()) break; if (VT.getSizeInBits() == 16) return std::make_pair(0U, &AArch64::FPR16RegClass); if (VT.getSizeInBits() == 32) return std::make_pair(0U, &AArch64::FPR32RegClass); if (VT.getSizeInBits() == 64) return std::make_pair(0U, &AArch64::FPR64RegClass); if (VT.getSizeInBits() == 128) return std::make_pair(0U, &AArch64::FPR128RegClass); break; // The instructions that this constraint is designed for can // only take 128-bit registers so just use that regclass. case 'x': if (!Subtarget->hasFPARMv8()) break; if (VT.getSizeInBits() == 128) return std::make_pair(0U, &AArch64::FPR128_loRegClass); break; } } if (StringRef("{cc}").equals_lower(Constraint)) return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); // Use the default implementation in TargetLowering to convert the register // constraint into a member of a register class. std::pair<unsigned, const TargetRegisterClass *> Res; Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); // Not found as a standard register? if (!Res.second) { unsigned Size = Constraint.size(); if ((Size == 4 || Size == 5) && Constraint[0] == '{' && tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { int RegNo; bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); if (!Failed && RegNo >= 0 && RegNo <= 31) { // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. // By default we'll emit v0-v31 for this unless there's a modifier where // we'll emit the correct register as well. if (VT != MVT::Other && VT.getSizeInBits() == 64) { Res.first = AArch64::FPR64RegClass.getRegister(RegNo); Res.second = &AArch64::FPR64RegClass; } else { Res.first = AArch64::FPR128RegClass.getRegister(RegNo); Res.second = &AArch64::FPR128RegClass; } } } } if (Res.second && !Subtarget->hasFPARMv8() && !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) return std::make_pair(0U, nullptr); return Res; } /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops /// vector. If it is invalid, don't add anything to Ops. void AArch64TargetLowering::LowerAsmOperandForConstraint( SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, SelectionDAG &DAG) const { SDValue Result; // Currently only support length 1 constraints. if (Constraint.length() != 1) return; char ConstraintLetter = Constraint[0]; switch (ConstraintLetter) { default: break; // This set of constraints deal with valid constants for various instructions. // Validate and return a target constant for them if we can. case 'z': { // 'z' maps to xzr or wzr so it needs an input of 0. if (!isNullConstant(Op)) return; if (Op.getValueType() == MVT::i64) Result = DAG.getRegister(AArch64::XZR, MVT::i64); else Result = DAG.getRegister(AArch64::WZR, MVT::i32); break; } case 'S': { // An absolute symbolic address or label reference. if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), GA->getValueType(0)); } else if (const BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(Op)) { Result = DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); } else if (const ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) { Result = DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); } else return; break; } case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); if (!C) return; // Grab the value and do some validation. uint64_t CVal = C->getZExtValue(); switch (ConstraintLetter) { // The I constraint applies only to simple ADD or SUB immediate operands: // i.e. 0 to 4095 with optional shift by 12 // The J constraint applies only to ADD or SUB immediates that would be // valid when negated, i.e. if [an add pattern] were to be output as a SUB // instruction [or vice versa], in other words -1 to -4095 with optional // left shift by 12. case 'I': if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) break; return; case 'J': { uint64_t NVal = -C->getSExtValue(); if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { CVal = C->getSExtValue(); break; } return; } // The K and L constraints apply *only* to logical immediates, including // what used to be the MOVI alias for ORR (though the MOVI alias has now // been removed and MOV should be used). So these constraints have to // distinguish between bit patterns that are valid 32-bit or 64-bit // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice // versa. case 'K': if (AArch64_AM::isLogicalImmediate(CVal, 32)) break; return; case 'L': if (AArch64_AM::isLogicalImmediate(CVal, 64)) break; return; // The M and N constraints are a superset of K and L respectively, for use // with the MOV (immediate) alias. As well as the logical immediates they // also match 32 or 64-bit immediates that can be loaded either using a // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca // (M) or 64-bit 0x1234000000000000 (N) etc. // As a note some of this code is liberally stolen from the asm parser. case 'M': { if (!isUInt<32>(CVal)) return; if (AArch64_AM::isLogicalImmediate(CVal, 32)) break; if ((CVal & 0xFFFF) == CVal) break; if ((CVal & 0xFFFF0000ULL) == CVal) break; uint64_t NCVal = ~(uint32_t)CVal; if ((NCVal & 0xFFFFULL) == NCVal) break; if ((NCVal & 0xFFFF0000ULL) == NCVal) break; return; } case 'N': { if (AArch64_AM::isLogicalImmediate(CVal, 64)) break; if ((CVal & 0xFFFFULL) == CVal) break; if ((CVal & 0xFFFF0000ULL) == CVal) break; if ((CVal & 0xFFFF00000000ULL) == CVal) break; if ((CVal & 0xFFFF000000000000ULL) == CVal) break; uint64_t NCVal = ~CVal; if ((NCVal & 0xFFFFULL) == NCVal) break; if ((NCVal & 0xFFFF0000ULL) == NCVal) break; if ((NCVal & 0xFFFF00000000ULL) == NCVal) break; if ((NCVal & 0xFFFF000000000000ULL) == NCVal) break; return; } default: return; } // All assembler immediates are 64-bit integers. Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); break; } if (Result.getNode()) { Ops.push_back(Result); return; } return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); } //===----------------------------------------------------------------------===// // AArch64 Advanced SIMD Support //===----------------------------------------------------------------------===// /// WidenVector - Given a value in the V64 register class, produce the /// equivalent value in the V128 register class. static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { EVT VT = V64Reg.getValueType(); unsigned NarrowSize = VT.getVectorNumElements(); MVT EltTy = VT.getVectorElementType().getSimpleVT(); MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); SDLoc DL(V64Reg); return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), V64Reg, DAG.getConstant(0, DL, MVT::i32)); } /// getExtFactor - Determine the adjustment factor for the position when /// generating an "extract from vector registers" instruction. static unsigned getExtFactor(SDValue &V) { EVT EltType = V.getValueType().getVectorElementType(); return EltType.getSizeInBits() / 8; } /// NarrowVector - Given a value in the V128 register class, produce the /// equivalent value in the V64 register class. static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { EVT VT = V128Reg.getValueType(); unsigned WideSize = VT.getVectorNumElements(); MVT EltTy = VT.getVectorElementType().getSimpleVT(); MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); SDLoc DL(V128Reg); return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); } // Gather data to see if the operation can be modelled as a // shuffle in combination with VEXTs. SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, SelectionDAG &DAG) const { assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); SDLoc dl(Op); EVT VT = Op.getValueType(); unsigned NumElts = VT.getVectorNumElements(); struct ShuffleSourceInfo { SDValue Vec; unsigned MinElt; unsigned MaxElt; // We may insert some combination of BITCASTs and VEXT nodes to force Vec to // be compatible with the shuffle we intend to construct. As a result // ShuffleVec will be some sliding window into the original Vec. SDValue ShuffleVec; // Code should guarantee that element i in Vec starts at element "WindowBase // + i * WindowScale in ShuffleVec". int WindowBase; int WindowScale; ShuffleSourceInfo(SDValue Vec) : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } }; // First gather all vectors used as an immediate source for this BUILD_VECTOR // node. SmallVector<ShuffleSourceInfo, 2> Sources; for (unsigned i = 0; i < NumElts; ++i) { SDValue V = Op.getOperand(i); if (V.isUndef()) continue; else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || !isa<ConstantSDNode>(V.getOperand(1))) { LLVM_DEBUG( dbgs() << "Reshuffle failed: " "a shuffle can only come from building a vector from " "various elements of other vectors, provided their " "indices are constant\n"); return SDValue(); } // Add this element source to the list if it's not already there. SDValue SourceVec = V.getOperand(0); auto Source = find(Sources, SourceVec); if (Source == Sources.end()) Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); // Update the minimum and maximum lane number seen. unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); Source->MinElt = std::min(Source->MinElt, EltNo); Source->MaxElt = std::max(Source->MaxElt, EltNo); } if (Sources.size() > 2) { LLVM_DEBUG( dbgs() << "Reshuffle failed: currently only do something sane when at " "most two source vectors are involved\n"); return SDValue(); } // Find out the smallest element size among result and two sources, and use // it as element size to build the shuffle_vector. EVT SmallestEltTy = VT.getVectorElementType(); for (auto &Source : Sources) { EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); if (SrcEltTy.bitsLT(SmallestEltTy)) { SmallestEltTy = SrcEltTy; } } unsigned ResMultiplier = VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); // If the source vector is too wide or too narrow, we may nevertheless be able // to construct a compatible shuffle either by concatenating it with UNDEF or // extracting a suitable range of elements. for (auto &Src : Sources) { EVT SrcVT = Src.ShuffleVec.getValueType(); if (SrcVT.getSizeInBits() == VT.getSizeInBits()) continue; // This stage of the search produces a source with the same element type as // the original, but with a total width matching the BUILD_VECTOR output. EVT EltVT = SrcVT.getVectorElementType(); unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); // We can pad out the smaller vector for free, so if it's part of a // shuffle... Src.ShuffleVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, DAG.getUNDEF(Src.ShuffleVec.getValueType())); continue; } assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); if (Src.MaxElt - Src.MinElt >= NumSrcElts) { LLVM_DEBUG( dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); return SDValue(); } if (Src.MinElt >= NumSrcElts) { // The extraction can just take the second half Src.ShuffleVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, DAG.getConstant(NumSrcElts, dl, MVT::i64)); Src.WindowBase = -NumSrcElts; } else if (Src.MaxElt < NumSrcElts) { // The extraction can just take the first half Src.ShuffleVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, DAG.getConstant(0, dl, MVT::i64)); } else { // An actual VEXT is needed SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, DAG.getConstant(0, dl, MVT::i64)); SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, DAG.getConstant(NumSrcElts, dl, MVT::i64)); unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, VEXTSrc2, DAG.getConstant(Imm, dl, MVT::i32)); Src.WindowBase = -Src.MinElt; } } // Another possible incompatibility occurs from the vector element types. We // can fix this by bitcasting the source vectors to the same type we intend // for the shuffle. for (auto &Src : Sources) { EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); if (SrcEltTy == SmallestEltTy) continue; assert(ShuffleVT.getVectorElementType() == SmallestEltTy); Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); Src.WindowBase *= Src.WindowScale; } // Final sanity check before we try to actually produce a shuffle. LLVM_DEBUG(for (auto Src : Sources) assert(Src.ShuffleVec.getValueType() == ShuffleVT);); // The stars all align, our next step is to produce the mask for the shuffle. SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { SDValue Entry = Op.getOperand(i); if (Entry.isUndef()) continue; auto Src = find(Sources, Entry.getOperand(0)); int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit // trunc. So only std::min(SrcBits, DestBits) actually get defined in this // segment. EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); int BitsDefined = std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); int LanesDefined = BitsDefined / BitsPerShuffleLane; // This source is expected to fill ResMultiplier lanes of the final shuffle, // starting at the appropriate offset. int *LaneMask = &Mask[i * ResMultiplier]; int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; ExtractBase += NumElts * (Src - Sources.begin()); for (int j = 0; j < LanesDefined; ++j) LaneMask[j] = ExtractBase + j; } // Final check before we try to produce nonsense... if (!isShuffleMaskLegal(Mask, ShuffleVT)) { LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); return SDValue(); } SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; for (unsigned i = 0; i < Sources.size(); ++i) ShuffleOps[i] = Sources[i].ShuffleVec; SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], ShuffleOps[1], Mask); SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); dbgs() << "Reshuffle, creating node: "; V.dump();); return V; } // check if an EXT instruction can handle the shuffle mask when the // vector sources of the shuffle are the same. static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { unsigned NumElts = VT.getVectorNumElements(); // Assume that the first shuffle index is not UNDEF. Fail if it is. if (M[0] < 0) return false; Imm = M[0]; // If this is a VEXT shuffle, the immediate value is the index of the first // element. The other shuffle indices must be the successive elements after // the first one. unsigned ExpectedElt = Imm; for (unsigned i = 1; i < NumElts; ++i) { // Increment the expected index. If it wraps around, just follow it // back to index zero and keep going. ++ExpectedElt; if (ExpectedElt == NumElts) ExpectedElt = 0; if (M[i] < 0) continue; // ignore UNDEF indices if (ExpectedElt != static_cast<unsigned>(M[i])) return false; } return true; } // check if an EXT instruction can handle the shuffle mask when the // vector sources of the shuffle are different. static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, unsigned &Imm) { // Look for the first non-undef element. const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); // Benefit form APInt to handle overflow when calculating expected element. unsigned NumElts = VT.getVectorNumElements(); unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); // The following shuffle indices must be the successive elements after the // first real element. const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); if (FirstWrongElt != M.end()) return false; // The index of an EXT is the first element if it is not UNDEF. // Watch out for the beginning UNDEFs. The EXT index should be the expected // value of the first element. E.g. // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. // ExpectedElt is the last mask index plus 1. Imm = ExpectedElt.getZExtValue(); // There are two difference cases requiring to reverse input vectors. // For example, for vector <4 x i32> we have the following cases, // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) // For both cases, we finally use mask <5, 6, 7, 0>, which requires // to reverse two input vectors. if (Imm < NumElts) ReverseEXT = true; else Imm -= NumElts; return true; } /// isREVMask - Check if a vector shuffle corresponds to a REV /// instruction with the specified blocksize. (The order of the elements /// within each block of the vector is reversed.) static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && "Only possible block sizes for REV are: 16, 32, 64"); unsigned EltSz = VT.getScalarSizeInBits(); if (EltSz == 64) return false; unsigned NumElts = VT.getVectorNumElements(); unsigned BlockElts = M[0] + 1; // If the first shuffle index is UNDEF, be optimistic. if (M[0] < 0) BlockElts = BlockSize / EltSz; if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) return false; for (unsigned i = 0; i < NumElts; ++i) { if (M[i] < 0) continue; // ignore UNDEF indices if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) return false; } return true; } static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { unsigned NumElts = VT.getVectorNumElements(); WhichResult = (M[0] == 0 ? 0 : 1); unsigned Idx = WhichResult * NumElts / 2; for (unsigned i = 0; i != NumElts; i += 2) { if ((M[i] >= 0 && (unsigned)M[i] != Idx) || (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) return false; Idx += 1; } return true; } static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { unsigned NumElts = VT.getVectorNumElements(); WhichResult = (M[0] == 0 ? 0 : 1); for (unsigned i = 0; i != NumElts; ++i) { if (M[i] < 0) continue; // ignore UNDEF indices if ((unsigned)M[i] != 2 * i + WhichResult) return false; } return true; } static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { unsigned NumElts = VT.getVectorNumElements(); WhichResult = (M[0] == 0 ? 0 : 1); for (unsigned i = 0; i < NumElts; i += 2) { if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) return false; } return true; } /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { unsigned NumElts = VT.getVectorNumElements(); WhichResult = (M[0] == 0 ? 0 : 1); unsigned Idx = WhichResult * NumElts / 2; for (unsigned i = 0; i != NumElts; i += 2) { if ((M[i] >= 0 && (unsigned)M[i] != Idx) || (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) return false; Idx += 1; } return true; } /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { unsigned Half = VT.getVectorNumElements() / 2; WhichResult = (M[0] == 0 ? 0 : 1); for (unsigned j = 0; j != 2; ++j) { unsigned Idx = WhichResult; for (unsigned i = 0; i != Half; ++i) { int MIdx = M[i + j * Half]; if (MIdx >= 0 && (unsigned)MIdx != Idx) return false; Idx += 2; } } return true; } /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { unsigned NumElts = VT.getVectorNumElements(); WhichResult = (M[0] == 0 ? 0 : 1); for (unsigned i = 0; i < NumElts; i += 2) { if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) return false; } return true; } static bool isINSMask(ArrayRef<int> M, int NumInputElements, bool &DstIsLeft, int &Anomaly) { if (M.size() != static_cast<size_t>(NumInputElements)) return false; int NumLHSMatch = 0, NumRHSMatch = 0; int LastLHSMismatch = -1, LastRHSMismatch = -1; for (int i = 0; i < NumInputElements; ++i) { if (M[i] == -1) { ++NumLHSMatch; ++NumRHSMatch; continue; } if (M[i] == i) ++NumLHSMatch; else LastLHSMismatch = i; if (M[i] == i + NumInputElements) ++NumRHSMatch; else LastRHSMismatch = i; } if (NumLHSMatch == NumInputElements - 1) { DstIsLeft = true; Anomaly = LastLHSMismatch; return true; } else if (NumRHSMatch == NumInputElements - 1) { DstIsLeft = false; Anomaly = LastRHSMismatch; return true; } return false; } static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { if (VT.getSizeInBits() != 128) return false; unsigned NumElts = VT.getVectorNumElements(); for (int I = 0, E = NumElts / 2; I != E; I++) { if (Mask[I] != I) return false; } int Offset = NumElts / 2; for (int I = NumElts / 2, E = NumElts; I != E; I++) { if (Mask[I] != I + SplitLHS * Offset) return false; } return true; } static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { SDLoc DL(Op); EVT VT = Op.getValueType(); SDValue V0 = Op.getOperand(0); SDValue V1 = Op.getOperand(1); ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || VT.getVectorElementType() != V1.getValueType().getVectorElementType()) return SDValue(); bool SplitV0 = V0.getValueSizeInBits() == 128; if (!isConcatMask(Mask, VT, SplitV0)) return SDValue(); EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), VT.getVectorNumElements() / 2); if (SplitV0) { V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, DAG.getConstant(0, DL, MVT::i64)); } if (V1.getValueSizeInBits() == 128) { V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, DAG.getConstant(0, DL, MVT::i64)); } return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); } /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit /// the specified operations to build the shuffle. static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, SDValue RHS, SelectionDAG &DAG, const SDLoc &dl) { unsigned OpNum = (PFEntry >> 26) & 0x0F; unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); enum { OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> OP_VREV, OP_VDUP0, OP_VDUP1, OP_VDUP2, OP_VDUP3, OP_VEXT1, OP_VEXT2, OP_VEXT3, OP_VUZPL, // VUZP, left result OP_VUZPR, // VUZP, right result OP_VZIPL, // VZIP, left result OP_VZIPR, // VZIP, right result OP_VTRNL, // VTRN, left result OP_VTRNR // VTRN, right result }; if (OpNum == OP_COPY) { if (LHSID == (1 * 9 + 2) * 9 + 3) return LHS; assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); return RHS; } SDValue OpLHS, OpRHS; OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); EVT VT = OpLHS.getValueType(); switch (OpNum) { default: llvm_unreachable("Unknown shuffle opcode!"); case OP_VREV: // VREV divides the vector in half and swaps within the half. if (VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::f32) return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); // vrev <4 x i16> -> REV32 if (VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::f16) return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); // vrev <4 x i8> -> REV16 assert(VT.getVectorElementType() == MVT::i8); return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); case OP_VDUP0: case OP_VDUP1: case OP_VDUP2: case OP_VDUP3: { EVT EltTy = VT.getVectorElementType(); unsigned Opcode; if (EltTy == MVT::i8) Opcode = AArch64ISD::DUPLANE8; else if (EltTy == MVT::i16 || EltTy == MVT::f16) Opcode = AArch64ISD::DUPLANE16; else if (EltTy == MVT::i32 || EltTy == MVT::f32) Opcode = AArch64ISD::DUPLANE32; else if (EltTy == MVT::i64 || EltTy == MVT::f64) Opcode = AArch64ISD::DUPLANE64; else llvm_unreachable("Invalid vector element type?"); if (VT.getSizeInBits() == 64) OpLHS = WidenVector(OpLHS, DAG); SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); } case OP_VEXT1: case OP_VEXT2: case OP_VEXT3: { unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, DAG.getConstant(Imm, dl, MVT::i32)); } case OP_VUZPL: return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS); case OP_VUZPR: return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS); case OP_VZIPL: return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS); case OP_VZIPR: return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS); case OP_VTRNL: return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS); case OP_VTRNR: return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS); } } static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, SelectionDAG &DAG) { // Check to see if we can use the TBL instruction. SDValue V1 = Op.getOperand(0); SDValue V2 = Op.getOperand(1); SDLoc DL(Op); EVT EltVT = Op.getValueType().getVectorElementType(); unsigned BytesPerElt = EltVT.getSizeInBits() / 8; SmallVector<SDValue, 8> TBLMask; for (int Val : ShuffleMask) { for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { unsigned Offset = Byte + Val * BytesPerElt; TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); } } MVT IndexVT = MVT::v8i8; unsigned IndexLen = 8; if (Op.getValueSizeInBits() == 128) { IndexVT = MVT::v16i8; IndexLen = 16; } SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); SDValue Shuffle; if (V2.getNode()->isUndef()) { if (IndexLen == 8) V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); Shuffle = DAG.getNode( ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, DAG.getBuildVector(IndexVT, DL, makeArrayRef(TBLMask.data(), IndexLen))); } else { if (IndexLen == 8) { V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); Shuffle = DAG.getNode( ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, DAG.getBuildVector(IndexVT, DL, makeArrayRef(TBLMask.data(), IndexLen))); } else { // FIXME: We cannot, for the moment, emit a TBL2 instruction because we // cannot currently represent the register constraints on the input // table registers. // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], // IndexLen)); Shuffle = DAG.getNode( ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, V2Cst, DAG.getBuildVector(IndexVT, DL, makeArrayRef(TBLMask.data(), IndexLen))); } } return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); } static unsigned getDUPLANEOp(EVT EltType) { if (EltType == MVT::i8) return AArch64ISD::DUPLANE8; if (EltType == MVT::i16 || EltType == MVT::f16) return AArch64ISD::DUPLANE16; if (EltType == MVT::i32 || EltType == MVT::f32) return AArch64ISD::DUPLANE32; if (EltType == MVT::i64 || EltType == MVT::f64) return AArch64ISD::DUPLANE64; llvm_unreachable("Invalid vector element type?"); } SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); EVT VT = Op.getValueType(); ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); // Convert shuffles that are directly supported on NEON to target-specific // DAG nodes, instead of keeping them as shuffles and matching them again // during code selection. This is more efficient and avoids the possibility // of inconsistencies between legalization and selection. ArrayRef<int> ShuffleMask = SVN->getMask(); SDValue V1 = Op.getOperand(0); SDValue V2 = Op.getOperand(1); if (SVN->isSplat()) { int Lane = SVN->getSplatIndex(); // If this is undef splat, generate it via "just" vdup, if possible. if (Lane == -1) Lane = 0; if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), V1.getOperand(0)); // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- // constant. If so, we can just reference the lane's definition directly. if (V1.getOpcode() == ISD::BUILD_VECTOR && !isa<ConstantSDNode>(V1.getOperand(Lane))) return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); // Otherwise, duplicate from the lane of the input vector. unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); // SelectionDAGBuilder may have "helpfully" already extracted or conatenated // to make a vector of the same size as this SHUFFLE. We can ignore the // extract entirely, and canonicalise the concat using WidenVector. if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); V1 = V1.getOperand(0); } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; Lane -= Idx * VT.getVectorNumElements() / 2; V1 = WidenVector(V1.getOperand(Idx), DAG); } else if (VT.getSizeInBits() == 64) V1 = WidenVector(V1, DAG); return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); } if (isREVMask(ShuffleMask, VT, 64)) return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); if (isREVMask(ShuffleMask, VT, 32)) return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); if (isREVMask(ShuffleMask, VT, 16)) return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); bool ReverseEXT = false; unsigned Imm; if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { if (ReverseEXT) std::swap(V1, V2); Imm *= getExtFactor(V1); return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, DAG.getConstant(Imm, dl, MVT::i32)); } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { Imm *= getExtFactor(V1); return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, DAG.getConstant(Imm, dl, MVT::i32)); } unsigned WhichResult; if (isZIPMask(ShuffleMask, VT, WhichResult)) { unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); } if (isUZPMask(ShuffleMask, VT, WhichResult)) { unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); } if (isTRNMask(ShuffleMask, VT, WhichResult)) { unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); } if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); } if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); } if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); } if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) return Concat; bool DstIsLeft; int Anomaly; int NumInputElements = V1.getValueType().getVectorNumElements(); if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { SDValue DstVec = DstIsLeft ? V1 : V2; SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); SDValue SrcVec = V1; int SrcLane = ShuffleMask[Anomaly]; if (SrcLane >= NumInputElements) { SrcVec = V2; SrcLane -= VT.getVectorNumElements(); } SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); EVT ScalarVT = VT.getVectorElementType(); if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) ScalarVT = MVT::i32; return DAG.getNode( ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), DstLaneV); } // If the shuffle is not directly supported and it has 4 elements, use // the PerfectShuffle-generated table to synthesize it from other shuffles. unsigned NumElts = VT.getVectorNumElements(); if (NumElts == 4) { unsigned PFIndexes[4]; for (unsigned i = 0; i != 4; ++i) { if (ShuffleMask[i] < 0) PFIndexes[i] = 8; else PFIndexes[i] = ShuffleMask[i]; } // Compute the index in the perfect shuffle table. unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + PFIndexes[2] * 9 + PFIndexes[3]; unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; unsigned Cost = (PFEntry >> 30); if (Cost <= 4) return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); } return GenerateTBL(Op, ShuffleMask, DAG); } static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, APInt &UndefBits) { EVT VT = BVN->getValueType(0); APInt SplatBits, SplatUndef; unsigned SplatBitSize; bool HasAnyUndefs; if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; for (unsigned i = 0; i < NumSplats; ++i) { CnstBits <<= SplatBitSize; UndefBits <<= SplatBitSize; CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); } return true; } return false; } // Try 64-bit splatted SIMD immediate. static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, const APInt &Bits) { if (Bits.getHiBits(64) == Bits.getLoBits(64)) { uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); EVT VT = Op.getValueType(); MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; if (AArch64_AM::isAdvSIMDModImmType10(Value)) { Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); SDLoc dl(Op); SDValue Mov = DAG.getNode(NewOp, dl, MovTy, DAG.getConstant(Value, dl, MVT::i32)); return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); } } return SDValue(); } // Try 32-bit splatted SIMD immediate. static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, const APInt &Bits, const SDValue *LHS = nullptr) { if (Bits.getHiBits(64) == Bits.getLoBits(64)) { uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); EVT VT = Op.getValueType(); MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; bool isAdvSIMDModImm = false; uint64_t Shift; if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); Shift = 0; } else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); Shift = 8; } else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); Shift = 16; } else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); Shift = 24; } if (isAdvSIMDModImm) { SDLoc dl(Op); SDValue Mov; if (LHS) Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, DAG.getConstant(Value, dl, MVT::i32), DAG.getConstant(Shift, dl, MVT::i32)); else Mov = DAG.getNode(NewOp, dl, MovTy, DAG.getConstant(Value, dl, MVT::i32), DAG.getConstant(Shift, dl, MVT::i32)); return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); } } return SDValue(); } // Try 16-bit splatted SIMD immediate. static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, const APInt &Bits, const SDValue *LHS = nullptr) { if (Bits.getHiBits(64) == Bits.getLoBits(64)) { uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); EVT VT = Op.getValueType(); MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; bool isAdvSIMDModImm = false; uint64_t Shift; if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); Shift = 0; } else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); Shift = 8; } if (isAdvSIMDModImm) { SDLoc dl(Op); SDValue Mov; if (LHS) Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, DAG.getConstant(Value, dl, MVT::i32), DAG.getConstant(Shift, dl, MVT::i32)); else Mov = DAG.getNode(NewOp, dl, MovTy, DAG.getConstant(Value, dl, MVT::i32), DAG.getConstant(Shift, dl, MVT::i32)); return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); } } return SDValue(); } // Try 32-bit splatted SIMD immediate with shifted ones. static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, SelectionDAG &DAG, const APInt &Bits) { if (Bits.getHiBits(64) == Bits.getLoBits(64)) { uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); EVT VT = Op.getValueType(); MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; bool isAdvSIMDModImm = false; uint64_t Shift; if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); Shift = 264; } else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); Shift = 272; } if (isAdvSIMDModImm) { SDLoc dl(Op); SDValue Mov = DAG.getNode(NewOp, dl, MovTy, DAG.getConstant(Value, dl, MVT::i32), DAG.getConstant(Shift, dl, MVT::i32)); return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); } } return SDValue(); } // Try 8-bit splatted SIMD immediate. static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, const APInt &Bits) { if (Bits.getHiBits(64) == Bits.getLoBits(64)) { uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); EVT VT = Op.getValueType(); MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; if (AArch64_AM::isAdvSIMDModImmType9(Value)) { Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); SDLoc dl(Op); SDValue Mov = DAG.getNode(NewOp, dl, MovTy, DAG.getConstant(Value, dl, MVT::i32)); return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); } } return SDValue(); } // Try FP splatted SIMD immediate. static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, const APInt &Bits) { if (Bits.getHiBits(64) == Bits.getLoBits(64)) { uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); EVT VT = Op.getValueType(); bool isWide = (VT.getSizeInBits() == 128); MVT MovTy; bool isAdvSIMDModImm = false; if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); MovTy = isWide ? MVT::v4f32 : MVT::v2f32; } else if (isWide && (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); MovTy = MVT::v2f64; } if (isAdvSIMDModImm) { SDLoc dl(Op); SDValue Mov = DAG.getNode(NewOp, dl, MovTy, DAG.getConstant(Value, dl, MVT::i32)); return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); } } return SDValue(); } // Specialized code to quickly find if PotentialBVec is a BuildVector that // consists of only the same constant int value, returned in reference arg // ConstVal static bool isAllConstantBuildVector(const SDValue &PotentialBVec, uint64_t &ConstVal) { BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); if (!Bvec) return false; ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); if (!FirstElt) return false; EVT VT = Bvec->getValueType(0); unsigned NumElts = VT.getVectorNumElements(); for (unsigned i = 1; i < NumElts; ++i) if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) return false; ConstVal = FirstElt->getZExtValue(); return true; } static unsigned getIntrinsicID(const SDNode *N) { unsigned Opcode = N->getOpcode(); switch (Opcode) { default: return Intrinsic::not_intrinsic; case ISD::INTRINSIC_WO_CHAIN: { unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); if (IID < Intrinsic::num_intrinsics) return IID; return Intrinsic::not_intrinsic; } } } // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. // Also, logical shift right -> sri, with the same structure. static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { EVT VT = N->getValueType(0); if (!VT.isVector()) return SDValue(); SDLoc DL(N); // Is the first op an AND? const SDValue And = N->getOperand(0); if (And.getOpcode() != ISD::AND) return SDValue(); // Is the second op an shl or lshr? SDValue Shift = N->getOperand(1); // This will have been turned into: AArch64ISD::VSHL vector, #shift // or AArch64ISD::VLSHR vector, #shift unsigned ShiftOpc = Shift.getOpcode(); if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) return SDValue(); bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; // Is the shift amount constant? ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); if (!C2node) return SDValue(); // Is the and mask vector all constant? uint64_t C1; if (!isAllConstantBuildVector(And.getOperand(1), C1)) return SDValue(); // Is C1 == ~C2, taking into account how much one can shift elements of a // particular size? uint64_t C2 = C2node->getZExtValue(); unsigned ElemSizeInBits = VT.getScalarSizeInBits(); if (C2 > ElemSizeInBits) return SDValue(); unsigned ElemMask = (1 << ElemSizeInBits) - 1; if ((C1 & ElemMask) != (~C2 & ElemMask)) return SDValue(); SDValue X = And.getOperand(0); SDValue Y = Shift.getOperand(0); unsigned Intrin = IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; SDValue ResultSLI = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, DAG.getConstant(Intrin, DL, MVT::i32), X, Y, Shift.getOperand(1)); LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); LLVM_DEBUG(N->dump(&DAG)); LLVM_DEBUG(dbgs() << "into: \n"); LLVM_DEBUG(ResultSLI->dump(&DAG)); ++NumShiftInserts; return ResultSLI; } SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, SelectionDAG &DAG) const { // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) if (EnableAArch64SlrGeneration) { if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) return Res; } EVT VT = Op.getValueType(); SDValue LHS = Op.getOperand(0); BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); if (!BVN) { // OR commutes, so try swapping the operands. LHS = Op.getOperand(1); BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); } if (!BVN) return Op; APInt DefBits(VT.getSizeInBits(), 0); APInt UndefBits(VT.getSizeInBits(), 0); if (resolveBuildVector(BVN, DefBits, UndefBits)) { SDValue NewOp; if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, DefBits, &LHS)) || (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, DefBits, &LHS))) return NewOp; if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, UndefBits, &LHS)) || (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, UndefBits, &LHS))) return NewOp; } // We can always fall back to a non-immediate OR. return Op; } // Normalize the operands of BUILD_VECTOR. The value of constant operands will // be truncated to fit element width. static SDValue NormalizeBuildVector(SDValue Op, SelectionDAG &DAG) { assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); SDLoc dl(Op); EVT VT = Op.getValueType(); EVT EltTy= VT.getVectorElementType(); if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) return Op; SmallVector<SDValue, 16> Ops; for (SDValue Lane : Op->ops()) { // For integer vectors, type legalization would have promoted the // operands already. Otherwise, if Op is a floating-point splat // (with operands cast to integers), then the only possibilities // are constants and UNDEFs. if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { APInt LowBits(EltTy.getSizeInBits(), CstLane->getZExtValue()); Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); } else if (Lane.getNode()->isUndef()) { Lane = DAG.getUNDEF(MVT::i32); } else { assert(Lane.getValueType() == MVT::i32 && "Unexpected BUILD_VECTOR operand type"); } Ops.push_back(Lane); } return DAG.getBuildVector(VT, dl, Ops); } static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { EVT VT = Op.getValueType(); APInt DefBits(VT.getSizeInBits(), 0); APInt UndefBits(VT.getSizeInBits(), 0); BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); if (resolveBuildVector(BVN, DefBits, UndefBits)) { SDValue NewOp; if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) return NewOp; DefBits = ~DefBits; if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) return NewOp; DefBits = UndefBits; if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) return NewOp; DefBits = ~UndefBits; if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) return NewOp; } return SDValue(); } SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { EVT VT = Op.getValueType(); // Try to build a simple constant vector. Op = NormalizeBuildVector(Op, DAG); if (VT.isInteger()) { // Certain vector constants, used to express things like logical NOT and // arithmetic NEG, are passed through unmodified. This allows special // patterns for these operations to match, which will lower these constants // to whatever is proven necessary. BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); if (BVN->isConstant()) if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { unsigned BitSize = VT.getVectorElementType().getSizeInBits(); APInt Val(BitSize, Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); if (Val.isNullValue() || Val.isAllOnesValue()) return Op; } } if (SDValue V = ConstantBuildVector(Op, DAG)) return V; // Scan through the operands to find some interesting properties we can // exploit: // 1) If only one value is used, we can use a DUP, or // 2) if only the low element is not undef, we can just insert that, or // 3) if only one constant value is used (w/ some non-constant lanes), // we can splat the constant value into the whole vector then fill // in the non-constant lanes. // 4) FIXME: If different constant values are used, but we can intelligently // select the values we'll be overwriting for the non-constant // lanes such that we can directly materialize the vector // some other way (MOVI, e.g.), we can be sneaky. // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. SDLoc dl(Op); unsigned NumElts = VT.getVectorNumElements(); bool isOnlyLowElement = true; bool usesOnlyOneValue = true; bool usesOnlyOneConstantValue = true; bool isConstant = true; bool AllLanesExtractElt = true; unsigned NumConstantLanes = 0; SDValue Value; SDValue ConstantValue; for (unsigned i = 0; i < NumElts; ++i) { SDValue V = Op.getOperand(i); if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) AllLanesExtractElt = false; if (V.isUndef()) continue; if (i > 0) isOnlyLowElement = false; if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) isConstant = false; if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { ++NumConstantLanes; if (!ConstantValue.getNode()) ConstantValue = V; else if (ConstantValue != V) usesOnlyOneConstantValue = false; } if (!Value.getNode()) Value = V; else if (V != Value) usesOnlyOneValue = false; } if (!Value.getNode()) { LLVM_DEBUG( dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); return DAG.getUNDEF(VT); } // Convert BUILD_VECTOR where all elements but the lowest are undef into // SCALAR_TO_VECTOR, except for when we have a single-element constant vector // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) { LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " "SCALAR_TO_VECTOR node\n"); return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); } if (AllLanesExtractElt) { SDNode *Vector = nullptr; bool Even = false; bool Odd = false; // Check whether the extract elements match the Even pattern <0,2,4,...> or // the Odd pattern <1,3,5,...>. for (unsigned i = 0; i < NumElts; ++i) { SDValue V = Op.getOperand(i); const SDNode *N = V.getNode(); if (!isa<ConstantSDNode>(N->getOperand(1))) break; SDValue N0 = N->getOperand(0); // All elements are extracted from the same vector. if (!Vector) { Vector = N0.getNode(); // Check that the type of EXTRACT_VECTOR_ELT matches the type of // BUILD_VECTOR. if (VT.getVectorElementType() != N0.getValueType().getVectorElementType()) break; } else if (Vector != N0.getNode()) { Odd = false; Even = false; break; } // Extracted values are either at Even indices <0,2,4,...> or at Odd // indices <1,3,5,...>. uint64_t Val = N->getConstantOperandVal(1); if (Val == 2 * i) { Even = true; continue; } if (Val - 1 == 2 * i) { Odd = true; continue; } // Something does not match: abort. Odd = false; Even = false; break; } if (Even || Odd) { SDValue LHS = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), DAG.getConstant(0, dl, MVT::i64)); SDValue RHS = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), DAG.getConstant(NumElts, dl, MVT::i64)); if (Even && !Odd) return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, RHS); if (Odd && !Even) return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, RHS); } } // Use DUP for non-constant splats. For f32 constant splats, reduce to // i32 and try again. if (usesOnlyOneValue) { if (!isConstant) { if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || Value.getValueType() != VT) { LLVM_DEBUG( dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); } // This is actually a DUPLANExx operation, which keeps everything vectory. SDValue Lane = Value.getOperand(1); Value = Value.getOperand(0); if (Value.getValueSizeInBits() == 64) { LLVM_DEBUG( dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " "widening it\n"); Value = WidenVector(Value, DAG); } unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); return DAG.getNode(Opcode, dl, VT, Value, Lane); } if (VT.getVectorElementType().isFloatingPoint()) { SmallVector<SDValue, 8> Ops; EVT EltTy = VT.getVectorElementType(); assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && "Unsupported floating-point vector type"); LLVM_DEBUG( dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " "BITCASTS, and try again\n"); MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); for (unsigned i = 0; i < NumElts; ++i) Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; Val.dump();); Val = LowerBUILD_VECTOR(Val, DAG); if (Val.getNode()) return DAG.getNode(ISD::BITCAST, dl, VT, Val); } } // If there was only one constant value used and for more than one lane, // start by splatting that value, then replace the non-constant lanes. This // is better than the default, which will perform a separate initialization // for each lane. if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { // Firstly, try to materialize the splat constant. SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), Val = ConstantBuildVector(Vec, DAG); if (!Val) { // Otherwise, materialize the constant and splat it. Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); } // Now insert the non-constant lanes. for (unsigned i = 0; i < NumElts; ++i) { SDValue V = Op.getOperand(i); SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) // Note that type legalization likely mucked about with the VT of the // source operand, so we may have to convert it here before inserting. Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); } return Val; } // This will generate a load from the constant pool. if (isConstant) { LLVM_DEBUG( dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " "expansion\n"); return SDValue(); } // Empirical tests suggest this is rarely worth it for vectors of length <= 2. if (NumElts >= 4) { if (SDValue shuffle = ReconstructShuffle(Op, DAG)) return shuffle; } // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we // know the default expansion would otherwise fall back on something even // worse. For a vector with one or two non-undef values, that's // scalar_to_vector for the elements followed by a shuffle (provided the // shuffle is valid for the target) and materialization element by element // on the stack followed by a load for everything else. if (!isConstant && !usesOnlyOneValue) { LLVM_DEBUG( dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " "of INSERT_VECTOR_ELT\n"); SDValue Vec = DAG.getUNDEF(VT); SDValue Op0 = Op.getOperand(0); unsigned i = 0; // Use SCALAR_TO_VECTOR for lane zero to // a) Avoid a RMW dependency on the full vector register, and // b) Allow the register coalescer to fold away the copy if the // value is already in an S or D register, and we're forced to emit an // INSERT_SUBREG that we can't fold anywhere. // // We also allow types like i8 and i16 which are illegal scalar but legal // vector element types. After type-legalization the inserted value is // extended (i32) and it is safe to cast them to the vector type by ignoring // the upper bits of the lowest lane (e.g. v8i8, v4i16). if (!Op0.isUndef()) { LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); ++i; } LLVM_DEBUG(if (i < NumElts) dbgs() << "Creating nodes for the other vector elements:\n";); for (; i < NumElts; ++i) { SDValue V = Op.getOperand(i); if (V.isUndef()) continue; SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); } return Vec; } LLVM_DEBUG( dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " "better alternative\n"); return SDValue(); } SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); // Check for non-constant or out of range lane. EVT VT = Op.getOperand(0).getValueType(); ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) return SDValue(); // Insertion/extraction are legal for V128 types. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f16) return Op; if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) return SDValue(); // For V64 types, we perform insertion by expanding the value // to a V128 type and perform the insertion on that. SDLoc DL(Op); SDValue WideVec = WidenVector(Op.getOperand(0), DAG); EVT WideTy = WideVec.getValueType(); SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, Op.getOperand(1), Op.getOperand(2)); // Re-narrow the resultant vector. return NarrowVector(Node, DAG); } SDValue AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); // Check for non-constant or out of range lane. EVT VT = Op.getOperand(0).getValueType(); ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) return SDValue(); // Insertion/extraction are legal for V128 types. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f16) return Op; if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) return SDValue(); // For V64 types, we perform extraction by expanding the value // to a V128 type and perform the extraction on that. SDLoc DL(Op); SDValue WideVec = WidenVector(Op.getOperand(0), DAG); EVT WideTy = WideVec.getValueType(); EVT ExtrTy = WideTy.getVectorElementType(); if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) ExtrTy = MVT::i32; // For extractions, we just return the result directly. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, Op.getOperand(1)); } SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const { EVT VT = Op.getOperand(0).getValueType(); SDLoc dl(Op); // Just in case... if (!VT.isVector()) return SDValue(); ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); if (!Cst) return SDValue(); unsigned Val = Cst->getZExtValue(); unsigned Size = Op.getValueSizeInBits(); // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. if (Val == 0) return Op; // If this is extracting the upper 64-bits of a 128-bit vector, we match // that directly. if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) return Op; return SDValue(); } bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { if (VT.getVectorNumElements() == 4 && (VT.is128BitVector() || VT.is64BitVector())) { unsigned PFIndexes[4]; for (unsigned i = 0; i != 4; ++i) { if (M[i] < 0) PFIndexes[i] = 8; else PFIndexes[i] = M[i]; } // Compute the index in the perfect shuffle table. unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + PFIndexes[2] * 9 + PFIndexes[3]; unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; unsigned Cost = (PFEntry >> 30); if (Cost <= 4) return true; } bool DummyBool; int DummyInt; unsigned DummyUnsigned; return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || isEXTMask(M, VT, DummyBool, DummyUnsigned) || // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || isZIPMask(M, VT, DummyUnsigned) || isTRN_v_undef_Mask(M, VT, DummyUnsigned) || isUZP_v_undef_Mask(M, VT, DummyUnsigned) || isZIP_v_undef_Mask(M, VT, DummyUnsigned) || isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || isConcatMask(M, VT, VT.getSizeInBits() == 128)); } /// getVShiftImm - Check if this is a valid build_vector for the immediate /// operand of a vector shift operation, where all the elements of the /// build_vector must have the same constant integer value. static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { // Ignore bit_converts. while (Op.getOpcode() == ISD::BITCAST) Op = Op.getOperand(0); BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); APInt SplatBits, SplatUndef; unsigned SplatBitSize; bool HasAnyUndefs; if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, ElementBits) || SplatBitSize > ElementBits) return false; Cnt = SplatBits.getSExtValue(); return true; } /// isVShiftLImm - Check if this is a valid build_vector for the immediate /// operand of a vector shift left operation. That value must be in the range: /// 0 <= Value < ElementBits for a left shift; or /// 0 <= Value <= ElementBits for a long left shift. static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { assert(VT.isVector() && "vector shift count is not a vector type"); int64_t ElementBits = VT.getScalarSizeInBits(); if (!getVShiftImm(Op, ElementBits, Cnt)) return false; return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); } /// isVShiftRImm - Check if this is a valid build_vector for the immediate /// operand of a vector shift right operation. The value must be in the range: /// 1 <= Value <= ElementBits for a right shift; or static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { assert(VT.isVector() && "vector shift count is not a vector type"); int64_t ElementBits = VT.getScalarSizeInBits(); if (!getVShiftImm(Op, ElementBits, Cnt)) return false; return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); } SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, SelectionDAG &DAG) const { EVT VT = Op.getValueType(); SDLoc DL(Op); int64_t Cnt; if (!Op.getOperand(1).getValueType().isVector()) return Op; unsigned EltSize = VT.getScalarSizeInBits(); switch (Op.getOpcode()) { default: llvm_unreachable("unexpected shift opcode"); case ISD::SHL: if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), DAG.getConstant(Cnt, DL, MVT::i32)); return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, MVT::i32), Op.getOperand(0), Op.getOperand(1)); case ISD::SRA: case ISD::SRL: // Right shift immediate if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { unsigned Opc = (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; return DAG.getNode(Opc, DL, VT, Op.getOperand(0), DAG.getConstant(Cnt, DL, MVT::i32)); } // Right shift register. Note, there is not a shift right register // instruction, but the shift left register instruction takes a signed // value, where negative numbers specify a right shift. unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl : Intrinsic::aarch64_neon_ushl; // negate the shift amount SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); SDValue NegShiftLeft = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), NegShift); return NegShiftLeft; } return SDValue(); } static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, AArch64CC::CondCode CC, bool NoNans, EVT VT, const SDLoc &dl, SelectionDAG &DAG) { EVT SrcVT = LHS.getValueType(); assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && "function only supposed to emit natural comparisons"); BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); APInt CnstBits(VT.getSizeInBits(), 0); APInt UndefBits(VT.getSizeInBits(), 0); bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); bool IsZero = IsCnst && (CnstBits == 0); if (SrcVT.getVectorElementType().isFloatingPoint()) { switch (CC) { default: return SDValue(); case AArch64CC::NE: { SDValue Fcmeq; if (IsZero) Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); else Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); } case AArch64CC::EQ: if (IsZero) return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); case AArch64CC::GE: if (IsZero) return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); case AArch64CC::GT: if (IsZero) return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); case AArch64CC::LS: if (IsZero) return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); case AArch64CC::LT: if (!NoNans) return SDValue(); // If we ignore NaNs then we can use to the MI implementation. LLVM_FALLTHROUGH; case AArch64CC::MI: if (IsZero) return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); } } switch (CC) { default: return SDValue(); case AArch64CC::NE: { SDValue Cmeq; if (IsZero) Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); else Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); } case AArch64CC::EQ: if (IsZero) return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); case AArch64CC::GE: if (IsZero) return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); case AArch64CC::GT: if (IsZero) return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); case AArch64CC::LE: if (IsZero) return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); case AArch64CC::LS: return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); case AArch64CC::LO: return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); case AArch64CC::LT: if (IsZero) return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); case AArch64CC::HI: return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); case AArch64CC::HS: return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); } } SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const { ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); SDValue LHS = Op.getOperand(0); SDValue RHS = Op.getOperand(1); EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); SDLoc dl(Op); if (LHS.getValueType().getVectorElementType().isInteger()) { assert(LHS.getValueType() == RHS.getValueType()); AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); SDValue Cmp = EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); } const bool FullFP16 = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); // Make v4f16 (only) fcmp operations utilise vector instructions // v8f16 support will be a litle more complicated if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { if (LHS.getValueType().getVectorNumElements() == 4) { LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); DAG.ReplaceAllUsesWith(Op, NewSetcc); CmpVT = MVT::v4i32; } else return SDValue(); } assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || LHS.getValueType().getVectorElementType() != MVT::f128); // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally // clean. Some of them require two branches to implement. AArch64CC::CondCode CC1, CC2; bool ShouldInvert; changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; SDValue Cmp = EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); if (!Cmp.getNode()) return SDValue(); if (CC2 != AArch64CC::AL) { SDValue Cmp2 = EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); if (!Cmp2.getNode()) return SDValue(); Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); } Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); if (ShouldInvert) Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); return Cmp; } static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, SelectionDAG &DAG) { SDValue VecOp = ScalarOp.getOperand(0); auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, DAG.getConstant(0, DL, MVT::i64)); } SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); switch (Op.getOpcode()) { case ISD::VECREDUCE_ADD: return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); case ISD::VECREDUCE_SMAX: return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); case ISD::VECREDUCE_SMIN: return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); case ISD::VECREDUCE_UMAX: return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); case ISD::VECREDUCE_UMIN: return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); case ISD::VECREDUCE_FMAX: { assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); return DAG.getNode( ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), Op.getOperand(0)); } case ISD::VECREDUCE_FMIN: { assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); return DAG.getNode( ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), Op.getOperand(0)); } default: llvm_unreachable("Unhandled reduction"); } } SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, SelectionDAG &DAG) const { auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); if (!Subtarget.hasLSE()) return SDValue(); // LSE has an atomic load-add instruction, but not a load-sub. SDLoc dl(Op); MVT VT = Op.getSimpleValueType(); SDValue RHS = Op.getOperand(2); AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), Op.getOperand(0), Op.getOperand(1), RHS, AN->getMemOperand()); } SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, SelectionDAG &DAG) const { auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); if (!Subtarget.hasLSE()) return SDValue(); // LSE has an atomic load-clear instruction, but not a load-and. SDLoc dl(Op); MVT VT = Op.getSimpleValueType(); SDValue RHS = Op.getOperand(2); AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), Op.getOperand(0), Op.getOperand(1), RHS, AN->getMemOperand()); } SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { SDLoc dl(Op); EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); if (Subtarget->hasCustomCallingConv()) TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, DAG.getConstant(4, dl, MVT::i64)); Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); Chain = DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), DAG.getRegisterMask(Mask), Chain.getValue(1)); // To match the actual intent better, we should read the output from X15 here // again (instead of potentially spilling it to the stack), but rereading Size // from X15 here doesn't work at -O0, since it thinks that X15 is undefined // here. Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, DAG.getConstant(4, dl, MVT::i64)); return Chain; } SDValue AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const { assert(Subtarget->isTargetWindows() && "Only Windows alloca probing supported"); SDLoc dl(Op); // Get the inputs. SDNode *Node = Op.getNode(); SDValue Chain = Op.getOperand(0); SDValue Size = Op.getOperand(1); unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); EVT VT = Node->getValueType(0); if (DAG.getMachineFunction().getFunction().hasFnAttribute( "no-stack-arg-probe")) { SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); Chain = SP.getValue(1); SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); if (Align) SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), DAG.getConstant(-(uint64_t)Align, dl, VT)); Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); SDValue Ops[2] = {SP, Chain}; return DAG.getMergeValues(Ops, dl); } Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); Chain = SP.getValue(1); SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); if (Align) SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), DAG.getConstant(-(uint64_t)Align, dl, VT)); Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); SDValue Ops[2] = {SP, Chain}; return DAG.getMergeValues(Ops, dl); } /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment /// specified in the intrinsic calls. bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I, MachineFunction &MF, unsigned Intrinsic) const { auto &DL = I.getModule()->getDataLayout(); switch (Intrinsic) { case Intrinsic::aarch64_neon_ld2: case Intrinsic::aarch64_neon_ld3: case Intrinsic::aarch64_neon_ld4: case Intrinsic::aarch64_neon_ld1x2: case Intrinsic::aarch64_neon_ld1x3: case Intrinsic::aarch64_neon_ld1x4: case Intrinsic::aarch64_neon_ld2lane: case Intrinsic::aarch64_neon_ld3lane: case Intrinsic::aarch64_neon_ld4lane: case Intrinsic::aarch64_neon_ld2r: case Intrinsic::aarch64_neon_ld3r: case Intrinsic::aarch64_neon_ld4r: { Info.opc = ISD::INTRINSIC_W_CHAIN; // Conservatively set memVT to the entire set of vectors loaded. uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); Info.offset = 0; Info.align = 0; // volatile loads with NEON intrinsics not supported Info.flags = MachineMemOperand::MOLoad; return true; } case Intrinsic::aarch64_neon_st2: case Intrinsic::aarch64_neon_st3: case Intrinsic::aarch64_neon_st4: case Intrinsic::aarch64_neon_st1x2: case Intrinsic::aarch64_neon_st1x3: case Intrinsic::aarch64_neon_st1x4: case Intrinsic::aarch64_neon_st2lane: case Intrinsic::aarch64_neon_st3lane: case Intrinsic::aarch64_neon_st4lane: { Info.opc = ISD::INTRINSIC_VOID; // Conservatively set memVT to the entire set of vectors stored. unsigned NumElts = 0; for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { Type *ArgTy = I.getArgOperand(ArgI)->getType(); if (!ArgTy->isVectorTy()) break; NumElts += DL.getTypeSizeInBits(ArgTy) / 64; } Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); Info.offset = 0; Info.align = 0; // volatile stores with NEON intrinsics not supported Info.flags = MachineMemOperand::MOStore; return true; } case Intrinsic::aarch64_ldaxr: case Intrinsic::aarch64_ldxr: { PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); Info.opc = ISD::INTRINSIC_W_CHAIN; Info.memVT = MVT::getVT(PtrTy->getElementType()); Info.ptrVal = I.getArgOperand(0); Info.offset = 0; Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; return true; } case Intrinsic::aarch64_stlxr: case Intrinsic::aarch64_stxr: { PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); Info.opc = ISD::INTRINSIC_W_CHAIN; Info.memVT = MVT::getVT(PtrTy->getElementType()); Info.ptrVal = I.getArgOperand(1); Info.offset = 0; Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; return true; } case Intrinsic::aarch64_ldaxp: case Intrinsic::aarch64_ldxp: Info.opc = ISD::INTRINSIC_W_CHAIN; Info.memVT = MVT::i128; Info.ptrVal = I.getArgOperand(0); Info.offset = 0; Info.align = 16; Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; return true; case Intrinsic::aarch64_stlxp: case Intrinsic::aarch64_stxp: Info.opc = ISD::INTRINSIC_W_CHAIN; Info.memVT = MVT::i128; Info.ptrVal = I.getArgOperand(2); Info.offset = 0; Info.align = 16; Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; return true; default: break; } return false; } bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, ISD::LoadExtType ExtTy, EVT NewVT) const { // TODO: This may be worth removing. Check regression tests for diffs. if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) return false; // If we're reducing the load width in order to avoid having to use an extra // instruction to do extension then it's probably a good idea. if (ExtTy != ISD::NON_EXTLOAD) return true; // Don't reduce load width if it would prevent us from combining a shift into // the offset. MemSDNode *Mem = dyn_cast<MemSDNode>(Load); assert(Mem); const SDValue &Base = Mem->getBasePtr(); if (Base.getOpcode() == ISD::ADD && Base.getOperand(1).getOpcode() == ISD::SHL && Base.getOperand(1).hasOneUse() && Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { // The shift can be combined if it matches the size of the value being // loaded (and so reducing the width would make it not match). uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; if (ShiftAmount == Log2_32(LoadBytes)) return false; } // We have no reason to disallow reducing the load width, so allow it. return true; } // Truncations from 64-bit GPR to 32-bit GPR is free. bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) return false; unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); return NumBits1 > NumBits2; } bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) return false; unsigned NumBits1 = VT1.getSizeInBits(); unsigned NumBits2 = VT2.getSizeInBits(); return NumBits1 > NumBits2; } /// Check if it is profitable to hoist instruction in then/else to if. /// Not profitable if I and it's user can form a FMA instruction /// because we prefer FMSUB/FMADD. bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { if (I->getOpcode() != Instruction::FMul) return true; if (!I->hasOneUse()) return true; Instruction *User = I->user_back(); if (User && !(User->getOpcode() == Instruction::FSub || User->getOpcode() == Instruction::FAdd)) return true; const TargetOptions &Options = getTargetMachine().Options; const DataLayout &DL = I->getModule()->getDataLayout(); EVT VT = getValueType(DL, User->getOperand(0)->getType()); return !(isFMAFasterThanFMulAndFAdd(VT) && isOperationLegalOrCustom(ISD::FMA, VT) && (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath)); } // All 32-bit GPR operations implicitly zero the high-half of the corresponding // 64-bit GPR. bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) return false; unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); return NumBits1 == 32 && NumBits2 == 64; } bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) return false; unsigned NumBits1 = VT1.getSizeInBits(); unsigned NumBits2 = VT2.getSizeInBits(); return NumBits1 == 32 && NumBits2 == 64; } bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { EVT VT1 = Val.getValueType(); if (isZExtFree(VT1, VT2)) { return true; } if (Val.getOpcode() != ISD::LOAD) return false; // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && VT1.getSizeInBits() <= 32); } bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { if (isa<FPExtInst>(Ext)) return false; // Vector types are not free. if (Ext->getType()->isVectorTy()) return false; for (const Use &U : Ext->uses()) { // The extension is free if we can fold it with a left shift in an // addressing mode or an arithmetic operation: add, sub, and cmp. // Is there a shift? const Instruction *Instr = cast<Instruction>(U.getUser()); // Is this a constant shift? switch (Instr->getOpcode()) { case Instruction::Shl: if (!isa<ConstantInt>(Instr->getOperand(1))) return false; break; case Instruction::GetElementPtr: { gep_type_iterator GTI = gep_type_begin(Instr); auto &DL = Ext->getModule()->getDataLayout(); std::advance(GTI, U.getOperandNo()-1); Type *IdxTy = GTI.getIndexedType(); // This extension will end up with a shift because of the scaling factor. // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. // Get the shift amount based on the scaling factor: // log2(sizeof(IdxTy)) - log2(8). uint64_t ShiftAmt = countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; // Is the constant foldable in the shift of the addressing mode? // I.e., shift amount is between 1 and 4 inclusive. if (ShiftAmt == 0 || ShiftAmt > 4) return false; break; } case Instruction::Trunc: // Check if this is a noop. // trunc(sext ty1 to ty2) to ty1. if (Instr->getType() == Ext->getOperand(0)->getType()) continue; LLVM_FALLTHROUGH; default: return false; } // At this point we can use the bfm family, so this extension is free // for that use. } return true; } /// Check if both Op1 and Op2 are shufflevector extracts of either the lower /// or upper half of the vector elements. static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { auto areTypesHalfed = [](Value *FullV, Value *HalfV) { auto *FullVT = cast<VectorType>(FullV->getType()); auto *HalfVT = cast<VectorType>(HalfV->getType()); return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth(); }; auto extractHalf = [](Value *FullV, Value *HalfV) { auto *FullVT = cast<VectorType>(FullV->getType()); auto *HalfVT = cast<VectorType>(HalfV->getType()); return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); }; Constant *M1, *M2; Value *S1Op1, *S2Op1; if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) || !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2)))) return false; // Check that the operands are half as wide as the result and we extract // half of the elements of the input vectors. if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) return false; // Check the mask extracts either the lower or upper half of vector // elements. int M1Start = -1; int M2Start = -1; int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2; if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) return false; return true; } /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth /// of the vector elements. static bool areExtractExts(Value *Ext1, Value *Ext2) { auto areExtDoubled = [](Instruction *Ext) { return Ext->getType()->getScalarSizeInBits() == 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); }; if (!match(Ext1, m_ZExtOrSExt(m_Value())) || !match(Ext2, m_ZExtOrSExt(m_Value())) || !areExtDoubled(cast<Instruction>(Ext1)) || !areExtDoubled(cast<Instruction>(Ext2))) return false; return true; } /// Check if sinking \p I's operands to I's basic block is profitable, because /// the operands can be folded into a target instruction, e.g. /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). bool AArch64TargetLowering::shouldSinkOperands( Instruction *I, SmallVectorImpl<Use *> &Ops) const { if (!I->getType()->isVectorTy()) return false; if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { switch (II->getIntrinsicID()) { case Intrinsic::aarch64_neon_umull: if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) return false; Ops.push_back(&II->getOperandUse(0)); Ops.push_back(&II->getOperandUse(1)); return true; default: return false; } } switch (I->getOpcode()) { case Instruction::Sub: case Instruction::Add: { if (!areExtractExts(I->getOperand(0), I->getOperand(1))) return false; // If the exts' operands extract either the lower or upper elements, we // can sink them too. auto Ext1 = cast<Instruction>(I->getOperand(0)); auto Ext2 = cast<Instruction>(I->getOperand(1)); if (areExtractShuffleVectors(Ext1, Ext2)) { Ops.push_back(&Ext1->getOperandUse(0)); Ops.push_back(&Ext2->getOperandUse(0)); } Ops.push_back(&I->getOperandUse(0)); Ops.push_back(&I->getOperandUse(1)); return true; } default: return false; } return false; } bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, unsigned &RequiredAligment) const { if (!LoadedType.isSimple() || (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) return false; // Cyclone supports unaligned accesses. RequiredAligment = 0; unsigned NumBits = LoadedType.getSizeInBits(); return NumBits == 32 || NumBits == 64; } /// A helper function for determining the number of interleaved accesses we /// will generate when lowering accesses of the given type. unsigned AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, const DataLayout &DL) const { return (DL.getTypeSizeInBits(VecTy) + 127) / 128; } MachineMemOperand::Flags AArch64TargetLowering::getMMOFlags(const Instruction &I) const { if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) return MOStridedAccess; return MachineMemOperand::MONone; } bool AArch64TargetLowering::isLegalInterleavedAccessType( VectorType *VecTy, const DataLayout &DL) const { unsigned VecSize = DL.getTypeSizeInBits(VecTy); unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); // Ensure the number of vector elements is greater than 1. if (VecTy->getNumElements() < 2) return false; // Ensure the element type is legal. if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) return false; // Ensure the total vector size is 64 or a multiple of 128. Types larger than // 128 will be split into multiple interleaved accesses. return VecSize == 64 || VecSize % 128 == 0; } /// Lower an interleaved load into a ldN intrinsic. /// /// E.g. Lower an interleaved load (Factor = 2): /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements /// /// Into: /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 bool AArch64TargetLowering::lowerInterleavedLoad( LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, ArrayRef<unsigned> Indices, unsigned Factor) const { assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && "Invalid interleave factor"); assert(!Shuffles.empty() && "Empty shufflevector input"); assert(Shuffles.size() == Indices.size() && "Unmatched number of shufflevectors and indices"); const DataLayout &DL = LI->getModule()->getDataLayout(); VectorType *VecTy = Shuffles[0]->getType(); // Skip if we do not have NEON and skip illegal vector types. We can // "legalize" wide vector types into multiple interleaved accesses as long as // the vector types are divisible by 128. if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) return false; unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); // A pointer vector can not be the return type of the ldN intrinsics. Need to // load integer vectors first and then convert to pointer vectors. Type *EltTy = VecTy->getVectorElementType(); if (EltTy->isPointerTy()) VecTy = VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); IRBuilder<> Builder(LI); // The base address of the load. Value *BaseAddr = LI->getPointerOperand(); if (NumLoads > 1) { // If we're going to generate more than one load, reset the sub-vector type // to something legal. VecTy = VectorType::get(VecTy->getVectorElementType(), VecTy->getVectorNumElements() / NumLoads); // We will compute the pointer operand of each load from the original base // address using GEPs. Cast the base address to a pointer to the scalar // element type. BaseAddr = Builder.CreateBitCast( BaseAddr, VecTy->getVectorElementType()->getPointerTo( LI->getPointerAddressSpace())); } Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); Type *Tys[2] = {VecTy, PtrTy}; static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, Intrinsic::aarch64_neon_ld3, Intrinsic::aarch64_neon_ld4}; Function *LdNFunc = Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); // Holds sub-vectors extracted from the load intrinsic return values. The // sub-vectors are associated with the shufflevector instructions they will // replace. DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { // If we're generating more than one load, compute the base address of // subsequent loads as an offset from the previous. if (LoadCount > 0) BaseAddr = Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, VecTy->getVectorNumElements() * Factor); CallInst *LdN = Builder.CreateCall( LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); // Extract and store the sub-vectors returned by the load intrinsic. for (unsigned i = 0; i < Shuffles.size(); i++) { ShuffleVectorInst *SVI = Shuffles[i]; unsigned Index = Indices[i]; Value *SubVec = Builder.CreateExtractValue(LdN, Index); // Convert the integer vector to pointer vector if the element is pointer. if (EltTy->isPointerTy()) SubVec = Builder.CreateIntToPtr( SubVec, VectorType::get(SVI->getType()->getVectorElementType(), VecTy->getVectorNumElements())); SubVecs[SVI].push_back(SubVec); } } // Replace uses of the shufflevector instructions with the sub-vectors // returned by the load intrinsic. If a shufflevector instruction is // associated with more than one sub-vector, those sub-vectors will be // concatenated into a single wide vector. for (ShuffleVectorInst *SVI : Shuffles) { auto &SubVec = SubVecs[SVI]; auto *WideVec = SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; SVI->replaceAllUsesWith(WideVec); } return true; } /// Lower an interleaved store into a stN intrinsic. /// /// E.g. Lower an interleaved store (Factor = 3): /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> /// store <12 x i32> %i.vec, <12 x i32>* %ptr /// /// Into: /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) /// /// Note that the new shufflevectors will be removed and we'll only generate one /// st3 instruction in CodeGen. /// /// Example for a more general valid mask (Factor 3). Lower: /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> /// store <12 x i32> %i.vec, <12 x i32>* %ptr /// /// Into: /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI, unsigned Factor) const { assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && "Invalid interleave factor"); VectorType *VecTy = SVI->getType(); assert(VecTy->getVectorNumElements() % Factor == 0 && "Invalid interleaved store"); unsigned LaneLen = VecTy->getVectorNumElements() / Factor; Type *EltTy = VecTy->getVectorElementType(); VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); const DataLayout &DL = SI->getModule()->getDataLayout(); // Skip if we do not have NEON and skip illegal vector types. We can // "legalize" wide vector types into multiple interleaved accesses as long as // the vector types are divisible by 128. if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) return false; unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); Value *Op0 = SVI->getOperand(0); Value *Op1 = SVI->getOperand(1); IRBuilder<> Builder(SI); // StN intrinsics don't support pointer vectors as arguments. Convert pointer // vectors to integer vectors. if (EltTy->isPointerTy()) { Type *IntTy = DL.getIntPtrType(EltTy); unsigned NumOpElts = Op0->getType()->getVectorNumElements(); // Convert to the corresponding integer vector. Type *IntVecTy = VectorType::get(IntTy, NumOpElts); Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); SubVecTy = VectorType::get(IntTy, LaneLen); } // The base address of the store. Value *BaseAddr = SI->getPointerOperand(); if (NumStores > 1) { // If we're going to generate more than one store, reset the lane length // and sub-vector type to something legal. LaneLen /= NumStores; SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); // We will compute the pointer operand of each store from the original base // address using GEPs. Cast the base address to a pointer to the scalar // element type. BaseAddr = Builder.CreateBitCast( BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( SI->getPointerAddressSpace())); } auto Mask = SVI->getShuffleMask(); Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); Type *Tys[2] = {SubVecTy, PtrTy}; static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, Intrinsic::aarch64_neon_st3, Intrinsic::aarch64_neon_st4}; Function *StNFunc = Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { SmallVector<Value *, 5> Ops; // Split the shufflevector operands into sub vectors for the new stN call. for (unsigned i = 0; i < Factor; i++) { unsigned IdxI = StoreCount * LaneLen * Factor + i; if (Mask[IdxI] >= 0) { Ops.push_back(Builder.CreateShuffleVector( Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); } else { unsigned StartMask = 0; for (unsigned j = 1; j < LaneLen; j++) { unsigned IdxJ = StoreCount * LaneLen * Factor + j; if (Mask[IdxJ * Factor + IdxI] >= 0) { StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; break; } } // Note: Filling undef gaps with random elements is ok, since // those elements were being written anyway (with undefs). // In the case of all undefs we're defaulting to using elems from 0 // Note: StartMask cannot be negative, it's checked in // isReInterleaveMask Ops.push_back(Builder.CreateShuffleVector( Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); } } // If we generating more than one store, we compute the base address of // subsequent stores as an offset from the previous. if (StoreCount > 0) BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), BaseAddr, LaneLen * Factor); Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); Builder.CreateCall(StNFunc, Ops); } return true; } static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, unsigned AlignCheck) { return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && (DstAlign == 0 || DstAlign % AlignCheck == 0)); } EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, bool ZeroMemset, bool MemcpyStrSrc, MachineFunction &MF) const { const Function &F = MF.getFunction(); bool CanImplicitFloat = !F.hasFnAttribute(Attribute::NoImplicitFloat); bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; // Only use AdvSIMD to implement memset of 32-byte and above. It would have // taken one instruction to materialize the v2i64 zero and one store (with // restrictive addressing mode). Just do i64 stores. bool IsSmallMemset = IsMemset && Size < 32; auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) { if (memOpAlign(SrcAlign, DstAlign, AlignCheck)) return true; bool Fast; return allowsMisalignedMemoryAccesses(VT, 0, 1, &Fast) && Fast; }; if (CanUseNEON && IsMemset && !IsSmallMemset && AlignmentIsAcceptable(MVT::v2i64, 16)) return MVT::v2i64; if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16)) return MVT::f128; if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8)) return MVT::i64; if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4)) return MVT::i32; return MVT::Other; } // 12-bit optionally shifted immediates are legal for adds. bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { if (Immed == std::numeric_limits<int64_t>::min()) { LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed << ": avoid UB for INT64_MIN\n"); return false; } // Same encoding for add/sub, just flip the sign. Immed = std::abs(Immed); bool IsLegal = ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); LLVM_DEBUG(dbgs() << "Is " << Immed << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); return IsLegal; } // Integer comparisons are implemented with ADDS/SUBS, so the range of valid // immediates is the same as for an add or a sub. bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { return isLegalAddImmediate(Immed); } /// isLegalAddressingMode - Return true if the addressing mode represented /// by AM is legal for this target, for a load/store of the specified type. bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const { // AArch64 has five basic addressing modes: // reg // reg + 9-bit signed offset // reg + SIZE_IN_BYTES * 12-bit unsigned offset // reg1 + reg2 // reg + SIZE_IN_BYTES * reg // No global is ever allowed as a base. if (AM.BaseGV) return false; // No reg+reg+imm addressing. if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) return false; // check reg + imm case: // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 uint64_t NumBytes = 0; if (Ty->isSized()) { uint64_t NumBits = DL.getTypeSizeInBits(Ty); NumBytes = NumBits / 8; if (!isPowerOf2_64(NumBits)) NumBytes = 0; } if (!AM.Scale) { int64_t Offset = AM.BaseOffs; // 9-bit signed offset if (isInt<9>(Offset)) return true; // 12-bit unsigned offset unsigned shift = Log2_64(NumBytes); if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && // Must be a multiple of NumBytes (NumBytes is a power of 2) (Offset >> shift) << shift == Offset) return true; return false; } // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); } bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { // Consider splitting large offset of struct or array. return true; } int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS) const { // Scaling factors are not free at all. // Operands | Rt Latency // ------------------------------------------- // Rt, [Xn, Xm] | 4 // ------------------------------------------- // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 // Rt, [Xn, Wm, <extend> #imm] | if (isLegalAddressingMode(DL, AM, Ty, AS)) // Scale represents reg2 * scale, thus account for 1 if // it is not equal to 0 or 1. return AM.Scale != 0 && AM.Scale != 1; return -1; } bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { VT = VT.getScalarType(); if (!VT.isSimple()) return false; switch (VT.getSimpleVT().SimpleTy) { case MVT::f32: case MVT::f64: return true; default: break; } return false; } const MCPhysReg * AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { // LR is a callee-save register, but we must treat it as clobbered by any call // site. Hence we include LR in the scratch registers, which are in turn added // as implicit-defs for stackmaps and patchpoints. static const MCPhysReg ScratchRegs[] = { AArch64::X16, AArch64::X17, AArch64::LR, 0 }; return ScratchRegs; } bool AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, CombineLevel Level) const { N = N->getOperand(0).getNode(); EVT VT = N->getValueType(0); // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine // it with shift to let it be lowered to UBFX. if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && isa<ConstantSDNode>(N->getOperand(1))) { uint64_t TruncMask = N->getConstantOperandVal(1); if (isMask_64(TruncMask) && N->getOperand(0).getOpcode() == ISD::SRL && isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) return false; } return true; } bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const { assert(Ty->isIntegerTy()); unsigned BitSize = Ty->getPrimitiveSizeInBits(); if (BitSize == 0) return false; int64_t Val = Imm.getSExtValue(); if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) return true; if ((int64_t)Val < 0) Val = ~Val; if (BitSize == 32) Val &= (1LL << 32) - 1; unsigned LZ = countLeadingZeros((uint64_t)Val); unsigned Shift = (63 - LZ) / 16; // MOVZ is free so return true for one or fewer MOVK. return Shift < 3; } bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, unsigned Index) const { if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) return false; return (Index == 0 || Index == ResVT.getVectorNumElements()); } /// Turn vector tests of the signbit in the form of: /// xor (sra X, elt_size(X)-1), -1 /// into: /// cmge X, X, #0 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, const AArch64Subtarget *Subtarget) { EVT VT = N->getValueType(0); if (!Subtarget->hasNEON() || !VT.isVector()) return SDValue(); // There must be a shift right algebraic before the xor, and the xor must be a // 'not' operation. SDValue Shift = N->getOperand(0); SDValue Ones = N->getOperand(1); if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || !ISD::isBuildVectorAllOnes(Ones.getNode())) return SDValue(); // The shift should be smearing the sign bit across each vector element. auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) return SDValue(); return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); } // Generate SUBS and CSEL for integer abs. static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { EVT VT = N->getValueType(0); SDValue N0 = N->getOperand(0); SDValue N1 = N->getOperand(1); SDLoc DL(N); // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) // and change it to SUB and CSEL. if (VT.isInteger() && N->getOpcode() == ISD::XOR && N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0.getOperand(0)); // Generate SUBS & CSEL. SDValue Cmp = DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), N0.getOperand(0), DAG.getConstant(0, DL, VT)); return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, DAG.getConstant(AArch64CC::PL, DL, MVT::i32), SDValue(Cmp.getNode(), 1)); } return SDValue(); } static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const AArch64Subtarget *Subtarget) { if (DCI.isBeforeLegalizeOps()) return SDValue(); if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) return Cmp; return performIntegerAbsCombine(N, DAG); } SDValue AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl<SDNode *> &Created) const { AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); if (isIntDivCheap(N->getValueType(0), Attr)) return SDValue(N,0); // Lower SDIV as SDIV // fold (sdiv X, pow2) EVT VT = N->getValueType(0); if ((VT != MVT::i32 && VT != MVT::i64) || !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) return SDValue(); SDLoc DL(N); SDValue N0 = N->getOperand(0); unsigned Lg2 = Divisor.countTrailingZeros(); SDValue Zero = DAG.getConstant(0, DL, VT); SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); // Add (N0 < 0) ? Pow2 - 1 : 0; SDValue CCVal; SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); Created.push_back(Cmp.getNode()); Created.push_back(Add.getNode()); Created.push_back(CSel.getNode()); // Divide by pow2. SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); // If we're dividing by a positive value, we're done. Otherwise, we must // negate the result. if (Divisor.isNonNegative()) return SRA; Created.push_back(SRA.getNode()); return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); } static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const AArch64Subtarget *Subtarget) { if (DCI.isBeforeLegalizeOps()) return SDValue(); // The below optimizations require a constant RHS. if (!isa<ConstantSDNode>(N->getOperand(1))) return SDValue(); ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); const APInt &ConstValue = C->getAPIntValue(); // Multiplication of a power of two plus/minus one can be done more // cheaply as as shift+add/sub. For now, this is true unilaterally. If // future CPUs have a cheaper MADD instruction, this may need to be // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and // 64-bit is 5 cycles, so this is always a win. // More aggressively, some multiplications N0 * C can be lowered to // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, // e.g. 6=3*2=(2+1)*2. // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 // which equals to (1+2)*16-(1+2). SDValue N0 = N->getOperand(0); // TrailingZeroes is used to test if the mul can be lowered to // shift+add+shift. unsigned TrailingZeroes = ConstValue.countTrailingZeros(); if (TrailingZeroes) { // Conservatively do not lower to shift+add+shift if the mul might be // folded into smul or umul. if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || isZeroExtended(N0.getNode(), DAG))) return SDValue(); // Conservatively do not lower to shift+add+shift if the mul might be // folded into madd or msub. if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || N->use_begin()->getOpcode() == ISD::SUB)) return SDValue(); } // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub // and shift+add+shift. APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); unsigned ShiftAmt, AddSubOpc; // Is the shifted value the LHS operand of the add/sub? bool ShiftValUseIsN0 = true; // Do we need to negate the result? bool NegateResult = false; if (ConstValue.isNonNegative()) { // (mul x, 2^N + 1) => (add (shl x, N), x) // (mul x, 2^N - 1) => (sub (shl x, N), x) // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) APInt SCVMinus1 = ShiftedConstValue - 1; APInt CVPlus1 = ConstValue + 1; if (SCVMinus1.isPowerOf2()) { ShiftAmt = SCVMinus1.logBase2(); AddSubOpc = ISD::ADD; } else if (CVPlus1.isPowerOf2()) { ShiftAmt = CVPlus1.logBase2(); AddSubOpc = ISD::SUB; } else return SDValue(); } else { // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) // (mul x, -(2^N + 1)) => - (add (shl x, N), x) APInt CVNegPlus1 = -ConstValue + 1; APInt CVNegMinus1 = -ConstValue - 1; if (CVNegPlus1.isPowerOf2()) { ShiftAmt = CVNegPlus1.logBase2(); AddSubOpc = ISD::SUB; ShiftValUseIsN0 = false; } else if (CVNegMinus1.isPowerOf2()) { ShiftAmt = CVNegMinus1.logBase2(); AddSubOpc = ISD::ADD; NegateResult = true; } else return SDValue(); } SDLoc DL(N); EVT VT = N->getValueType(0); SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShiftAmt, DL, MVT::i64)); SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); assert(!(NegateResult && TrailingZeroes) && "NegateResult and TrailingZeroes cannot both be true for now."); // Negate the result. if (NegateResult) return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); // Shift the result. if (TrailingZeroes) return DAG.getNode(ISD::SHL, DL, VT, Res, DAG.getConstant(TrailingZeroes, DL, MVT::i64)); return Res; } static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, SelectionDAG &DAG) { // Take advantage of vector comparisons producing 0 or -1 in each lane to // optimize away operation when it's from a constant. // // The general transformation is: // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> // AND(VECTOR_CMP(x,y), constant2) // constant2 = UNARYOP(constant) // Early exit if this isn't a vector operation, the operand of the // unary operation isn't a bitwise AND, or if the sizes of the operations // aren't the same. EVT VT = N->getValueType(0); if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) return SDValue(); // Now check that the other operand of the AND is a constant. We could // make the transformation for non-constant splats as well, but it's unclear // that would be a benefit as it would not eliminate any operations, just // perform one more step in scalar code before moving to the vector unit. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { // Bail out if the vector isn't a constant. if (!BV->isConstant()) return SDValue(); // Everything checks out. Build up the new and improved node. SDLoc DL(N); EVT IntVT = BV->getValueType(0); // Create a new constant of the appropriate type for the transformed // DAG. SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); // The AND node needs bitcasts to/from an integer vector type around it. SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, N->getOperand(0)->getOperand(0), MaskConst); SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); return Res; } return SDValue(); } static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, const AArch64Subtarget *Subtarget) { // First try to optimize away the conversion when it's conditionally from // a constant. Vectors only. if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) return Res; EVT VT = N->getValueType(0); if (VT != MVT::f32 && VT != MVT::f64) return SDValue(); // Only optimize when the source and destination types have the same width. if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) return SDValue(); // If the result of an integer load is only used by an integer-to-float // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. // This eliminates an "integer-to-vector-move" UOP and improves throughput. SDValue N0 = N->getOperand(0); if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && // Do not change the width of a volatile load. !cast<LoadSDNode>(N0)->isVolatile()) { LoadSDNode *LN0 = cast<LoadSDNode>(N0); SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), LN0->getPointerInfo(), LN0->getAlignment(), LN0->getMemOperand()->getFlags()); // Make sure successors of the original load stay after it by updating them // to use the new Chain. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); unsigned Opcode = (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; return DAG.getNode(Opcode, SDLoc(N), VT, Load); } return SDValue(); } /// Fold a floating-point multiply by power of two into floating-point to /// fixed-point conversion. static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const AArch64Subtarget *Subtarget) { if (!Subtarget->hasNEON()) return SDValue(); SDValue Op = N->getOperand(0); if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || Op.getOpcode() != ISD::FMUL) return SDValue(); SDValue ConstVec = Op->getOperand(1); if (!isa<BuildVectorSDNode>(ConstVec)) return SDValue(); MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); uint32_t FloatBits = FloatTy.getSizeInBits(); if (FloatBits != 32 && FloatBits != 64) return SDValue(); MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); uint32_t IntBits = IntTy.getSizeInBits(); if (IntBits != 16 && IntBits != 32 && IntBits != 64) return SDValue(); // Avoid conversions where iN is larger than the float (e.g., float -> i64). if (IntBits > FloatBits) return SDValue(); BitVector UndefElements; BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); int32_t Bits = IntBits == 64 ? 64 : 32; int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); if (C == -1 || C == 0 || C > Bits) return SDValue(); MVT ResTy; unsigned NumLanes = Op.getValueType().getVectorNumElements(); switch (NumLanes) { default: return SDValue(); case 2: ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; break; case 4: ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; break; } if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) return SDValue(); assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && "Illegal vector type after legalization"); SDLoc DL(N); bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs : Intrinsic::aarch64_neon_vcvtfp2fxu; SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); // We can handle smaller integers by generating an extra trunc. if (IntBits < FloatBits) FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); return FixConv; } /// Fold a floating-point divide by power of two into fixed-point to /// floating-point conversion. static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, TargetLowering::DAGCombinerInfo &DCI, const AArch64Subtarget *Subtarget) { if (!Subtarget->hasNEON()) return SDValue(); SDValue Op = N->getOperand(0); unsigned Opc = Op->getOpcode(); if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || !Op.getOperand(0).getValueType().isSimple() || (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) return SDValue(); SDValue ConstVec = N->getOperand(1); if (!isa<BuildVectorSDNode>(ConstVec)) return SDValue(); MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); int32_t IntBits = IntTy.getSizeInBits(); if (IntBits != 16 && IntBits != 32 && IntBits != 64) return SDValue(); MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); int32_t FloatBits = FloatTy.getSizeInBits(); if (FloatBits != 32 && FloatBits != 64) return SDValue(); // Avoid conversions where iN is larger than the float (e.g., i64 -> float). if (IntBits > FloatBits) return SDValue(); BitVector UndefElements; BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); if (C == -1 || C == 0 || C > FloatBits) return SDValue(); MVT ResTy; unsigned NumLanes = Op.getValueType().getVectorNumElements(); switch (NumLanes) { default: return SDValue(); case 2: ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; break; case 4: ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; break; } if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) return SDValue(); SDLoc DL(N); SDValue ConvInput = Op.getOperand(0); bool IsSigned = Opc == ISD::SINT_TO_FP; if (IntBits < FloatBits) ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, ResTy, ConvInput); unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp : Intrinsic::aarch64_neon_vcvtfxu2fp; return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, DAG.getConstant(C, DL, MVT::i32)); } /// An EXTR instruction is made up of two shifts, ORed together. This helper /// searches for and classifies those shifts. static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, bool &FromHi) { if (N.getOpcode() == ISD::SHL) FromHi = false; else if (N.getOpcode() == ISD::SRL) FromHi = true; else return false; if (!isa<ConstantSDNode>(N.getOperand(1))) return false; ShiftAmount = N->getConstantOperandVal(1); Src = N->getOperand(0); return true; } /// EXTR instruction extracts a contiguous chunk of bits from two existing /// registers viewed as a high/low pair. This function looks for the pattern: /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it /// with an EXTR. Can't quite be done in TableGen because the two immediates /// aren't independent. static SDValue tryCombineToEXTR(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { SelectionDAG &DAG = DCI.DAG; SDLoc DL(N); EVT VT = N->getValueType(0); assert(N->getOpcode() == ISD::OR && "Unexpected root"); if (VT != MVT::i32 && VT != MVT::i64) return SDValue(); SDValue LHS; uint32_t ShiftLHS = 0; bool LHSFromHi = false; if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) return SDValue(); SDValue RHS; uint32_t ShiftRHS = 0; bool RHSFromHi = false; if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) return SDValue(); // If they're both trying to come from the high part of the register, they're // not really an EXTR. if (LHSFromHi == RHSFromHi) return SDValue(); if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) return SDValue(); if (LHSFromHi) { std::swap(LHS, RHS); std::swap(ShiftLHS, ShiftRHS); } return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, DAG.getConstant(ShiftRHS, DL, MVT::i64)); } static SDValue tryCombineToBSL(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { EVT VT = N->getValueType(0); SelectionDAG &DAG = DCI.DAG; SDLoc DL(N); if (!VT.isVector()) return SDValue(); SDValue N0 = N->getOperand(0); if (N0.getOpcode() != ISD::AND) return SDValue(); SDValue N1 = N->getOperand(1); if (N1.getOpcode() != ISD::AND) return SDValue(); // We only have to look for constant vectors here since the general, variable // case can be handled in TableGen. unsigned Bits = VT.getScalarSizeInBits(); uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); for (int i = 1; i >= 0; --i) for (int j = 1; j >= 0; --j) { BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); if (!BVN0 || !BVN1) continue; bool FoundMatch = true; for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); if (!CN0 || !CN1 || CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { FoundMatch = false; break; } } if (FoundMatch) return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), N0->getOperand(1 - i), N1->getOperand(1 - j)); } return SDValue(); } static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const AArch64Subtarget *Subtarget) { // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) SelectionDAG &DAG = DCI.DAG; EVT VT = N->getValueType(0); if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) return SDValue(); if (SDValue Res = tryCombineToEXTR(N, DCI)) return Res; if (SDValue Res = tryCombineToBSL(N, DCI)) return Res; return SDValue(); } static SDValue performANDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { SelectionDAG &DAG = DCI.DAG; SDValue LHS = N->getOperand(0); EVT VT = N->getValueType(0); if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) return SDValue(); BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); if (!BVN) return SDValue(); // AND does not accept an immediate, so check if we can use a BIC immediate // instruction instead. We do this here instead of using a (and x, (mvni imm)) // pattern in isel, because some immediates may be lowered to the preferred // (and x, (movi imm)) form, even though an mvni representation also exists. APInt DefBits(VT.getSizeInBits(), 0); APInt UndefBits(VT.getSizeInBits(), 0); if (resolveBuildVector(BVN, DefBits, UndefBits)) { SDValue NewOp; DefBits = ~DefBits; if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, DefBits, &LHS)) || (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, DefBits, &LHS))) return NewOp; UndefBits = ~UndefBits; if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, UndefBits, &LHS)) || (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, UndefBits, &LHS))) return NewOp; } return SDValue(); } static SDValue performSRLCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { SelectionDAG &DAG = DCI.DAG; EVT VT = N->getValueType(0); if (VT != MVT::i32 && VT != MVT::i64) return SDValue(); // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. SDValue N0 = N->getOperand(0); if (N0.getOpcode() == ISD::BSWAP) { SDLoc DL(N); SDValue N1 = N->getOperand(1); SDValue N00 = N0.getOperand(0); if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { uint64_t ShiftAmt = C->getZExtValue(); if (VT == MVT::i32 && ShiftAmt == 16 && DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); if (VT == MVT::i64 && ShiftAmt == 32 && DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); } } return SDValue(); } static SDValue performBitcastCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { // Wait 'til after everything is legalized to try this. That way we have // legal vector types and such. if (DCI.isBeforeLegalizeOps()) return SDValue(); // Remove extraneous bitcasts around an extract_subvector. // For example, // (v4i16 (bitconvert // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) // becomes // (extract_subvector ((v8i16 ...), (i64 4))) // Only interested in 64-bit vectors as the ultimate result. EVT VT = N->getValueType(0); if (!VT.isVector()) return SDValue(); if (VT.getSimpleVT().getSizeInBits() != 64) return SDValue(); // Is the operand an extract_subvector starting at the beginning or halfway // point of the vector? A low half may also come through as an // EXTRACT_SUBREG, so look for that, too. SDValue Op0 = N->getOperand(0); if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && !(Op0->isMachineOpcode() && Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) return SDValue(); uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) return SDValue(); } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { if (idx != AArch64::dsub) return SDValue(); // The dsub reference is equivalent to a lane zero subvector reference. idx = 0; } // Look through the bitcast of the input to the extract. if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) return SDValue(); SDValue Source = Op0->getOperand(0)->getOperand(0); // If the source type has twice the number of elements as our destination // type, we know this is an extract of the high or low half of the vector. EVT SVT = Source->getValueType(0); if (!SVT.isVector() || SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) return SDValue(); LLVM_DEBUG( dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); // Create the simplified form to just extract the low or high half of the // vector directly rather than bothering with the bitcasts. SDLoc dl(N); unsigned NumElements = VT.getVectorNumElements(); if (idx) { SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); } else { SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, Source, SubReg), 0); } } static SDValue performConcatVectorsCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { SDLoc dl(N); EVT VT = N->getValueType(0); SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); // Optimize concat_vectors of truncated vectors, where the intermediate // type is illegal, to avoid said illegality, e.g., // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), // (v2i16 (truncate (v2i64))))) // -> // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), // (v4i32 (bitcast (v2i64))), // <0, 2, 4, 6>))) // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed // on both input and result type, so we might generate worse code. // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. if (N->getNumOperands() == 2 && N0->getOpcode() == ISD::TRUNCATE && N1->getOpcode() == ISD::TRUNCATE) { SDValue N00 = N0->getOperand(0); SDValue N10 = N1->getOperand(0); EVT N00VT = N00.getValueType(); if (N00VT == N10.getValueType() && (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); for (size_t i = 0; i < Mask.size(); ++i) Mask[i] = i * 2; return DAG.getNode(ISD::TRUNCATE, dl, VT, DAG.getVectorShuffle( MidVT, dl, DAG.getNode(ISD::BITCAST, dl, MidVT, N00), DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); } } // Wait 'til after everything is legalized to try this. That way we have // legal vector types and such. if (DCI.isBeforeLegalizeOps()) return SDValue(); // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector // splat. The indexed instructions are going to be expecting a DUPLANE64, so // canonicalise to that. if (N0 == N1 && VT.getVectorNumElements() == 2) { assert(VT.getScalarSizeInBits() == 64); return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), DAG.getConstant(0, dl, MVT::i64)); } // Canonicalise concat_vectors so that the right-hand vector has as few // bit-casts as possible before its real operation. The primary matching // destination for these operations will be the narrowing "2" instructions, // which depend on the operation being performed on this right-hand vector. // For example, // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) // becomes // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) if (N1->getOpcode() != ISD::BITCAST) return SDValue(); SDValue RHS = N1->getOperand(0); MVT RHSTy = RHS.getValueType().getSimpleVT(); // If the RHS is not a vector, this is not the pattern we're looking for. if (!RHSTy.isVector()) return SDValue(); LLVM_DEBUG( dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), RHSTy.getVectorNumElements() * 2); return DAG.getNode(ISD::BITCAST, dl, VT, DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), RHS)); } static SDValue tryCombineFixedPointConvert(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { // Wait until after everything is legalized to try this. That way we have // legal vector types and such. if (DCI.isBeforeLegalizeOps()) return SDValue(); // Transform a scalar conversion of a value from a lane extract into a // lane extract of a vector conversion. E.g., from foo1 to foo2: // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } // // The second form interacts better with instruction selection and the // register allocator to avoid cross-class register copies that aren't // coalescable due to a lane reference. // Check the operand and see if it originates from a lane extract. SDValue Op1 = N->getOperand(1); if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { // Yep, no additional predication needed. Perform the transform. SDValue IID = N->getOperand(0); SDValue Shift = N->getOperand(2); SDValue Vec = Op1.getOperand(0); SDValue Lane = Op1.getOperand(1); EVT ResTy = N->getValueType(0); EVT VecResTy; SDLoc DL(N); // The vector width should be 128 bits by the time we get here, even // if it started as 64 bits (the extract_vector handling will have // done so). assert(Vec.getValueSizeInBits() == 128 && "unexpected vector size on extract_vector_elt!"); if (Vec.getValueType() == MVT::v4i32) VecResTy = MVT::v4f32; else if (Vec.getValueType() == MVT::v2i64) VecResTy = MVT::v2f64; else llvm_unreachable("unexpected vector type!"); SDValue Convert = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); } return SDValue(); } // AArch64 high-vector "long" operations are formed by performing the non-high // version on an extract_subvector of each operand which gets the high half: // // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) // // However, there are cases which don't have an extract_high explicitly, but // have another operation that can be made compatible with one for free. For // example: // // (dupv64 scalar) --> (extract_high (dup128 scalar)) // // This routine does the actual conversion of such DUPs, once outer routines // have determined that everything else is in order. // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold // similarly here. static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { switch (N.getOpcode()) { case AArch64ISD::DUP: case AArch64ISD::DUPLANE8: case AArch64ISD::DUPLANE16: case AArch64ISD::DUPLANE32: case AArch64ISD::DUPLANE64: case AArch64ISD::MOVI: case AArch64ISD::MOVIshift: case AArch64ISD::MOVIedit: case AArch64ISD::MOVImsl: case AArch64ISD::MVNIshift: case AArch64ISD::MVNImsl: break; default: // FMOV could be supported, but isn't very useful, as it would only occur // if you passed a bitcast' floating point immediate to an eligible long // integer op (addl, smull, ...). return SDValue(); } MVT NarrowTy = N.getSimpleValueType(); if (!NarrowTy.is64BitVector()) return SDValue(); MVT ElementTy = NarrowTy.getVectorElementType(); unsigned NumElems = NarrowTy.getVectorNumElements(); MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); SDLoc dl(N); return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), DAG.getConstant(NumElems, dl, MVT::i64)); } static bool isEssentiallyExtractHighSubvector(SDValue N) { if (N.getOpcode() == ISD::BITCAST) N = N.getOperand(0); if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) return false; return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == N.getOperand(0).getValueType().getVectorNumElements() / 2; } /// Helper structure to keep track of ISD::SET_CC operands. struct GenericSetCCInfo { const SDValue *Opnd0; const SDValue *Opnd1; ISD::CondCode CC; }; /// Helper structure to keep track of a SET_CC lowered into AArch64 code. struct AArch64SetCCInfo { const SDValue *Cmp; AArch64CC::CondCode CC; }; /// Helper structure to keep track of SetCC information. union SetCCInfo { GenericSetCCInfo Generic; AArch64SetCCInfo AArch64; }; /// Helper structure to be able to read SetCC information. If set to /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a /// GenericSetCCInfo. struct SetCCInfoAndKind { SetCCInfo Info; bool IsAArch64; }; /// Check whether or not \p Op is a SET_CC operation, either a generic or /// an /// AArch64 lowered one. /// \p SetCCInfo is filled accordingly. /// \post SetCCInfo is meanginfull only when this function returns true. /// \return True when Op is a kind of SET_CC operation. static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { // If this is a setcc, this is straight forward. if (Op.getOpcode() == ISD::SETCC) { SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); SetCCInfo.IsAArch64 = false; return true; } // Otherwise, check if this is a matching csel instruction. // In other words: // - csel 1, 0, cc // - csel 0, 1, !cc if (Op.getOpcode() != AArch64ISD::CSEL) return false; // Set the information about the operands. // TODO: we want the operands of the Cmp not the csel SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); SetCCInfo.IsAArch64 = true; SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); // Check that the operands matches the constraints: // (1) Both operands must be constants. // (2) One must be 1 and the other must be 0. ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); // Check (1). if (!TValue || !FValue) return false; // Check (2). if (!TValue->isOne()) { // Update the comparison when we are interested in !cc. std::swap(TValue, FValue); SetCCInfo.Info.AArch64.CC = AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); } return TValue->isOne() && FValue->isNullValue(); } // Returns true if Op is setcc or zext of setcc. static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { if (isSetCC(Op, Info)) return true; return ((Op.getOpcode() == ISD::ZERO_EXTEND) && isSetCC(Op->getOperand(0), Info)); } // The folding we want to perform is: // (add x, [zext] (setcc cc ...) ) // --> // (csel x, (add x, 1), !cc ...) // // The latter will get matched to a CSINC instruction. static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); SDValue LHS = Op->getOperand(0); SDValue RHS = Op->getOperand(1); SetCCInfoAndKind InfoAndKind; // If neither operand is a SET_CC, give up. if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { std::swap(LHS, RHS); if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) return SDValue(); } // FIXME: This could be generatized to work for FP comparisons. EVT CmpVT = InfoAndKind.IsAArch64 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() : InfoAndKind.Info.Generic.Opnd0->getValueType(); if (CmpVT != MVT::i32 && CmpVT != MVT::i64) return SDValue(); SDValue CCVal; SDValue Cmp; SDLoc dl(Op); if (InfoAndKind.IsAArch64) { CCVal = DAG.getConstant( AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, MVT::i32); Cmp = *InfoAndKind.Info.AArch64.Cmp; } else Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1, ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), CCVal, DAG, dl); EVT VT = Op->getValueType(0); LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); } // The basic add/sub long vector instructions have variants with "2" on the end // which act on the high-half of their inputs. They are normally matched by // patterns like: // // (add (zeroext (extract_high LHS)), // (zeroext (extract_high RHS))) // -> uaddl2 vD, vN, vM // // However, if one of the extracts is something like a duplicate, this // instruction can still be used profitably. This function puts the DAG into a // more appropriate form for those patterns to trigger. static SDValue performAddSubLongCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { if (DCI.isBeforeLegalizeOps()) return SDValue(); MVT VT = N->getSimpleValueType(0); if (!VT.is128BitVector()) { if (N->getOpcode() == ISD::ADD) return performSetccAddFolding(N, DAG); return SDValue(); } // Make sure both branches are extended in the same way. SDValue LHS = N->getOperand(0); SDValue RHS = N->getOperand(1); if ((LHS.getOpcode() != ISD::ZERO_EXTEND && LHS.getOpcode() != ISD::SIGN_EXTEND) || LHS.getOpcode() != RHS.getOpcode()) return SDValue(); unsigned ExtType = LHS.getOpcode(); // It's not worth doing if at least one of the inputs isn't already an // extract, but we don't know which it'll be so we have to try both. if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); if (!RHS.getNode()) return SDValue(); RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); if (!LHS.getNode()) return SDValue(); LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); } return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); } // Massage DAGs which we can use the high-half "long" operations on into // something isel will recognize better. E.g. // // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> // (aarch64_neon_umull (extract_high (v2i64 vec))) // (extract_high (v2i64 (dup128 scalar))))) // static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { if (DCI.isBeforeLegalizeOps()) return SDValue(); SDValue LHS = N->getOperand(1); SDValue RHS = N->getOperand(2); assert(LHS.getValueType().is64BitVector() && RHS.getValueType().is64BitVector() && "unexpected shape for long operation"); // Either node could be a DUP, but it's not worth doing both of them (you'd // just as well use the non-high version) so look for a corresponding extract // operation on the other "wing". if (isEssentiallyExtractHighSubvector(LHS)) { RHS = tryExtendDUPToExtractHigh(RHS, DAG); if (!RHS.getNode()) return SDValue(); } else if (isEssentiallyExtractHighSubvector(RHS)) { LHS = tryExtendDUPToExtractHigh(LHS, DAG); if (!LHS.getNode()) return SDValue(); } return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), N->getOperand(0), LHS, RHS); } static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { MVT ElemTy = N->getSimpleValueType(0).getScalarType(); unsigned ElemBits = ElemTy.getSizeInBits(); int64_t ShiftAmount; if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { APInt SplatValue, SplatUndef; unsigned SplatBitSize; bool HasAnyUndefs; if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, HasAnyUndefs, ElemBits) || SplatBitSize != ElemBits) return SDValue(); ShiftAmount = SplatValue.getSExtValue(); } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { ShiftAmount = CVN->getSExtValue(); } else return SDValue(); unsigned Opcode; bool IsRightShift; switch (IID) { default: llvm_unreachable("Unknown shift intrinsic"); case Intrinsic::aarch64_neon_sqshl: Opcode = AArch64ISD::SQSHL_I; IsRightShift = false; break; case Intrinsic::aarch64_neon_uqshl: Opcode = AArch64ISD::UQSHL_I; IsRightShift = false; break; case Intrinsic::aarch64_neon_srshl: Opcode = AArch64ISD::SRSHR_I; IsRightShift = true; break; case Intrinsic::aarch64_neon_urshl: Opcode = AArch64ISD::URSHR_I; IsRightShift = true; break; case Intrinsic::aarch64_neon_sqshlu: Opcode = AArch64ISD::SQSHLU_I; IsRightShift = false; break; } if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { SDLoc dl(N); return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), DAG.getConstant(-ShiftAmount, dl, MVT::i32)); } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { SDLoc dl(N); return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), DAG.getConstant(ShiftAmount, dl, MVT::i32)); } return SDValue(); } // The CRC32[BH] instructions ignore the high bits of their data operand. Since // the intrinsics must be legal and take an i32, this means there's almost // certainly going to be a zext in the DAG which we can eliminate. static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { SDValue AndN = N->getOperand(2); if (AndN.getOpcode() != ISD::AND) return SDValue(); ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); if (!CMask || CMask->getZExtValue() != Mask) return SDValue(); return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); } static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, SelectionDAG &DAG) { SDLoc dl(N); return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), DAG.getNode(Opc, dl, N->getOperand(1).getSimpleValueType(), N->getOperand(1)), DAG.getConstant(0, dl, MVT::i64)); } static SDValue performIntrinsicCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, const AArch64Subtarget *Subtarget) { SelectionDAG &DAG = DCI.DAG; unsigned IID = getIntrinsicID(N); switch (IID) { default: break; case Intrinsic::aarch64_neon_vcvtfxs2fp: case Intrinsic::aarch64_neon_vcvtfxu2fp: return tryCombineFixedPointConvert(N, DCI, DAG); case Intrinsic::aarch64_neon_saddv: return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); case Intrinsic::aarch64_neon_uaddv: return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); case Intrinsic::aarch64_neon_sminv: return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); case Intrinsic::aarch64_neon_uminv: return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); case Intrinsic::aarch64_neon_smaxv: return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); case Intrinsic::aarch64_neon_umaxv: return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); case Intrinsic::aarch64_neon_fmax: return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), N->getOperand(1), N->getOperand(2)); case Intrinsic::aarch64_neon_fmin: return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), N->getOperand(1), N->getOperand(2)); case Intrinsic::aarch64_neon_fmaxnm: return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), N->getOperand(1), N->getOperand(2)); case Intrinsic::aarch64_neon_fminnm: return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), N->getOperand(1), N->getOperand(2)); case Intrinsic::aarch64_neon_smull: case Intrinsic::aarch64_neon_umull: case Intrinsic::aarch64_neon_pmull: case Intrinsic::aarch64_neon_sqdmull: return tryCombineLongOpWithDup(IID, N, DCI, DAG); case Intrinsic::aarch64_neon_sqshl: case Intrinsic::aarch64_neon_uqshl: case Intrinsic::aarch64_neon_sqshlu: case Intrinsic::aarch64_neon_srshl: case Intrinsic::aarch64_neon_urshl: return tryCombineShiftImm(IID, N, DAG); case Intrinsic::aarch64_crc32b: case Intrinsic::aarch64_crc32cb: return tryCombineCRC32(0xff, N, DAG); case Intrinsic::aarch64_crc32h: case Intrinsic::aarch64_crc32ch: return tryCombineCRC32(0xffff, N, DAG); } return SDValue(); } static SDValue performExtendCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then // we can convert that DUP into another extract_high (of a bigger DUP), which // helps the backend to decide that an sabdl2 would be useful, saving a real // extract_high operation. if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { SDNode *ABDNode = N->getOperand(0).getNode(); unsigned IID = getIntrinsicID(ABDNode); if (IID == Intrinsic::aarch64_neon_sabd || IID == Intrinsic::aarch64_neon_uabd) { SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); if (!NewABD.getNode()) return SDValue(); return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD); } } // This is effectively a custom type legalization for AArch64. // // Type legalization will split an extend of a small, legal, type to a larger // illegal type by first splitting the destination type, often creating // illegal source types, which then get legalized in isel-confusing ways, // leading to really terrible codegen. E.g., // %result = v8i32 sext v8i8 %value // becomes // %losrc = extract_subreg %value, ... // %hisrc = extract_subreg %value, ... // %lo = v4i32 sext v4i8 %losrc // %hi = v4i32 sext v4i8 %hisrc // Things go rapidly downhill from there. // // For AArch64, the [sz]ext vector instructions can only go up one element // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 // take two instructions. // // This implies that the most efficient way to do the extend from v8i8 // to two v4i32 values is to first extend the v8i8 to v8i16, then do // the normal splitting to happen for the v8i16->v8i32. // This is pre-legalization to catch some cases where the default // type legalization will create ill-tempered code. if (!DCI.isBeforeLegalizeOps()) return SDValue(); // We're only interested in cleaning things up for non-legal vector types // here. If both the source and destination are legal, things will just // work naturally without any fiddling. const TargetLowering &TLI = DAG.getTargetLoweringInfo(); EVT ResVT = N->getValueType(0); if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) return SDValue(); // If the vector type isn't a simple VT, it's beyond the scope of what // we're worried about here. Let legalization do its thing and hope for // the best. SDValue Src = N->getOperand(0); EVT SrcVT = Src->getValueType(0); if (!ResVT.isSimple() || !SrcVT.isSimple()) return SDValue(); // If the source VT is a 64-bit vector, we can play games and get the // better results we want. if (SrcVT.getSizeInBits() != 64) return SDValue(); unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); unsigned ElementCount = SrcVT.getVectorNumElements(); SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); SDLoc DL(N); Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); // Now split the rest of the operation into two halves, each with a 64 // bit source. EVT LoVT, HiVT; SDValue Lo, Hi; unsigned NumElements = ResVT.getVectorNumElements(); assert(!(NumElements & 1) && "Splitting vector, but not in half!"); LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(), NumElements / 2); EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), LoVT.getVectorNumElements()); Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, DAG.getConstant(0, DL, MVT::i64)); Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); // Now combine the parts back together so we still have a single result // like the combiner expects. return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); } static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, SDValue SplatVal, unsigned NumVecElts) { assert(!St.isTruncatingStore() && "cannot split truncating vector store"); unsigned OrigAlignment = St.getAlignment(); unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; // Create scalar stores. This is at least as good as the code sequence for a // split unaligned store which is a dup.s, ext.b, and two stores. // Most of the time the three stores should be replaced by store pair // instructions (stp). SDLoc DL(&St); SDValue BasePtr = St.getBasePtr(); uint64_t BaseOffset = 0; const MachinePointerInfo &PtrInfo = St.getPointerInfo(); SDValue NewST1 = DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, OrigAlignment, St.getMemOperand()->getFlags()); // As this in ISel, we will not merge this add which may degrade results. if (BasePtr->getOpcode() == ISD::ADD && isa<ConstantSDNode>(BasePtr->getOperand(1))) { BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); BasePtr = BasePtr->getOperand(0); } unsigned Offset = EltOffset; while (--NumVecElts) { unsigned Alignment = MinAlign(OrigAlignment, Offset); SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, PtrInfo.getWithOffset(Offset), Alignment, St.getMemOperand()->getFlags()); Offset += EltOffset; } return NewST1; } /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The /// load store optimizer pass will merge them to store pair stores. This should /// be better than a movi to create the vector zero followed by a vector store /// if the zero constant is not re-used, since one instructions and one register /// live range will be removed. /// /// For example, the final generated code should be: /// /// stp xzr, xzr, [x0] /// /// instead of: /// /// movi v0.2d, #0 /// str q0, [x0] /// static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { SDValue StVal = St.getValue(); EVT VT = StVal.getValueType(); // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or // 2, 3 or 4 i32 elements. int NumVecElts = VT.getVectorNumElements(); if (!(((NumVecElts == 2 || NumVecElts == 3) && VT.getVectorElementType().getSizeInBits() == 64) || ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && VT.getVectorElementType().getSizeInBits() == 32))) return SDValue(); if (StVal.getOpcode() != ISD::BUILD_VECTOR) return SDValue(); // If the zero constant has more than one use then the vector store could be // better since the constant mov will be amortized and stp q instructions // should be able to be formed. if (!StVal.hasOneUse()) return SDValue(); // If the store is truncating then it's going down to i16 or smaller, which // means it can be implemented in a single store anyway. if (St.isTruncatingStore()) return SDValue(); // If the immediate offset of the address operand is too large for the stp // instruction, then bail out. if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); if (Offset < -512 || Offset > 504) return SDValue(); } for (int I = 0; I < NumVecElts; ++I) { SDValue EltVal = StVal.getOperand(I); if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) return SDValue(); } // Use a CopyFromReg WZR/XZR here to prevent // DAGCombiner::MergeConsecutiveStores from undoing this transformation. SDLoc DL(&St); unsigned ZeroReg; EVT ZeroVT; if (VT.getVectorElementType().getSizeInBits() == 32) { ZeroReg = AArch64::WZR; ZeroVT = MVT::i32; } else { ZeroReg = AArch64::XZR; ZeroVT = MVT::i64; } SDValue SplatVal = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); return splitStoreSplat(DAG, St, SplatVal, NumVecElts); } /// Replace a splat of a scalar to a vector store by scalar stores of the scalar /// value. The load store optimizer pass will merge them to store pair stores. /// This has better performance than a splat of the scalar followed by a split /// vector store. Even if the stores are not merged it is four stores vs a dup, /// followed by an ext.b and two stores. static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { SDValue StVal = St.getValue(); EVT VT = StVal.getValueType(); // Don't replace floating point stores, they possibly won't be transformed to // stp because of the store pair suppress pass. if (VT.isFloatingPoint()) return SDValue(); // We can express a splat as store pair(s) for 2 or 4 elements. unsigned NumVecElts = VT.getVectorNumElements(); if (NumVecElts != 4 && NumVecElts != 2) return SDValue(); // If the store is truncating then it's going down to i16 or smaller, which // means it can be implemented in a single store anyway. if (St.isTruncatingStore()) return SDValue(); // Check that this is a splat. // Make sure that each of the relevant vector element locations are inserted // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); SDValue SplatVal; for (unsigned I = 0; I < NumVecElts; ++I) { // Check for insert vector elements. if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) return SDValue(); // Check that same value is inserted at each vector element. if (I == 0) SplatVal = StVal.getOperand(1); else if (StVal.getOperand(1) != SplatVal) return SDValue(); // Check insert element index. ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); if (!CIndex) return SDValue(); uint64_t IndexVal = CIndex->getZExtValue(); if (IndexVal >= NumVecElts) return SDValue(); IndexNotInserted.reset(IndexVal); StVal = StVal.getOperand(0); } // Check that all vector element locations were inserted to. if (IndexNotInserted.any()) return SDValue(); return splitStoreSplat(DAG, St, SplatVal, NumVecElts); } static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG, const AArch64Subtarget *Subtarget) { StoreSDNode *S = cast<StoreSDNode>(N); if (S->isVolatile() || S->isIndexed()) return SDValue(); SDValue StVal = S->getValue(); EVT VT = StVal.getValueType(); if (!VT.isVector()) return SDValue(); // If we get a splat of zeros, convert this vector store to a store of // scalars. They will be merged into store pairs of xzr thereby removing one // instruction and one register. if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) return ReplacedZeroSplat; // FIXME: The logic for deciding if an unaligned store should be split should // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be // a call to that function here. if (!Subtarget->isMisaligned128StoreSlow()) return SDValue(); // Don't split at -Oz. if (DAG.getMachineFunction().getFunction().optForMinSize()) return SDValue(); // Don't split v2i64 vectors. Memcpy lowering produces those and splitting // those up regresses performance on micro-benchmarks and olden/bh. if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) return SDValue(); // Split unaligned 16B stores. They are terrible for performance. // Don't split stores with alignment of 1 or 2. Code that uses clang vector // extensions can use this to mark that it does not want splitting to happen // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of // eliminating alignment hazards is only 1 in 8 for alignment of 2. if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || S->getAlignment() <= 2) return SDValue(); // If we get a splat of a scalar convert this vector store to a store of // scalars. They will be merged into store pairs thereby removing two // instructions. if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) return ReplacedSplat; SDLoc DL(S); unsigned NumElts = VT.getVectorNumElements() / 2; // Split VT into two. EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, DAG.getConstant(0, DL, MVT::i64)); SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, DAG.getConstant(NumElts, DL, MVT::i64)); SDValue BasePtr = S->getBasePtr(); SDValue NewST1 = DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), S->getAlignment(), S->getMemOperand()->getFlags()); SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, DAG.getConstant(8, DL, MVT::i64)); return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, S->getPointerInfo(), S->getAlignment(), S->getMemOperand()->getFlags()); } /// Target-specific DAG combine function for post-increment LD1 (lane) and /// post-increment LD1R. static SDValue performPostLD1Combine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, bool IsLaneOp) { if (DCI.isBeforeLegalizeOps()) return SDValue(); SelectionDAG &DAG = DCI.DAG; EVT VT = N->getValueType(0); unsigned LoadIdx = IsLaneOp ? 1 : 0; SDNode *LD = N->getOperand(LoadIdx).getNode(); // If it is not LOAD, can not do such combine. if (LD->getOpcode() != ISD::LOAD) return SDValue(); // The vector lane must be a constant in the LD1LANE opcode. SDValue Lane; if (IsLaneOp) { Lane = N->getOperand(2); auto *LaneC = dyn_cast<ConstantSDNode>(Lane); if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) return SDValue(); } LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); EVT MemVT = LoadSDN->getMemoryVT(); // Check if memory operand is the same type as the vector element. if (MemVT != VT.getVectorElementType()) return SDValue(); // Check if there are other uses. If so, do not combine as it will introduce // an extra load. for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; ++UI) { if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. continue; if (*UI != N) return SDValue(); } SDValue Addr = LD->getOperand(1); SDValue Vector = N->getOperand(0); // Search for a use of the address operand that is an increment. for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = Addr.getNode()->use_end(); UI != UE; ++UI) { SDNode *User = *UI; if (User->getOpcode() != ISD::ADD || UI.getUse().getResNo() != Addr.getResNo()) continue; // If the increment is a constant, it must match the memory ref size. SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { uint32_t IncVal = CInc->getZExtValue(); unsigned NumBytes = VT.getScalarSizeInBits() / 8; if (IncVal != NumBytes) continue; Inc = DAG.getRegister(AArch64::XZR, MVT::i64); } // To avoid cycle construction make sure that neither the load nor the add // are predecessors to each other or the Vector. SmallPtrSet<const SDNode *, 32> Visited; SmallVector<const SDNode *, 16> Worklist; Visited.insert(N); Worklist.push_back(User); Worklist.push_back(LD); Worklist.push_back(Vector.getNode()); if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || SDNode::hasPredecessorHelper(User, Visited, Worklist)) continue; SmallVector<SDValue, 8> Ops; Ops.push_back(LD->getOperand(0)); // Chain if (IsLaneOp) { Ops.push_back(Vector); // The vector to be inserted Ops.push_back(Lane); // The lane to be inserted in the vector } Ops.push_back(Addr); Ops.push_back(Inc); EVT Tys[3] = { VT, MVT::i64, MVT::Other }; SDVTList SDTys = DAG.getVTList(Tys); unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, MemVT, LoadSDN->getMemOperand()); // Update the uses. SDValue NewResults[] = { SDValue(LD, 0), // The result of load SDValue(UpdN.getNode(), 2) // Chain }; DCI.CombineTo(LD, NewResults); DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register break; } return SDValue(); } /// Simplify ``Addr`` given that the top byte of it is ignored by HW during /// address translation. static bool performTBISimplification(SDValue Addr, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { APInt DemandedMask = APInt::getLowBitsSet(64, 56); KnownBits Known; TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), !DCI.isBeforeLegalizeOps()); const TargetLowering &TLI = DAG.getTargetLoweringInfo(); if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { DCI.CommitTargetLoweringOpt(TLO); return true; } return false; } static SDValue performSTORECombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG, const AArch64Subtarget *Subtarget) { if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) return Split; if (Subtarget->supportsAddressTopByteIgnored() && performTBISimplification(N->getOperand(2), DCI, DAG)) return SDValue(N, 0); return SDValue(); } /// Target-specific DAG combine function for NEON load/store intrinsics /// to merge base address updates. static SDValue performNEONPostLDSTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) return SDValue(); unsigned AddrOpIdx = N->getNumOperands() - 1; SDValue Addr = N->getOperand(AddrOpIdx); // Search for a use of the address operand that is an increment. for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = Addr.getNode()->use_end(); UI != UE; ++UI) { SDNode *User = *UI; if (User->getOpcode() != ISD::ADD || UI.getUse().getResNo() != Addr.getResNo()) continue; // Check that the add is independent of the load/store. Otherwise, folding // it would create a cycle. SmallPtrSet<const SDNode *, 32> Visited; SmallVector<const SDNode *, 16> Worklist; Visited.insert(Addr.getNode()); Worklist.push_back(N); Worklist.push_back(User); if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || SDNode::hasPredecessorHelper(User, Visited, Worklist)) continue; // Find the new opcode for the updating load/store. bool IsStore = false; bool IsLaneOp = false; bool IsDupOp = false; unsigned NewOpc = 0; unsigned NumVecs = 0; unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); switch (IntNo) { default: llvm_unreachable("unexpected intrinsic for Neon base update"); case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; NumVecs = 2; break; case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; NumVecs = 3; break; case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; NumVecs = 4; break; case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; NumVecs = 2; IsStore = true; break; case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; NumVecs = 3; IsStore = true; break; case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; NumVecs = 4; IsStore = true; break; case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; NumVecs = 2; break; case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; NumVecs = 3; break; case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; NumVecs = 4; break; case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; NumVecs = 2; IsStore = true; break; case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; NumVecs = 3; IsStore = true; break; case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; NumVecs = 4; IsStore = true; break; case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; NumVecs = 2; IsDupOp = true; break; case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; NumVecs = 3; IsDupOp = true; break; case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; NumVecs = 4; IsDupOp = true; break; case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; NumVecs = 2; IsLaneOp = true; break; case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; NumVecs = 3; IsLaneOp = true; break; case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; NumVecs = 4; IsLaneOp = true; break; case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; NumVecs = 2; IsStore = true; IsLaneOp = true; break; case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; NumVecs = 3; IsStore = true; IsLaneOp = true; break; case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; NumVecs = 4; IsStore = true; IsLaneOp = true; break; } EVT VecTy; if (IsStore) VecTy = N->getOperand(2).getValueType(); else VecTy = N->getValueType(0); // If the increment is a constant, it must match the memory ref size. SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { uint32_t IncVal = CInc->getZExtValue(); unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; if (IsLaneOp || IsDupOp) NumBytes /= VecTy.getVectorNumElements(); if (IncVal != NumBytes) continue; Inc = DAG.getRegister(AArch64::XZR, MVT::i64); } SmallVector<SDValue, 8> Ops; Ops.push_back(N->getOperand(0)); // Incoming chain // Load lane and store have vector list as input. if (IsLaneOp || IsStore) for (unsigned i = 2; i < AddrOpIdx; ++i) Ops.push_back(N->getOperand(i)); Ops.push_back(Addr); // Base register Ops.push_back(Inc); // Return Types. EVT Tys[6]; unsigned NumResultVecs = (IsStore ? 0 : NumVecs); unsigned n; for (n = 0; n < NumResultVecs; ++n) Tys[n] = VecTy; Tys[n++] = MVT::i64; // Type of write back register Tys[n] = MVT::Other; // Type of the chain SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, MemInt->getMemoryVT(), MemInt->getMemOperand()); // Update the uses. std::vector<SDValue> NewResults; for (unsigned i = 0; i < NumResultVecs; ++i) { NewResults.push_back(SDValue(UpdN.getNode(), i)); } NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); DCI.CombineTo(N, NewResults); DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); break; } return SDValue(); } // Checks to see if the value is the prescribed width and returns information // about its extension mode. static bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { ExtType = ISD::NON_EXTLOAD; switch(V.getNode()->getOpcode()) { default: return false; case ISD::LOAD: { LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { ExtType = LoadNode->getExtensionType(); return true; } return false; } case ISD::AssertSext: { VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); if ((TypeNode->getVT() == MVT::i8 && width == 8) || (TypeNode->getVT() == MVT::i16 && width == 16)) { ExtType = ISD::SEXTLOAD; return true; } return false; } case ISD::AssertZext: { VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); if ((TypeNode->getVT() == MVT::i8 && width == 8) || (TypeNode->getVT() == MVT::i16 && width == 16)) { ExtType = ISD::ZEXTLOAD; return true; } return false; } case ISD::Constant: case ISD::TargetConstant: { return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 1LL << (width - 1); } } return true; } // This function does a whole lot of voodoo to determine if the tests are // equivalent without and with a mask. Essentially what happens is that given a // DAG resembling: // // +-------------+ +-------------+ +-------------+ +-------------+ // | Input | | AddConstant | | CompConstant| | CC | // +-------------+ +-------------+ +-------------+ +-------------+ // | | | | // V V | +----------+ // +-------------+ +----+ | | // | ADD | |0xff| | | // +-------------+ +----+ | | // | | | | // V V | | // +-------------+ | | // | AND | | | // +-------------+ | | // | | | // +-----+ | | // | | | // V V V // +-------------+ // | CMP | // +-------------+ // // The AND node may be safely removed for some combinations of inputs. In // particular we need to take into account the extension type of the Input, // the exact values of AddConstant, CompConstant, and CC, along with the nominal // width of the input (this can work for any width inputs, the above graph is // specific to 8 bits. // // The specific equations were worked out by generating output tables for each // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The // problem was simplified by working with 4 bit inputs, which means we only // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 // patterns present in both extensions (0,7). For every distinct set of // AddConstant and CompConstants bit patterns we can consider the masked and // unmasked versions to be equivalent if the result of this function is true for // all 16 distinct bit patterns of for the current extension type of Input (w0). // // sub w8, w0, w1 // and w10, w8, #0x0f // cmp w8, w2 // cset w9, AArch64CC // cmp w10, w2 // cset w11, AArch64CC // cmp w9, w11 // cset w0, eq // ret // // Since the above function shows when the outputs are equivalent it defines // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and // would be expensive to run during compiles. The equations below were written // in a test harness that confirmed they gave equivalent outputs to the above // for all inputs function, so they can be used determine if the removal is // legal instead. // // isEquivalentMaskless() is the code for testing if the AND can be removed // factored out of the DAG recognition as the DAG can take several forms. static bool isEquivalentMaskless(unsigned CC, unsigned width, ISD::LoadExtType ExtType, int AddConstant, int CompConstant) { // By being careful about our equations and only writing the in term // symbolic values and well known constants (0, 1, -1, MaxUInt) we can // make them generally applicable to all bit widths. int MaxUInt = (1 << width); // For the purposes of these comparisons sign extending the type is // equivalent to zero extending the add and displacing it by half the integer // width. Provided we are careful and make sure our equations are valid over // the whole range we can just adjust the input and avoid writing equations // for sign extended inputs. if (ExtType == ISD::SEXTLOAD) AddConstant -= (1 << (width-1)); switch(CC) { case AArch64CC::LE: case AArch64CC::GT: if ((AddConstant == 0) || (CompConstant == MaxUInt - 1 && AddConstant < 0) || (AddConstant >= 0 && CompConstant < 0) || (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) return true; break; case AArch64CC::LT: case AArch64CC::GE: if ((AddConstant == 0) || (AddConstant >= 0 && CompConstant <= 0) || (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) return true; break; case AArch64CC::HI: case AArch64CC::LS: if ((AddConstant >= 0 && CompConstant < 0) || (AddConstant <= 0 && CompConstant >= -1 && CompConstant < AddConstant + MaxUInt)) return true; break; case AArch64CC::PL: case AArch64CC::MI: if ((AddConstant == 0) || (AddConstant > 0 && CompConstant <= 0) || (AddConstant < 0 && CompConstant <= AddConstant)) return true; break; case AArch64CC::LO: case AArch64CC::HS: if ((AddConstant >= 0 && CompConstant <= 0) || (AddConstant <= 0 && CompConstant >= 0 && CompConstant <= AddConstant + MaxUInt)) return true; break; case AArch64CC::EQ: case AArch64CC::NE: if ((AddConstant > 0 && CompConstant < 0) || (AddConstant < 0 && CompConstant >= 0 && CompConstant < AddConstant + MaxUInt) || (AddConstant >= 0 && CompConstant >= 0 && CompConstant >= AddConstant) || (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) return true; break; case AArch64CC::VS: case AArch64CC::VC: case AArch64CC::AL: case AArch64CC::NV: return true; case AArch64CC::Invalid: break; } return false; } static SDValue performCONDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG, unsigned CCIndex, unsigned CmpIndex) { unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); unsigned CondOpcode = SubsNode->getOpcode(); if (CondOpcode != AArch64ISD::SUBS) return SDValue(); // There is a SUBS feeding this condition. Is it fed by a mask we can // use? SDNode *AndNode = SubsNode->getOperand(0).getNode(); unsigned MaskBits = 0; if (AndNode->getOpcode() != ISD::AND) return SDValue(); if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { uint32_t CNV = CN->getZExtValue(); if (CNV == 255) MaskBits = 8; else if (CNV == 65535) MaskBits = 16; } if (!MaskBits) return SDValue(); SDValue AddValue = AndNode->getOperand(0); if (AddValue.getOpcode() != ISD::ADD) return SDValue(); // The basic dag structure is correct, grab the inputs and validate them. SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); SDValue SubsInputValue = SubsNode->getOperand(1); // The mask is present and the provenance of all the values is a smaller type, // lets see if the mask is superfluous. if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || !isa<ConstantSDNode>(SubsInputValue.getNode())) return SDValue(); ISD::LoadExtType ExtType; if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || !checkValueWidth(AddInputValue2, MaskBits, ExtType) || !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) return SDValue(); if(!isEquivalentMaskless(CC, MaskBits, ExtType, cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) return SDValue(); // The AND is not necessary, remove it. SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), SubsNode->getValueType(1)); SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); return SDValue(N, 0); } // Optimize compare with zero and branch. static SDValue performBRCONDCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { MachineFunction &MF = DAG.getMachineFunction(); // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions // will not be produced, as they are conditional branch instructions that do // not set flags. if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) return SDValue(); if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) N = NV.getNode(); SDValue Chain = N->getOperand(0); SDValue Dest = N->getOperand(1); SDValue CCVal = N->getOperand(2); SDValue Cmp = N->getOperand(3); assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); if (CC != AArch64CC::EQ && CC != AArch64CC::NE) return SDValue(); unsigned CmpOpc = Cmp.getOpcode(); if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) return SDValue(); // Only attempt folding if there is only one use of the flag and no use of the // value. if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) return SDValue(); SDValue LHS = Cmp.getOperand(0); SDValue RHS = Cmp.getOperand(1); assert(LHS.getValueType() == RHS.getValueType() && "Expected the value type to be the same for both operands!"); if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) return SDValue(); if (isNullConstant(LHS)) std::swap(LHS, RHS); if (!isNullConstant(RHS)) return SDValue(); if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || LHS.getOpcode() == ISD::SRL) return SDValue(); // Fold the compare into the branch instruction. SDValue BR; if (CC == AArch64CC::EQ) BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); else BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); // Do not add new nodes to DAG combiner worklist. DCI.CombineTo(N, BR, false); return SDValue(); } // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test // as well as whether the test should be inverted. This code is required to // catch these cases (as opposed to standard dag combines) because // AArch64ISD::TBZ is matched during legalization. static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, SelectionDAG &DAG) { if (!Op->hasOneUse()) return Op; // We don't handle undef/constant-fold cases below, as they should have // already been taken care of (e.g. and of 0, test of undefined shifted bits, // etc.) // (tbz (trunc x), b) -> (tbz x, b) // This case is just here to enable more of the below cases to be caught. if (Op->getOpcode() == ISD::TRUNCATE && Bit < Op->getValueType(0).getSizeInBits()) { return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); } if (Op->getNumOperands() != 2) return Op; auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); if (!C) return Op; switch (Op->getOpcode()) { default: return Op; // (tbz (and x, m), b) -> (tbz x, b) case ISD::AND: if ((C->getZExtValue() >> Bit) & 1) return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); return Op; // (tbz (shl x, c), b) -> (tbz x, b-c) case ISD::SHL: if (C->getZExtValue() <= Bit && (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { Bit = Bit - C->getZExtValue(); return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); } return Op; // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x case ISD::SRA: Bit = Bit + C->getZExtValue(); if (Bit >= Op->getValueType(0).getSizeInBits()) Bit = Op->getValueType(0).getSizeInBits() - 1; return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); // (tbz (srl x, c), b) -> (tbz x, b+c) case ISD::SRL: if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { Bit = Bit + C->getZExtValue(); return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); } return Op; // (tbz (xor x, -1), b) -> (tbnz x, b) case ISD::XOR: if ((C->getZExtValue() >> Bit) & 1) Invert = !Invert; return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); } } // Optimize test single bit zero/non-zero and branch. static SDValue performTBZCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, SelectionDAG &DAG) { unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); bool Invert = false; SDValue TestSrc = N->getOperand(1); SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); if (TestSrc == NewTestSrc) return SDValue(); unsigned NewOpc = N->getOpcode(); if (Invert) { if (NewOpc == AArch64ISD::TBZ) NewOpc = AArch64ISD::TBNZ; else { assert(NewOpc == AArch64ISD::TBNZ); NewOpc = AArch64ISD::TBZ; } } SDLoc DL(N); return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); } // vselect (v1i1 setcc) -> // vselect (v1iXX setcc) (XX is the size of the compared operand type) // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine // such VSELECT. static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { SDValue N0 = N->getOperand(0); EVT CCVT = N0.getValueType(); if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || CCVT.getVectorElementType() != MVT::i1) return SDValue(); EVT ResVT = N->getValueType(0); EVT CmpVT = N0.getOperand(0).getValueType(); // Only combine when the result type is of the same size as the compared // operands. if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) return SDValue(); SDValue IfTrue = N->getOperand(1); SDValue IfFalse = N->getOperand(2); SDValue SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), N0.getOperand(0), N0.getOperand(1), cast<CondCodeSDNode>(N0.getOperand(2))->get()); return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, IfTrue, IfFalse); } /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with /// the compare-mask instructions rather than going via NZCV, even if LHS and /// RHS are really scalar. This replaces any scalar setcc in the above pattern /// with a vector one followed by a DUP shuffle on the result. static SDValue performSelectCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) { SelectionDAG &DAG = DCI.DAG; SDValue N0 = N->getOperand(0); EVT ResVT = N->getValueType(0); if (N0.getOpcode() != ISD::SETCC) return SDValue(); // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered // scalar SetCCResultType. We also don't expect vectors, because we assume // that selects fed by vector SETCCs are canonicalized to VSELECT. assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && "Scalar-SETCC feeding SELECT has unexpected result type!"); // If NumMaskElts == 0, the comparison is larger than select result. The // largest real NEON comparison is 64-bits per lane, which means the result is // at most 32-bits and an illegal vector. Just bail out for now. EVT SrcVT = N0.getOperand(0).getValueType(); // Don't try to do this optimization when the setcc itself has i1 operands. // There are no legal vectors of i1, so this would be pointless. if (SrcVT == MVT::i1) return SDValue(); int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); if (!ResVT.isVector() || NumMaskElts == 0) return SDValue(); SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); // Also bail out if the vector CCVT isn't the same size as ResVT. // This can happen if the SETCC operand size doesn't divide the ResVT size // (e.g., f64 vs v3f32). if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) return SDValue(); // Make sure we didn't create illegal types, if we're not supposed to. assert(DCI.isBeforeLegalize() || DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); // First perform a vector comparison, where lane 0 is the one we're interested // in. SDLoc DL(N0); SDValue LHS = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); SDValue RHS = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); // Now duplicate the comparison mask we want across all other lanes. SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); Mask = DAG.getNode(ISD::BITCAST, DL, ResVT.changeVectorElementTypeToInteger(), Mask); return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); } /// Get rid of unnecessary NVCASTs (that don't change the type). static SDValue performNVCASTCombine(SDNode *N) { if (N->getValueType(0) == N->getOperand(0).getValueType()) return N->getOperand(0); return SDValue(); } // If all users of the globaladdr are of the form (globaladdr + constant), find // the smallest constant, fold it into the globaladdr's offset and rewrite the // globaladdr as (globaladdr + constant) - constant. static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, const AArch64Subtarget *Subtarget, const TargetMachine &TM) { auto *GN = cast<GlobalAddressSDNode>(N); if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != AArch64II::MO_NO_FLAG) return SDValue(); uint64_t MinOffset = -1ull; for (SDNode *N : GN->uses()) { if (N->getOpcode() != ISD::ADD) return SDValue(); auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); if (!C) C = dyn_cast<ConstantSDNode>(N->getOperand(1)); if (!C) return SDValue(); MinOffset = std::min(MinOffset, C->getZExtValue()); } uint64_t Offset = MinOffset + GN->getOffset(); // Require that the new offset is larger than the existing one. Otherwise, we // can end up oscillating between two possible DAGs, for example, // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). if (Offset <= uint64_t(GN->getOffset())) return SDValue(); // Check whether folding this offset is legal. It must not go out of bounds of // the referenced object to avoid violating the code model, and must be // smaller than 2^21 because this is the largest offset expressible in all // object formats. // // This check also prevents us from folding negative offsets, which will end // up being treated in the same way as large positive ones. They could also // cause code model violations, and aren't really common enough to matter. if (Offset >= (1 << 21)) return SDValue(); const GlobalValue *GV = GN->getGlobal(); Type *T = GV->getValueType(); if (!T->isSized() || Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) return SDValue(); SDLoc DL(GN); SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, DAG.getConstant(MinOffset, DL, MVT::i64)); } SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const { SelectionDAG &DAG = DCI.DAG; switch (N->getOpcode()) { default: LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); break; case ISD::ADD: case ISD::SUB: return performAddSubLongCombine(N, DCI, DAG); case ISD::XOR: return performXorCombine(N, DAG, DCI, Subtarget); case ISD::MUL: return performMulCombine(N, DAG, DCI, Subtarget); case ISD::SINT_TO_FP: case ISD::UINT_TO_FP: return performIntToFpCombine(N, DAG, Subtarget); case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: return performFpToIntCombine(N, DAG, DCI, Subtarget); case ISD::FDIV: return performFDivCombine(N, DAG, DCI, Subtarget); case ISD::OR: return performORCombine(N, DCI, Subtarget); case ISD::AND: return performANDCombine(N, DCI); case ISD::SRL: return performSRLCombine(N, DCI); case ISD::INTRINSIC_WO_CHAIN: return performIntrinsicCombine(N, DCI, Subtarget); case ISD::ANY_EXTEND: case ISD::ZERO_EXTEND: case ISD::SIGN_EXTEND: return performExtendCombine(N, DCI, DAG); case ISD::BITCAST: return performBitcastCombine(N, DCI, DAG); case ISD::CONCAT_VECTORS: return performConcatVectorsCombine(N, DCI, DAG); case ISD::SELECT: return performSelectCombine(N, DCI); case ISD::VSELECT: return performVSelectCombine(N, DCI.DAG); case ISD::LOAD: if (performTBISimplification(N->getOperand(1), DCI, DAG)) return SDValue(N, 0); break; case ISD::STORE: return performSTORECombine(N, DCI, DAG, Subtarget); case AArch64ISD::BRCOND: return performBRCONDCombine(N, DCI, DAG); case AArch64ISD::TBNZ: case AArch64ISD::TBZ: return performTBZCombine(N, DCI, DAG); case AArch64ISD::CSEL: return performCONDCombine(N, DCI, DAG, 2, 3); case AArch64ISD::DUP: return performPostLD1Combine(N, DCI, false); case AArch64ISD::NVCAST: return performNVCASTCombine(N); case ISD::INSERT_VECTOR_ELT: return performPostLD1Combine(N, DCI, true); case ISD::INTRINSIC_VOID: case ISD::INTRINSIC_W_CHAIN: switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { case Intrinsic::aarch64_neon_ld2: case Intrinsic::aarch64_neon_ld3: case Intrinsic::aarch64_neon_ld4: case Intrinsic::aarch64_neon_ld1x2: case Intrinsic::aarch64_neon_ld1x3: case Intrinsic::aarch64_neon_ld1x4: case Intrinsic::aarch64_neon_ld2lane: case Intrinsic::aarch64_neon_ld3lane: case Intrinsic::aarch64_neon_ld4lane: case Intrinsic::aarch64_neon_ld2r: case Intrinsic::aarch64_neon_ld3r: case Intrinsic::aarch64_neon_ld4r: case Intrinsic::aarch64_neon_st2: case Intrinsic::aarch64_neon_st3: case Intrinsic::aarch64_neon_st4: case Intrinsic::aarch64_neon_st1x2: case Intrinsic::aarch64_neon_st1x3: case Intrinsic::aarch64_neon_st1x4: case Intrinsic::aarch64_neon_st2lane: case Intrinsic::aarch64_neon_st3lane: case Intrinsic::aarch64_neon_st4lane: return performNEONPostLDSTCombine(N, DCI, DAG); default: break; } break; case ISD::GlobalAddress: return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); } return SDValue(); } // Check if the return value is used as only a return value, as otherwise // we can't perform a tail-call. In particular, we need to check for // target ISD nodes that are returns and any other "odd" constructs // that the generic analysis code won't necessarily catch. bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const { if (N->getNumValues() != 1) return false; if (!N->hasNUsesOfValue(1, 0)) return false; SDValue TCChain = Chain; SDNode *Copy = *N->use_begin(); if (Copy->getOpcode() == ISD::CopyToReg) { // If the copy has a glue operand, we conservatively assume it isn't safe to // perform a tail call. if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == MVT::Glue) return false; TCChain = Copy->getOperand(0); } else if (Copy->getOpcode() != ISD::FP_EXTEND) return false; bool HasRet = false; for (SDNode *Node : Copy->uses()) { if (Node->getOpcode() != AArch64ISD::RET_FLAG) return false; HasRet = true; } if (!HasRet) return false; Chain = TCChain; return true; } // Return whether the an instruction can potentially be optimized to a tail // call. This will cause the optimizers to attempt to move, or duplicate, // return instructions to help enable tail call optimizations for this // instruction. bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { return CI->isTailCall(); } bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, bool &IsInc, SelectionDAG &DAG) const { if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) return false; Base = Op->getOperand(0); // All of the indexed addressing mode instructions take a signed // 9 bit immediate offset. if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { int64_t RHSC = RHS->getSExtValue(); if (Op->getOpcode() == ISD::SUB) RHSC = -(uint64_t)RHSC; if (!isInt<9>(RHSC)) return false; IsInc = (Op->getOpcode() == ISD::ADD); Offset = Op->getOperand(1); return true; } return false; } bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { EVT VT; SDValue Ptr; if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { VT = LD->getMemoryVT(); Ptr = LD->getBasePtr(); } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { VT = ST->getMemoryVT(); Ptr = ST->getBasePtr(); } else return false; bool IsInc; if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) return false; AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; return true; } bool AArch64TargetLowering::getPostIndexedAddressParts( SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { EVT VT; SDValue Ptr; if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { VT = LD->getMemoryVT(); Ptr = LD->getBasePtr(); } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { VT = ST->getMemoryVT(); Ptr = ST->getBasePtr(); } else return false; bool IsInc; if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) return false; // Post-indexing updates the base, so it's not a valid transform // if that's not the same as the load's pointer. if (Ptr != Base) return false; AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; return true; } static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) { SDLoc DL(N); SDValue Op = N->getOperand(0); if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) return; Op = SDValue( DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, DAG.getUNDEF(MVT::i32), Op, DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 0); Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); } static void ReplaceReductionResults(SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG, unsigned InterOp, unsigned AcrossOp) { EVT LoVT, HiVT; SDValue Lo, Hi; SDLoc dl(N); std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); Results.push_back(SplitVal); } static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { SDLoc DL(N); SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, DAG.getNode(ISD::SRL, DL, MVT::i128, N, DAG.getConstant(64, DL, MVT::i64))); return std::make_pair(Lo, Hi); } // Create an even/odd pair of X registers holding integer value V. static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { SDLoc dl(V.getNode()); SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); SDValue VHi = DAG.getAnyExtOrTrunc( DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), dl, MVT::i64); if (DAG.getDataLayout().isBigEndian()) std::swap (VLo, VHi); SDValue RegClass = DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; return SDValue( DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); } static void ReplaceCMP_SWAP_128Results(SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG, const AArch64Subtarget *Subtarget) { assert(N->getValueType(0) == MVT::i128 && "AtomicCmpSwap on types less than 128 should be legal"); if (Subtarget->hasLSE()) { // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. SDValue Ops[] = { createGPRPairNode(DAG, N->getOperand(2)), // Compare value createGPRPairNode(DAG, N->getOperand(3)), // Store value N->getOperand(1), // Ptr N->getOperand(0), // Chain in }; MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); unsigned Opcode; switch (MemOp->getOrdering()) { case AtomicOrdering::Monotonic: Opcode = AArch64::CASPX; break; case AtomicOrdering::Acquire: Opcode = AArch64::CASPAX; break; case AtomicOrdering::Release: Opcode = AArch64::CASPLX; break; case AtomicOrdering::AcquireRelease: case AtomicOrdering::SequentiallyConsistent: Opcode = AArch64::CASPALX; break; default: llvm_unreachable("Unexpected ordering!"); } MachineSDNode *CmpSwap = DAG.getMachineNode( Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); DAG.setNodeMemRefs(CmpSwap, {MemOp}); unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; if (DAG.getDataLayout().isBigEndian()) std::swap(SubReg1, SubReg2); Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, SDValue(CmpSwap, 0))); Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, SDValue(CmpSwap, 0))); Results.push_back(SDValue(CmpSwap, 1)); // Chain out return; } auto Desired = splitInt128(N->getOperand(2), DAG); auto New = splitInt128(N->getOperand(3), DAG); SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, New.first, New.second, N->getOperand(0)}; SDNode *CmpSwap = DAG.getMachineNode( AArch64::CMP_SWAP_128, SDLoc(N), DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); Results.push_back(SDValue(CmpSwap, 0)); Results.push_back(SDValue(CmpSwap, 1)); Results.push_back(SDValue(CmpSwap, 3)); } void AArch64TargetLowering::ReplaceNodeResults( SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { switch (N->getOpcode()) { default: llvm_unreachable("Don't know how to custom expand this"); case ISD::BITCAST: ReplaceBITCASTResults(N, Results, DAG); return; case ISD::VECREDUCE_ADD: case ISD::VECREDUCE_SMAX: case ISD::VECREDUCE_SMIN: case ISD::VECREDUCE_UMAX: case ISD::VECREDUCE_UMIN: Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); return; case AArch64ISD::SADDV: ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); return; case AArch64ISD::UADDV: ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); return; case AArch64ISD::SMINV: ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); return; case AArch64ISD::UMINV: ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); return; case AArch64ISD::SMAXV: ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); return; case AArch64ISD::UMAXV: ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); return; case ISD::FP_TO_UINT: case ISD::FP_TO_SINT: assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); // Let normal code take care of it by not adding anything to Results. return; case ISD::ATOMIC_CMP_SWAP: ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); return; } } bool AArch64TargetLowering::useLoadStackGuardNode() const { if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) return TargetLowering::useLoadStackGuardNode(); return true; } unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { // Combine multiple FDIVs with the same divisor into multiple FMULs by the // reciprocal if there are three or more FDIVs. return 3; } TargetLoweringBase::LegalizeTypeAction AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, // v4i16, v2i32 instead of to promote. if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || VT == MVT::v1f32) return TypeWidenVector; return TargetLoweringBase::getPreferredVectorAction(VT); } // Loads and stores less than 128-bits are already atomic; ones above that // are doomed anyway, so defer to the default libcall and blame the OS when // things go wrong. bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); return Size == 128; } // Loads and stores less than 128-bits are already atomic; ones above that // are doomed anyway, so defer to the default libcall and blame the OS when // things go wrong. TargetLowering::AtomicExpansionKind AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { unsigned Size = LI->getType()->getPrimitiveSizeInBits(); return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; } // For the real atomic operations, we have ldxr/stxr up to 128 bits, TargetLowering::AtomicExpansionKind AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { if (AI->isFloatingPointOperation()) return AtomicExpansionKind::CmpXChg; unsigned Size = AI->getType()->getPrimitiveSizeInBits(); if (Size > 128) return AtomicExpansionKind::None; // Nand not supported in LSE. if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; // Leave 128 bits to LLSC. return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; } TargetLowering::AtomicExpansionKind AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( AtomicCmpXchgInst *AI) const { // If subtarget has LSE, leave cmpxchg intact for codegen. if (Subtarget->hasLSE()) return AtomicExpansionKind::None; // At -O0, fast-regalloc cannot cope with the live vregs necessary to // implement cmpxchg without spilling. If the address being exchanged is also // on the stack and close enough to the spill slot, this can lead to a // situation where the monitor always gets cleared and the atomic operation // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. if (getTargetMachine().getOptLevel() == 0) return AtomicExpansionKind::None; return AtomicExpansionKind::LLSC; } Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, AtomicOrdering Ord) const { Module *M = Builder.GetInsertBlock()->getParent()->getParent(); Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); bool IsAcquire = isAcquireOrStronger(Ord); // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd // intrinsic must return {i64, i64} and we have to recombine them into a // single i128 here. if (ValTy->getPrimitiveSizeInBits() == 128) { Intrinsic::ID Int = IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; Function *Ldxr = Intrinsic::getDeclaration(M, Int); Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); return Builder.CreateOr( Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); } Type *Tys[] = { Addr->getType() }; Intrinsic::ID Int = IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); const DataLayout &DL = M->getDataLayout(); IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); return Builder.CreateBitCast(Trunc, EltTy); } void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( IRBuilder<> &Builder) const { Module *M = Builder.GetInsertBlock()->getParent()->getParent(); Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); } Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const { Module *M = Builder.GetInsertBlock()->getParent()->getParent(); bool IsRelease = isReleaseOrStronger(Ord); // Since the intrinsics must have legal type, the i128 intrinsics take two // parameters: "i64, i64". We must marshal Val into the appropriate form // before the call. if (Val->getType()->getPrimitiveSizeInBits() == 128) { Intrinsic::ID Int = IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; Function *Stxr = Intrinsic::getDeclaration(M, Int); Type *Int64Ty = Type::getInt64Ty(M->getContext()); Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); } Intrinsic::ID Int = IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; Type *Tys[] = { Addr->getType() }; Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); const DataLayout &DL = M->getDataLayout(); IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); Val = Builder.CreateBitCast(Val, IntValTy); return Builder.CreateCall(Stxr, {Builder.CreateZExtOrBitCast( Val, Stxr->getFunctionType()->getParamType(0)), Addr}); } bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { return Ty->isArrayTy(); } bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, EVT) const { return false; } static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { Module *M = IRB.GetInsertBlock()->getParent()->getParent(); Function *ThreadPointerFunc = Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); return IRB.CreatePointerCast( IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), Offset), IRB.getInt8PtrTy()->getPointerTo(0)); } Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { // Android provides a fixed TLS slot for the stack cookie. See the definition // of TLS_SLOT_STACK_GUARD in // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h if (Subtarget->isTargetAndroid()) return UseTlsOffset(IRB, 0x28); // Fuchsia is similar. // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. if (Subtarget->isTargetFuchsia()) return UseTlsOffset(IRB, -0x10); return TargetLowering::getIRStackGuard(IRB); } void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { // MSVC CRT provides functionalities for stack protection. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { // MSVC CRT has a global variable holding security cookie. M.getOrInsertGlobal("__security_cookie", Type::getInt8PtrTy(M.getContext())); // MSVC CRT has a function to validate security cookie. FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( "__security_check_cookie", Type::getVoidTy(M.getContext()), Type::getInt8PtrTy(M.getContext())); if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { F->setCallingConv(CallingConv::Win64); F->addAttribute(1, Attribute::AttrKind::InReg); } return; } TargetLowering::insertSSPDeclarations(M); } Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { // MSVC CRT has a global variable holding security cookie. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) return M.getGlobalVariable("__security_cookie"); return TargetLowering::getSDagStackGuard(M); } Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { // MSVC CRT has a function to validate security cookie. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) return M.getFunction("__security_check_cookie"); return TargetLowering::getSSPStackGuardCheck(M); } Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { // Android provides a fixed TLS slot for the SafeStack pointer. See the // definition of TLS_SLOT_SAFESTACK in // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h if (Subtarget->isTargetAndroid()) return UseTlsOffset(IRB, 0x48); // Fuchsia is similar. // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. if (Subtarget->isTargetFuchsia()) return UseTlsOffset(IRB, -0x8); return TargetLowering::getSafeStackPointerLocation(IRB); } bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( const Instruction &AndI) const { // Only sink 'and' mask to cmp use block if it is masking a single bit, since // this is likely to be fold the and/cmp/br into a single tbz instruction. It // may be beneficial to sink in other cases, but we would have to check that // the cmp would not get folded into the br to form a cbz for these to be // beneficial. ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); if (!Mask) return false; return Mask->getValue().isPowerOf2(); } void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { // Update IsSplitCSR in AArch64unctionInfo. AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); AFI->setIsSplitCSR(true); } void AArch64TargetLowering::insertCopiesSplitCSR( MachineBasicBlock *Entry, const SmallVectorImpl<MachineBasicBlock *> &Exits) const { const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); if (!IStart) return; const TargetInstrInfo *TII = Subtarget->getInstrInfo(); MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); MachineBasicBlock::iterator MBBI = Entry->begin(); for (const MCPhysReg *I = IStart; *I; ++I) { const TargetRegisterClass *RC = nullptr; if (AArch64::GPR64RegClass.contains(*I)) RC = &AArch64::GPR64RegClass; else if (AArch64::FPR64RegClass.contains(*I)) RC = &AArch64::FPR64RegClass; else llvm_unreachable("Unexpected register class in CSRsViaCopy!"); unsigned NewVR = MRI->createVirtualRegister(RC); // Create copy from CSR to a virtual register. // FIXME: this currently does not emit CFI pseudo-instructions, it works // fine for CXX_FAST_TLS since the C++-style TLS access functions should be // nounwind. If we want to generalize this later, we may need to emit // CFI pseudo-instructions. assert(Entry->getParent()->getFunction().hasFnAttribute( Attribute::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"); Entry->addLiveIn(*I); BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) .addReg(*I); // Insert the copy-back instructions right before the terminator. for (auto *Exit : Exits) BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), TII->get(TargetOpcode::COPY), *I) .addReg(NewVR); } } bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { // Integer division on AArch64 is expensive. However, when aggressively // optimizing for code size, we prefer to use a div instruction, as it is // usually smaller than the alternative sequence. // The exception to this is vector division. Since AArch64 doesn't have vector // integer division, leaving the division as-is is a loss even in terms of // size, because it will have to be scalarized, while the alternative code // sequence can be performed in vector form. bool OptSize = Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); return OptSize && !VT.isVector(); } bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); } unsigned AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) return getPointerTy(DL).getSizeInBits(); return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; } void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { MF.getFrameInfo().computeMaxCallFrameSize(MF); TargetLoweringBase::finalizeLowering(MF); } // Unlike X86, we let frame lowering assign offsets to all catch objects. bool AArch64TargetLowering::needsFixedCatchObjects() const { return false; }
#pragma once #ifdef _WIN32 #include <Windows.h> #include <Windowsx.h> #define WIN32_DX11 (true) #define WIN32_OPENGL (false) #if WIN32_DX11 #include <d3d11.h> #include <d3dcompiler.h> #include <wrl.h> #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "D3DCompiler.lib") #endif #if WIN32_OPENGL #include <GL/glew.h> #include <GL/wglew.h> #include <GL/gl.h> #include <GL/glu.h> #pragma comment(lib, "Opengl32.lib") #pragma comment(lib, "Glu32.lib") #endif #endif #include <cstdint> #include <cstdio> #include <exception> #include <iostream> #include <memory> #include <string> struct Vertex { float x; float y; float r; float g; float b; }; class noncopyable { public: noncopyable() = default; private: noncopyable(const noncopyable&) = delete; void operator=(const noncopyable&) = delete; }; class error_handler : public std::exception { public: error_handler(const char* msg = "") { printf("error_handler(%s)\n", msg); } }; #if WIN32_OPENGL inline void load_shader(std::string& shader_code, const char* filename) { auto* shader_file = fopen(filename, "rb"); if (!shader_file) { throw error_handler("cannot open the shader file"); } fseek(shader_file, 0, SEEK_END); auto code_size = ftell(shader_file); fseek(shader_file, 0, SEEK_SET); shader_code.resize(code_size); if (fread(&*shader_code.begin(), code_size, 1, shader_file) < 0) { fclose(shader_file); throw error_handler("error read file"); } fclose(shader_file); } class MSWindowFalseContext { public: ~MSWindowFalseContext() { if (m_rc) { ::wglDeleteContext(m_rc); m_rc = nullptr; } if (m_dc) { ::ReleaseDC(m_hwnd, m_dc); m_dc = nullptr; } if (m_hwnd) { ::DestroyWindow(m_hwnd); m_hwnd = nullptr; } } void create() { auto hInstance = GetModuleHandle(nullptr); const wchar_t* className = L"MSWindowFalseContext"; WNDCLASSEX wc; if (!GetClassInfoEx(hInstance, className, &wc)) { memset(&wc, 0, sizeof(wc)); wc.cbSize = sizeof(wc); wc.style = CS_OWNDC; wc.lpfnWndProc = DefWindowProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.hbrBackground = nullptr; wc.lpszClassName = className; if (!RegisterClassEx(&wc)) { throw error_handler("RegisterClassEx"); } } m_hwnd = CreateWindowExW(0, className, L"", WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hInstance, nullptr); if (!m_hwnd) { throw error_handler("CreateWindow"); } m_dc = GetDC(m_hwnd); if (!m_dc) { throw error_handler("GetDC"); } PIXELFORMATDESCRIPTOR pfd; { memset(&pfd, 0, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; } int nPixelFormat = ChoosePixelFormat(m_dc, &pfd); if (nPixelFormat == 0) { throw error_handler("ChoosePixelFormat"); } BOOL bResult = SetPixelFormat(m_dc, nPixelFormat, &pfd); if (!bResult) { throw error_handler("SetPixelFormat"); } m_rc = wglCreateContext(m_dc); if (!m_rc) { throw error_handler("wglCreateContext"); } wglMakeCurrent(m_dc, m_rc); } private: HWND m_hwnd = nullptr; HDC m_dc = nullptr; HGLRC m_rc = nullptr; }; #endif class Renderer { public: ~Renderer() = default; Renderer() = default; #if _WIN32 Renderer(const HWND& hwnd) { m_hwnd = hwnd; m_dc = GetDC(m_hwnd); { if (!m_dc) { throw error_handler("GetDC"); } } #endif #if WIN32_OPENGL // clang-format off const int formatAttrs[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, 0 }; int contextAttrs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, #if 0 WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, #else WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, #endif WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; // clang-format on int format, numFormat; if (!wglChoosePixelFormatARB(m_dc, formatAttrs, nullptr, 1, &format, (UINT*)&numFormat)) { throw error_handler("wglChoosePixelFormatARB"); } PIXELFORMATDESCRIPTOR pfd; if (!SetPixelFormat(m_dc, format, &pfd)) { throw error_handler("SetPixelFormat"); } HGLRC sharedContext = nullptr; m_rc = wglCreateContextAttribsARB(m_dc, sharedContext, contextAttrs); if (!m_rc) { throw error_handler("wglCreateContext"); } #endif #if WIN32_DX11 set_viewport_width(hwnd); set_viewport_height(hwnd); DXGI_SWAP_CHAIN_DESC swapchain = {}; swapchain.BufferDesc.Width = 0; swapchain.BufferDesc.Height = 0; swapchain.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swapchain.BufferDesc.RefreshRate.Numerator = 0; swapchain.BufferDesc.RefreshRate.Denominator = 0; swapchain.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapchain.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapchain.SampleDesc.Count = 1; swapchain.SampleDesc.Quality = 0; swapchain.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapchain.BufferCount = 1; swapchain.OutputWindow = hwnd; swapchain.Windowed = TRUE; swapchain.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapchain.Flags = 0; m_hresult = D3D11CreateDeviceAndSwapChain(nullptr, // DXGI Adapter D3D_DRIVER_TYPE_HARDWARE, // Driver Type nullptr, // Software Rasterizer 0, // Create Flags nullptr, // Feature Level 0, // Feature Level D3D11_SDK_VERSION, // SDKVersion &swapchain, // SwapChain &m_dxgi_swapchain, // SwapChain &m_dx11_device, // Device nullptr, // FeatureLevel &m_dx11_device_context); // DeviceContext Microsoft::WRL::ComPtr<ID3D11Resource> pBackBuffer; m_hresult = m_dxgi_swapchain->GetBuffer(0, // zero-based buffer index __uuidof(ID3D11Resource), // REFIID &pBackBuffer); // point to a back buffer interface m_hresult = m_dx11_device->CreateRenderTargetView(pBackBuffer.Get(), // Render Target nullptr, // Render Target View Description &m_dx11_render_target_view); // Render Target View } #endif void init(void) { #if WIN32_OPENGL glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); glDepthMask(GL_TRUE); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glClearDepth(1); #endif #if WIN32_DX11 #endif } void destory(void) { #if _WIN32 if (m_rc) { wglDeleteContext(m_rc); m_rc = nullptr; } if (m_dc) { ReleaseDC(m_hwnd, m_dc); m_dc = nullptr; } #endif } #if WIN32_DX11 void VertexBufferPipeline(const Vertex (&vertices)[3]) { Microsoft::WRL::ComPtr<ID3D11Buffer> pVertexBuffer; D3D11_BUFFER_DESC bufferDescription = {}; bufferDescription.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferDescription.Usage = D3D11_USAGE_DEFAULT; bufferDescription.CPUAccessFlags = 0; bufferDescription.MiscFlags = 0; bufferDescription.ByteWidth = sizeof(vertices); bufferDescription.StructureByteStride = sizeof(Vertex); D3D11_SUBRESOURCE_DATA suberSourceData = {}; suberSourceData.pSysMem = vertices; m_hresult = m_dx11_device->CreateBuffer(&bufferDescription, &suberSourceData, &pVertexBuffer); const UINT stride = sizeof(Vertex); const UINT offset = 0; m_dx11_device_context->IASetVertexBuffers(0, // input start slot 1, // number of vertex buffers pVertexBuffer.GetAddressOf(), // vertex buffers &stride, // stride value for each buffer &offset); // offset value for each buffer } void ShaderPipeline(const wchar_t* const PixelShaderFile, const wchar_t* const VertexShaderFile) { Microsoft::WRL::ComPtr<ID3DBlob> pBlob; Microsoft::WRL::ComPtr<ID3D11PixelShader> pPixelShader; { m_hresult = D3DReadFileToBlob(PixelShaderFile, &pBlob); m_hresult = m_dx11_device->CreatePixelShader(pBlob->GetBufferPointer(), // pBlob->GetBufferSize(), // nullptr, // ID3D11ClassLinkage &pPixelShader); // m_dx11_device_context->PSSetShader(pPixelShader.Get(), // ID3D11PixelShader nullptr, // ID3D11ClassInstance 0); // number of instance } Microsoft::WRL::ComPtr<ID3D11VertexShader> pVertexShader; { m_hresult = D3DReadFileToBlob(VertexShaderFile, // &pBlob); // ID3DBlob m_hresult = m_dx11_device->CreateVertexShader(pBlob->GetBufferPointer(), // pBlob->GetBufferSize(), // nullptr, // &pVertexShader); // m_dx11_device_context->VSSetShader(pVertexShader.Get(), // nullptr, // 0); // } Microsoft::WRL::ComPtr<ID3D11InputLayout> pInputLayout; { const D3D11_INPUT_ELEMENT_DESC inputElementDescription[] = { { "Position", // SemanticName 0, // SemanticIndex DXGI_FORMAT_R32G32_FLOAT, // Format 0, // InputSlot 0, // AlignedByteOffset D3D11_INPUT_PER_VERTEX_DATA, // InputSlotClass 0 // InstanceDataStepRate }, { "Color", // 0, // DXGI_FORMAT_R32G32B32_FLOAT, // 0, // 8, // D3D11_INPUT_PER_VERTEX_DATA, // 0 // }, }; m_hresult = m_dx11_device->CreateInputLayout(inputElementDescription, // static_cast<UINT>(std::size(inputElementDescription)), // pBlob->GetBufferPointer(), // pBlob->GetBufferSize(), // &pInputLayout); // } m_dx11_device_context->IASetInputLayout(pInputLayout.Get()); } void BindTargetPipeline(void) { m_dx11_device_context->OMSetRenderTargets(1, // m_dx11_render_target_view.GetAddressOf(), // nullptr); // } void SetPrimitiveTopologyPipeline(enum D3D_PRIMITIVE_TOPOLOGY topology) { m_dx11_device_context->IASetPrimitiveTopology(topology); } void ConfigureViewport(int width, int height) { D3D11_VIEWPORT viewport; viewport.Width = width; viewport.Height = height; viewport.MinDepth = 0; viewport.MaxDepth = 1; viewport.TopLeftX = 0; viewport.TopLeftY = 0; m_dx11_device_context->RSSetViewports(1, &viewport); } void RenderVertices(const Vertex (&vertices)[3]) { m_dx11_device_context->Draw(static_cast<UINT>(std::size(vertices)), // 0); // } void onRender(const Vertex (&vertices)[3], // const wchar_t* const PixelShaderFile, // const wchar_t* const VertexShaderFile, // enum D3D_PRIMITIVE_TOPOLOGY topology) { // VertexBufferPipeline(vertices); ShaderPipeline(PixelShaderFile, VertexShaderFile); BindTargetPipeline(); SetPrimitiveTopologyPipeline(topology); ConfigureViewport(get_viewport_width(), get_viewport_height()); RenderVertices(vertices); } int get_viewport_width() const { return m_viewport_width; } int get_viewport_height() const { return m_viewport_height; } void set_viewport_width(const HWND& hwnd) { RECT rect; if (GetWindowRect(hwnd, &rect)) { m_viewport_width = rect.right - rect.left; } } void set_viewport_height(const HWND& hwnd) { RECT rect; if (GetWindowRect(hwnd, &rect)) { m_viewport_height = rect.bottom - rect.top; } } #endif #if WIN32_OPENGL void configShader(void) { std::string vertexCode; load_shader(vertexCode, "libng\\shader\\glsl\\vertex.glsl"); const char* vertexSrcData = vertexCode.c_str(); GLint vertexSrcLen = vertexCode.size(); unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexSrcData, &vertexSrcLen); glCompileShader(vertexShader); int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog); throw error_handler("vertex shader error"); } std::string fragmentCode; load_shader(fragmentCode, "libng\\shader\\glsl\\fragment.glsl"); const char* fragmentSrcData = fragmentCode.c_str(); GLint fragmentSrcLen = fragmentCode.size(); unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentSrcData, &fragmentSrcLen); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog); throw error_handler("fragment shader error"); } shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog); throw error_handler("shader linking error"); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // clang-format off float vertices[] = { -0.5f, -0.5f, 0.0f, // left +0.5f, -0.5f, 0.0f, // right +0.0f, +0.5f, 0.0f // top }; // clang-format on glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } #endif void SetBackgroundColor(void) { #if WIN32_OPENGL glClearColor(0.0f, 0.2f, 0.2f, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); #endif #if WIN32_DX11 const float color[] = {1.0f, 0.0f, 0.0f, 1.0f}; m_dx11_device_context->ClearRenderTargetView(m_dx11_render_target_view.Get(), // render target color); // 4-dim array #endif } void SetTriangle(void) { #if WIN32_OPENGL configShader(); glUseProgram(shaderProgram); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); #endif #if WIN32_DX11 // create vertex buffer (1 2d triangle at center of screen) const Vertex vertices[] = { {+0.0f, +0.5f, 0.0f, 0.0f, 0.0f}, {+0.5f, -0.5f, 1.0f, 1.0f, 0.0f}, {-0.5f, -0.5f, 0.0f, 0.0f, 1.0f}, }; onRender(vertices, // L"build\\sample\\shader\\pixel.cso", // L"build\\sample\\shader\\vertex.cso", // D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // #endif } void makeCurrent() { #if WIN32_OPENGL if (m_rc) { wglMakeContextCurrentARB(m_dc, m_dc, m_rc); } #endif #if WIN32_DX11 #endif } void swapBuffers() { #if WIN32_OPENGL if (m_dc) { ::SwapBuffers(m_dc); } #endif #if WIN32_DX11 m_hresult = m_dxgi_swapchain->Present(1, // synchronize option pre frame 0); // swap chain option #endif } private: #if _WIN32 HWND m_hwnd = nullptr; HDC m_dc = nullptr; HGLRC m_rc = nullptr; #endif #if WIN32_DX11 HRESULT m_hresult; int m_viewport_width = 0; int m_viewport_height = 0; Microsoft::WRL::ComPtr<ID3D11Device> m_dx11_device; Microsoft::WRL::ComPtr<IDXGISwapChain> m_dxgi_swapchain; Microsoft::WRL::ComPtr<ID3D11DeviceContext> m_dx11_device_context; Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_dx11_render_target_view; #endif #if WIN32_OPENGL unsigned int shaderProgram; unsigned int VBO, VAO; #endif }; class MSWindow : public noncopyable { public: MSWindow() = default; ~MSWindow() { destroy(); } void set_width(int width) { if (width > 0) { m_width = width; } } void set_height(int height) { if (height > 0) { m_height = height; } } void set_title(const wchar_t* const title) { if (title != nullptr) { m_title.clear(); m_title = title; } } void create(int width, int height, const wchar_t* const title) { set_width(width); set_height(height); set_title(title); #if _WIN32 auto hInstance = GetModuleHandle(nullptr); #endif destroy(); #if WIN32_OPENGL MSWindowFalseContext falseContext; falseContext.create(); glewInit(); #endif #if _WIN32 WNDCLASSEX wc; if (!GetClassInfoEx(hInstance, wndClassName(), &wc)) { memset(&wc, 0, sizeof(wc)); wc.cbSize = sizeof(wc); wc.style = CS_OWNDC; wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.hbrBackground = nullptr; wc.lpszClassName = wndClassName(); if (!RegisterClassEx(&wc)) { throw error_handler("RegisterClassEx"); } } m_hwnd = CreateWindowEx(0, // wndClassName(), // m_title.c_str(), // WS_OVERLAPPEDWINDOW, // CW_USEDEFAULT, // CW_USEDEFAULT, // m_width, // m_height, // nullptr, // nullptr, // hInstance, // this); // if (!m_hwnd) { throw error_handler("CreateWindow"); } m_renderer = Renderer(m_hwnd); makeCurrent(); onInit(); ShowWindow(m_hwnd, SW_SHOW); UpdateWindow(m_hwnd); #endif } void destroy() { m_renderer.destory(); #if _WIN32 if (m_hwnd) { DestroyWindow(m_hwnd); m_hwnd = nullptr; } #endif } virtual bool onShouldClose() { return true; } virtual void onDestroy() { } virtual void onPaint() { } virtual void onInit() { } static const wchar_t* wndClassName() { return L"MSWindowClass"; } void makeCurrent() { m_renderer.makeCurrent(); } void swapBuffers() { m_renderer.swapBuffers(); } int canvasWidth() const { return m_canvasWidth; } int canvasHeight() const { return m_canvasHeight; } protected: Renderer m_renderer; private: #if _WIN32 static LRESULT WINAPI WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: { auto* cs = reinterpret_cast<CREATESTRUCT*>(lParam); auto* thisObj = reinterpret_cast<MSWindow*>(cs->lpCreateParams); SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG)thisObj); } break; case WM_PAINT: { #if 0 PAINTSTRUCT ps; BeginPaint(hwnd, &ps); getThis(hwnd)->onPaint(); EndPaint(hwnd, &ps); #else getThis(hwnd)->onPaint(); return 0; #endif } break; case WM_DESTROY: { getThis(hwnd)->onDestroy(); } break; case WM_SIZE: { auto* thisObj = getThis(hwnd); auto w = GET_X_LPARAM(lParam); auto h = GET_Y_LPARAM(lParam); thisObj->m_canvasWidth = w; thisObj->m_canvasHeight = h; } break; case WM_CLOSE: { if (!getThis(hwnd)->onShouldClose()) { return 1; } } break; default: break; } return DefWindowProc(hwnd, msg, wParam, lParam); } #endif #if _WIN32 static MSWindow* getThis(HWND hwnd) { auto data = GetWindowLongPtr(hwnd, GWLP_USERDATA); auto* thisObj = reinterpret_cast<MSWindow*>(data); if (hwnd != thisObj->m_hwnd) throw error_handler("getThis()"); return thisObj; } #endif #if _WIN32 HWND m_hwnd = nullptr; #endif int m_canvasWidth = 0; int m_canvasHeight = 0; int m_width = 0; int m_height = 0; std::wstring m_title; }; class UIWindow : public MSWindow { public: virtual void onInit() override { m_renderer.init(); } virtual void onDestroy() override { #if _WIN32 PostQuitMessage(0); #endif } virtual void onPaint() override { m_renderer.SetBackgroundColor(); m_renderer.SetTriangle(); swapBuffers(); } }; class App : public noncopyable { public: explicit App(const int width, const int height, const wchar_t* const title) { m_window.create(width, height, title); } ~App() = default; int execute(void) { #if _WIN32 MSG msg; while (GetMessage(&msg, nullptr, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; #endif #if __linux__ return 0; #endif } private: UIWindow m_window; };
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/sagbit-config.h" #endif #include "util.h" #include "chainparamsbase.h" #include "random.h" #include "serialize.h" #include "sync.h" #include "utilstrencodings.h" #include "utiltime.h" #include <stdarg.h> #if (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) #include <pthread.h> #include <pthread_np.h> #endif #ifndef WIN32 // for posix_fallocate #ifdef __linux__ #ifdef _POSIX_C_SOURCE #undef _POSIX_C_SOURCE #endif #define _POSIX_C_SOURCE 200112L #endif // __linux__ #include <algorithm> #include <fcntl.h> #include <sys/resource.h> #include <sys/stat.h> #else #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <io.h> /* for _commit */ #include <shlobj.h> #endif #ifdef HAVE_SYS_PRCTL_H #include <sys/prctl.h> #endif #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/foreach.hpp> #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/conf.h> // Work around clang compilation problem in Boost 1.46: // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION namespace boost { namespace program_options { std::string to_internal(const std::string&); } } // namespace boost using namespace std; const char * const SAGBIT_CONF_FILENAME = "sagbit.conf"; const char * const SAGBIT_PID_FILENAME = "sagbitd.pid"; map<string, string> mapArgs; map<string, vector<string> > mapMultiArgs; bool fDebug = false; bool fPrintToConsole = false; bool fPrintToDebugLog = true; bool fDaemon = false; bool fServer = false; string strMiscWarning; bool fLogTimestamps = DEFAULT_LOGTIMESTAMPS; bool fLogTimeMicros = DEFAULT_LOGTIMEMICROS; bool fLogIPs = DEFAULT_LOGIPS; volatile bool fReopenDebugLog = false; CTranslationInterface translationInterface; /** Init OpenSSL library multithreading support */ static CCriticalSection** ppmutexOpenSSL; void locking_callback(int mode, int i, const char* file, int line) NO_THREAD_SAFETY_ANALYSIS { if (mode & CRYPTO_LOCK) { ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } else { LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } } // Init class CInit { public: CInit() { // Init OpenSSL library multithreading support ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*)); for (int i = 0; i < CRYPTO_num_locks(); i++) ppmutexOpenSSL[i] = new CCriticalSection(); CRYPTO_set_locking_callback(locking_callback); // OpenSSL can optionally load a config file which lists optional loadable modules and engines. // We don't use them so we don't require the config. However some of our libs may call functions // which attempt to load the config file, possibly resulting in an exit() or crash if it is missing // or corrupt. Explicitly tell OpenSSL not to try to load the file. The result for our libs will be // that the config appears to have been loaded and there are no modules/engines available. OPENSSL_no_config(); #ifdef WIN32 // Seed OpenSSL PRNG with current contents of the screen RAND_screen(); #endif // Seed OpenSSL PRNG with performance counter RandAddSeed(); } ~CInit() { // Securely erase the memory used by the PRNG RAND_cleanup(); // Shutdown OpenSSL library multithreading support CRYPTO_set_locking_callback(NULL); for (int i = 0; i < CRYPTO_num_locks(); i++) delete ppmutexOpenSSL[i]; OPENSSL_free(ppmutexOpenSSL); } } instance_of_cinit; /** * LogPrintf() has been broken a couple of times now * by well-meaning people adding mutexes in the most straightforward way. * It breaks because it may be called by global destructors during shutdown. * Since the order of destruction of static/global objects is undefined, * defining a mutex as a global object doesn't work (the mutex gets * destroyed, and then some later destructor calls OutputDebugStringF, * maybe indirectly, and you get a core dump at shutdown trying to lock * the mutex). */ static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT; /** * We use boost::call_once() to make sure mutexDebugLog and * vMsgsBeforeOpenLog are initialized in a thread-safe manner. * * NOTE: fileout, mutexDebugLog and sometimes vMsgsBeforeOpenLog * are leaked on exit. This is ugly, but will be cleaned up by * the OS/libc. When the shutdown sequence is fully audited and * tested, explicit destruction of these objects can be implemented. */ static FILE* fileout = NULL; static boost::mutex* mutexDebugLog = NULL; static list<string> *vMsgsBeforeOpenLog; static int FileWriteStr(const std::string &str, FILE *fp) { return fwrite(str.data(), 1, str.size(), fp); } static void DebugPrintInit() { assert(mutexDebugLog == NULL); mutexDebugLog = new boost::mutex(); vMsgsBeforeOpenLog = new list<string>; } void OpenDebugLog() { boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); assert(fileout == NULL); assert(vMsgsBeforeOpenLog); boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; fileout = fopen(pathDebug.string().c_str(), "a"); if (fileout) setbuf(fileout, NULL); // unbuffered // dump buffered messages from before we opened the log while (!vMsgsBeforeOpenLog->empty()) { FileWriteStr(vMsgsBeforeOpenLog->front(), fileout); vMsgsBeforeOpenLog->pop_front(); } delete vMsgsBeforeOpenLog; vMsgsBeforeOpenLog = NULL; } bool LogAcceptCategory(const char* category) { if (category != NULL) { if (!fDebug) return false; // Give each thread quick access to -debug settings. // This helps prevent issues debugging global destructors, // where mapMultiArgs might be deleted before another // global destructor calls LogPrint() static boost::thread_specific_ptr<set<string> > ptrCategory; if (ptrCategory.get() == NULL) { const vector<string>& categories = mapMultiArgs["-debug"]; ptrCategory.reset(new set<string>(categories.begin(), categories.end())); // thread_specific_ptr automatically deletes the set when the thread ends. } const set<string>& setCategories = *ptrCategory.get(); // if not debugging everything and not debugging specific category, LogPrint does nothing. if (setCategories.count(string("")) == 0 && setCategories.count(string("1")) == 0 && setCategories.count(string(category)) == 0) return false; } return true; } /** * fStartedNewLine is a state variable held by the calling context that will * suppress printing of the timestamp when multiple calls are made that don't * end in a newline. Initialize it to true, and hold it, in the calling context. */ static std::string LogTimestampStr(const std::string &str, bool *fStartedNewLine) { string strStamped; if (!fLogTimestamps) return str; if (*fStartedNewLine) { int64_t nTimeMicros = GetLogTimeMicros(); strStamped = DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nTimeMicros/1000000); if (fLogTimeMicros) strStamped += strprintf(".%06d", nTimeMicros%1000000); strStamped += ' ' + str; } else strStamped = str; if (!str.empty() && str[str.size()-1] == '\n') *fStartedNewLine = true; else *fStartedNewLine = false; return strStamped; } int LogPrintStr(const std::string &str) { int ret = 0; // Returns total number of characters written static bool fStartedNewLine = true; string strTimestamped = LogTimestampStr(str, &fStartedNewLine); if (fPrintToConsole) { // print to console ret = fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout); fflush(stdout); } else if (fPrintToDebugLog) { boost::call_once(&DebugPrintInit, debugPrintInitFlag); boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); // buffer if we haven't opened the log yet if (fileout == NULL) { assert(vMsgsBeforeOpenLog); ret = strTimestamped.length(); vMsgsBeforeOpenLog->push_back(strTimestamped); } else { // reopen the log file, if requested if (fReopenDebugLog) { fReopenDebugLog = false; boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL) setbuf(fileout, NULL); // unbuffered } ret = FileWriteStr(strTimestamped, fileout); } } return ret; } /** Interpret string as boolean, for argument parsing */ static bool InterpretBool(const std::string& strValue) { if (strValue.empty()) return true; return (atoi(strValue) != 0); } /** Turn -noX into -X=0 */ static void InterpretNegativeSetting(std::string& strKey, std::string& strValue) { if (strKey.length()>3 && strKey[0]=='-' && strKey[1]=='n' && strKey[2]=='o') { strKey = "-" + strKey.substr(3); strValue = InterpretBool(strValue) ? "0" : "1"; } } void ParseParameters(int argc, const char* const argv[]) { mapArgs.clear(); mapMultiArgs.clear(); for (int i = 1; i < argc; i++) { std::string str(argv[i]); std::string strValue; size_t is_index = str.find('='); if (is_index != std::string::npos) { strValue = str.substr(is_index+1); str = str.substr(0, is_index); } #ifdef WIN32 boost::to_lower(str); if (boost::algorithm::starts_with(str, "/")) str = "-" + str.substr(1); #endif if (str[0] != '-') break; // Interpret --foo as -foo. // If both --foo and -foo are set, the last takes effect. if (str.length() > 1 && str[1] == '-') str = str.substr(1); InterpretNegativeSetting(str, strValue); mapArgs[str] = strValue; mapMultiArgs[str].push_back(strValue); } } std::string GetArg(const std::string& strArg, const std::string& strDefault) { if (mapArgs.count(strArg)) return mapArgs[strArg]; return strDefault; } int64_t GetArg(const std::string& strArg, int64_t nDefault) { if (mapArgs.count(strArg)) return atoi64(mapArgs[strArg]); return nDefault; } bool GetBoolArg(const std::string& strArg, bool fDefault) { if (mapArgs.count(strArg)) return InterpretBool(mapArgs[strArg]); return fDefault; } bool SoftSetArg(const std::string& strArg, const std::string& strValue) { if (mapArgs.count(strArg)) return false; mapArgs[strArg] = strValue; return true; } bool SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } static const int screenWidth = 79; static const int optIndent = 2; static const int msgIndent = 7; std::string HelpMessageGroup(const std::string &message) { return std::string(message) + std::string("\n\n"); } std::string HelpMessageOpt(const std::string &option, const std::string &message) { return std::string(optIndent,' ') + std::string(option) + std::string("\n") + std::string(msgIndent,' ') + FormatParagraph(message, screenWidth - msgIndent, msgIndent) + std::string("\n\n"); } static std::string FormatException(const std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(NULL, pszModule, sizeof(pszModule)); #else const char* pszModule = "sagbit"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void PrintExceptionContinue(const std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); LogPrintf("\n\n************************\n%s\n", message); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); } boost::filesystem::path GetDefaultDataDir() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\Sagbit // Windows >= Vista: C:\Users\Username\AppData\Roaming\Sagbit // Mac: ~/Library/Application Support/Sagbit // Unix: ~/.sagbit #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "Sagbit"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac pathRet /= "Library/Application Support"; TryCreateDirectory(pathRet); return pathRet / "Sagbit"; #else // Unix return pathRet / ".sagbit"; #endif #endif } static boost::filesystem::path pathCached; static boost::filesystem::path pathCachedNetSpecific; static CCriticalSection csPathCached; const boost::filesystem::path &GetDataDir(bool fNetSpecific) { namespace fs = boost::filesystem; LOCK(csPathCached); fs::path &path = fNetSpecific ? pathCachedNetSpecific : pathCached; // This can be called during exceptions by LogPrintf(), so we cache the // value so we don't have to do memory allocations after that. if (!path.empty()) return path; if (mapArgs.count("-datadir")) { path = fs::system_complete(mapArgs["-datadir"]); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific) path /= BaseParams().DataDir(); fs::create_directories(path); return path; } void ClearDatadirCache() { pathCached = boost::filesystem::path(); pathCachedNetSpecific = boost::filesystem::path(); } boost::filesystem::path GetConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-conf", SAGBIT_CONF_FILENAME)); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile; return pathConfigFile; } void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()) return; // No sagbit.conf file is OK set<string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override sagbit.conf string strKey = string("-") + it->string_key; string strValue = it->value[0]; InterpretNegativeSetting(strKey, strValue); if (mapSettingsRet.count(strKey) == 0) mapSettingsRet[strKey] = strValue; mapMultiSettingsRet[strKey].push_back(strValue); } // If datadir is changed in .conf file: ClearDatadirCache(); } #ifndef WIN32 boost::filesystem::path GetPidFile() { boost::filesystem::path pathPidFile(GetArg("-pid", SAGBIT_PID_FILENAME)); if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile; return pathPidFile; } void CreatePidFile(const boost::filesystem::path &path, pid_t pid) { FILE* file = fopen(path.string().c_str(), "w"); if (file) { fprintf(file, "%d\n", pid); fclose(file); } } #endif bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest) { #ifdef WIN32 return MoveFileExA(src.string().c_str(), dest.string().c_str(), MOVEFILE_REPLACE_EXISTING) != 0; #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } /** * Ignores exceptions thrown by Boost's create_directory if the requested directory exists. * Specifically handles case where path p exists, but it wasn't possible for the user to * write to the parent directory. */ bool TryCreateDirectory(const boost::filesystem::path& p) { try { return boost::filesystem::create_directory(p); } catch (const boost::filesystem::filesystem_error&) { if (!boost::filesystem::exists(p) || !boost::filesystem::is_directory(p)) throw; } // create_directory didn't create the directory, it had to have existed already return false; } void FileCommit(FILE *fileout) { fflush(fileout); // harmless if redundantly called #ifdef WIN32 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fileout)); FlushFileBuffers(hFile); #else #if defined(__linux__) || defined(__NetBSD__) fdatasync(fileno(fileout)); #elif defined(__APPLE__) && defined(F_FULLFSYNC) fcntl(fileno(fileout), F_FULLFSYNC, 0); #else fsync(fileno(fileout)); #endif #endif } bool TruncateFile(FILE *file, unsigned int length) { #if defined(WIN32) return _chsize(_fileno(file), length) == 0; #else return ftruncate(fileno(file), length) == 0; #endif } /** * this function tries to raise the file descriptor limit to the requested number. * It returns the actual file descriptor limit (which may be more or less than nMinFD) */ int RaiseFileDescriptorLimit(int nMinFD) { #if defined(WIN32) return 2048; #else struct rlimit limitFD; if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) { if (limitFD.rlim_cur < (rlim_t)nMinFD) { limitFD.rlim_cur = nMinFD; if (limitFD.rlim_cur > limitFD.rlim_max) limitFD.rlim_cur = limitFD.rlim_max; setrlimit(RLIMIT_NOFILE, &limitFD); getrlimit(RLIMIT_NOFILE, &limitFD); } return limitFD.rlim_cur; } return nMinFD; // getrlimit failed, assume it's fine #endif } /** * this function tries to make a particular range of a file allocated (corresponding to disk space) * it is advisory, and the range specified in the arguments will never contain live data */ void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) { #if defined(WIN32) // Windows-specific version HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); LARGE_INTEGER nFileSize; int64_t nEndPos = (int64_t)offset + length; nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF; nFileSize.u.HighPart = nEndPos >> 32; SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN); SetEndOfFile(hFile); #elif defined(MAC_OSX) // OSX specific version fstore_t fst; fst.fst_flags = F_ALLOCATECONTIG; fst.fst_posmode = F_PEOFPOSMODE; fst.fst_offset = 0; fst.fst_length = (off_t)offset + length; fst.fst_bytesalloc = 0; if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) { fst.fst_flags = F_ALLOCATEALL; fcntl(fileno(file), F_PREALLOCATE, &fst); } ftruncate(fileno(file), fst.fst_length); #elif defined(__linux__) // Version using posix_fallocate off_t nEndPos = (off_t)offset + length; posix_fallocate(fileno(file), 0, nEndPos); #else // Fallback version // TODO: just write one byte per block static const char buf[65536] = {}; fseek(file, offset, SEEK_SET); while (length > 0) { unsigned int now = 65536; if (length < now) now = length; fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway length -= now; } #endif } void ShrinkDebugFile() { // Scroll debug.log if it's getting too big boost::filesystem::path pathLog = GetDataDir() / "debug.log"; FILE* file = fopen(pathLog.string().c_str(), "r"); if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000) { // Restart the file with some of the end std::vector <char> vch(200000,0); fseek(file, -((long)vch.size()), SEEK_END); int nBytes = fread(begin_ptr(vch), 1, vch.size(), file); fclose(file); file = fopen(pathLog.string().c_str(), "w"); if (file) { fwrite(begin_ptr(vch), 1, nBytes, file); fclose(file); } } else if (file != NULL) fclose(file); } #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate) { namespace fs = boost::filesystem; char pszPath[MAX_PATH] = ""; if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } LogPrintf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n"); return fs::path(""); } #endif boost::filesystem::path GetTempPath() { #if BOOST_FILESYSTEM_VERSION == 3 return boost::filesystem::temp_directory_path(); #else // TODO: remove when we don't support filesystem v2 anymore boost::filesystem::path path; #ifdef WIN32 char pszPath[MAX_PATH] = ""; if (GetTempPathA(MAX_PATH, pszPath)) path = boost::filesystem::path(pszPath); #else path = boost::filesystem::path("/tmp"); #endif if (path.empty() || !boost::filesystem::is_directory(path)) { LogPrintf("GetTempPath(): failed to find temp path\n"); return boost::filesystem::path(""); } return path; #endif } void runCommand(const std::string& strCommand) { int nErr = ::system(strCommand.c_str()); if (nErr) LogPrintf("runCommand error: system(%s) returned %d\n", strCommand, nErr); } void RenameThread(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif (defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)) pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) pthread_setname_np(name); #else // Prevent warnings for unused parameters... (void)name; #endif } void SetupEnvironment() { // On most POSIX systems (e.g. Linux, but not BSD) the environment's locale // may be invalid, in which case the "C" locale is used as fallback. #if !defined(WIN32) && !defined(MAC_OSX) && !defined(__FreeBSD__) && !defined(__OpenBSD__) try { std::locale(""); // Raises a runtime error if current locale is invalid } catch (const std::runtime_error&) { setenv("LC_ALL", "C", 1); } #endif // The path locale is lazy initialized and to avoid deinitialization errors // in multithreading environments, it is set explicitly by the main thread. // A dummy locale is used to extract the internal default locale, used by // boost::filesystem::path, which is then used to explicitly imbue the path. std::locale loc = boost::filesystem::path::imbue(std::locale::classic()); boost::filesystem::path::imbue(loc); } bool SetupNetworking() { #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) return false; #endif return true; } void SetThreadPriority(int nPriority) { #ifdef WIN32 SetThreadPriority(GetCurrentThread(), nPriority); #else // WIN32 #ifdef PRIO_THREAD setpriority(PRIO_THREAD, 0, nPriority); #else // PRIO_THREAD setpriority(PRIO_PROCESS, 0, nPriority); #endif // PRIO_THREAD #endif // WIN32 } int GetNumCores() { #if BOOST_VERSION >= 105600 return boost::thread::physical_concurrency(); #else // Must fall back to hardware_concurrency, which unfortunately counts virtual cores return boost::thread::hardware_concurrency(); #endif }
// Copyright 2013 The Flutter 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 "impeller/aiks/aiks_playground.h" #include "impeller/aiks/aiks_context.h" namespace impeller { AiksPlayground::AiksPlayground() = default; AiksPlayground::~AiksPlayground() = default; bool AiksPlayground::OpenPlaygroundHere(const Picture& picture) { return OpenPlaygroundHere( [&picture](AiksContext& renderer, RenderPass& pass) -> bool { return renderer.Render(picture, pass); }); } bool AiksPlayground::OpenPlaygroundHere(AiksPlaygroundCallback callback) { if (!Playground::is_enabled()) { return true; } AiksContext renderer(GetContext()); if (!renderer.IsValid()) { return false; } return Playground::OpenPlaygroundHere( [&renderer, &callback](RenderPass& pass) -> bool { return callback(renderer, pass); }); } } // namespace impeller
// dear imgui, v1.80 // (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/3488 (please post your screenshots/video there!) // - Glossary https://github.com/ocornut/imgui/wiki/Glossary // - Wiki https://github.com/ocornut/imgui/wiki // - Issues & support https://github.com/ocornut/imgui/issues // 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.org". // 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, PLATFORM WINDOWS // [SECTION] DOCKING // [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 read the FAQ (https://www.dearimgui.org/faq) - 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, less 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 the FAQ. - 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 own 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 are 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 made modification to 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 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 are 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/ contains 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 your 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->TexID = (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 mainloop 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 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 contains 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->TextureId. // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization. MyEngineBindTexture((MyTexture*)pcmd->TextureId); // We are using scissoring to clip some objects. All low-level graphics API should supports 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 (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize) // In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize. // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' 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 uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone. Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.). - You can download PNG/PSD files depicting the gamepad controls for common controllers at: 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 as moving back and forth!) (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want to set a boolean to ignore your other external mouse positions until the external source is moved again.) API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. 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 a 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. (Docking/Viewport Branch) - 2020/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that: - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore. you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos) - likewise io.MousePos and GetMousePos() will use OS coordinates. If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos. - 2020/XX/XX (1.XX) - Moved IME support functions from io.ImeSetInputScreenPosFn, io.ImeWindowHandle to the PlatformIO api. - 2020/12/21 (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 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 were 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 the 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 arbitrary 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 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 be used. Sorry! - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. - 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->TexId = 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 set io.Fonts->TexID. - 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 of 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 to 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 to my application? A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags! >> See https://www.dearimgui.org/faq for 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.org" 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 (github.com/ocornut/imgui/issues/3488). Visuals are ideal as they inspire other programmers. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately). */ //------------------------------------------------------------------------- // [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 #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_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. 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. // Docking static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport. static const float DOCKING_SPLITTER_SIZE = 2.0f; //------------------------------------------------------------------------- // [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); 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(ImGuiNavMoveResult* result, ImRect cand); static void NavApplyItemToResult(ImGuiNavMoveResult* 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 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, bool handle_borders_and_resize_grips, 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); static void EndFrameDrawDimmedBackgrounds(); // Viewports const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter. static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags); static void UpdateViewportsNewFrame(); static void UpdateViewportsEndFrame(); static void UpdateSelectWindowViewport(ImGuiWindow* window); static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport); static bool UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window); static void SetCurrentViewport(ImGuiWindow* window, ImGuiViewportP* viewport); static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window); static int FindPlatformMonitorForPos(const ImVec2& pos); static int FindPlatformMonitorForRect(const ImRect& r); static void UpdateViewportPlatformMonitor(ImGuiViewportP* viewport); } //----------------------------------------------------------------------------- // [SECTION] CONTEXT AND MEMORY ALLOCATORS //----------------------------------------------------------------------------- // 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(). // 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call // SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading. // In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into. // 2) 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, you can: // - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h: // struct ImGuiContext; // extern thread_local ImGuiContext* MyImGuiTLS; // #define GImGui MyImGuiTLS // And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword. // - Future development aim 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 different namespace. #ifndef GImGui ImGuiContext* GImGui = NULL; #endif // Memory Allocator functions. Use SetAllocatorFunctions() to change them. // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file. // Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS static void* MallocWrapper(size_t size, void* user_data) { 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 void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper; static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = 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. CircleSegmentMaxError = 1.60f; // 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); // Docking options (when ImGuiConfigFlags_DockingEnable is set) ConfigDockingNoSplit = false; ConfigDockingWithShift = false; ConfigDockingAlwaysTabBar = false; ConfigDockingTransparentPayload = false; // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set) ConfigViewportsNoAutoMerge = false; ConfigViewportsNoTaskBarIcon = false; ConfigViewportsNoDecoration = true; ConfigViewportsNoDefaultParent = false; // 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; // 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)) // Codepoint will not fit in ImWchar (extra parenthesis around 0xFFFF somehow fixes -Wunreachable-code with Clang) cp = IM_UNICODE_CODEPOINT_INVALID; else cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000); 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 ImBezierClosestPointCasteljau() 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(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; } // 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* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) { char* buf_out = buf; const char* buf_end = buf + buf_size; while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end - buf_out - 1), c); } *buf_out = 0; return (int)(buf_out - buf); } int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) { int bytes_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) bytes_count++; else bytes_count += ImTextCountUtf8BytesFromChar(c); } return bytes_count; } //----------------------------------------------------------------------------- // [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 //----------------------------------------------------------------------------- // 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; } //----------------------------------------------------------------------------- // [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 ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] = { ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive }; 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_DockingPreview: return "DockingPreview"; case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg"; 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, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const float border_size = g.Style.FrameBorderSize; if (border_size > 0.0f) { window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } 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, ImDrawCornerFlags_All, THICKNESS); if (!fully_visible) window->DrawList->PopClipRect(); } if (flags & ImGuiNavHighlightFlags_TypeThin) { window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f); } } //----------------------------------------------------------------------------- // [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); ViewportAllowPlatformMonitorExtend = -1; ViewportPos = ImVec2(FLT_MAX, FLT_MAX); MoveId = GetID("#MOVE"); ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); AutoFitFramesX = AutoFitFramesY = -1; AutoPosLastDirection = ImGuiDir_None; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; LastFrameJustFocused = -1; LastTimeActive = -1.0f; FontWindowScale = FontDpiScale = 1.0f; SettingsOffset = -1; DockOrder = -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; 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; } // Filter by viewport if (window->Viewport != g.MouseViewport) if (g.MovingWindow == NULL || window->RootWindow != g.MovingWindow->RootWindow) 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() if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function // Test if we are hovering the right window (our window could be behind another window) // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself. // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while. //if (g.HoveredWindow != window) // return false; if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped)) return false; // Test if another item is active (e.g. being dragged) if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId) return false; // Test if interactions on this window are blocked by an active popup or modal. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. if (!IsWindowContentHoverable(window, flags)) return false; // Test if the item is disabled if ((window->DC.ItemFlags & 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->ID || 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) || (window->DC.ItemFlags & 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. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) { ImGuiContext& g = *GImGui; // Increment counters const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0; window->DC.FocusCounterRegular++; if (is_tab_stop) 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.FocusTabPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.FocusRequestNextWindow == NULL) { g.FocusRequestNextWindow = window; g.FocusRequestNextCounterTabStop = 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.FocusRequestCurrWindow == window) { if (window->DC.FocusCounterRegular == g.FocusRequestCurrCounterRegular) return true; if (is_tab_stop && window->DC.FocusCounterTabStop == g.FocusRequestCurrCounterTabStop) { g.NavJustTabbedId = id; return true; } // If another item is about to be focused, we clear our own active id if (g.ActiveId == id) ClearActiveID(); } return false; } void ImGui::FocusableItemUnregister(ImGuiWindow* window) { window->DC.FocusCounterRegular--; window->DC.FocusCounterTabStop--; } 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(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data) { GImAllocatorAllocFunc = alloc_func; GImAllocatorFreeFunc = free_func; GImAllocatorUserData = user_data; } ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas) { ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas); if (GImGui == NULL) SetCurrentContext(ctx); Initialize(ctx); return ctx; } void ImGui::DestroyContext(ImGuiContext* ctx) { if (ctx == NULL) ctx = GImGui; Shutdown(ctx); if (GImGui == ctx) SetCurrentContext(NULL); IM_DELETE(ctx); } // No specific ordering/dependency support, will see as needed void ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook) { ImGuiContext& g = *ctx; IM_ASSERT(hook->Callback != NULL); g.Hooks.push_back(*hook); } // 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; } ImGuiPlatformIO& ImGui::GetPlatformIO() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?"); return GImGui->PlatformIO; } // Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { ImGuiContext& g = *GImGui; return g.Viewports[0]->DrawDataP.Valid ? &g.Viewports[0]->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->LastFrameDrawLists[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->LastFrameDrawLists[drawlist_no] = g.FrameCount; } return draw_list; } ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport) { return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background"); } ImDrawList* ImGui::GetBackgroundDrawList() { ImGuiWindow* window = GImGui->CurrentWindow; return GetBackgroundDrawList(window->Viewport); } ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport) { return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground"); } ImDrawList* ImGui::GetForegroundDrawList() { ImGuiWindow* window = GImGui->CurrentWindow; return GetForegroundDrawList(window->Viewport); } 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.MouseClickedPos[0] - window->RootWindow->Pos; bool can_move_window = true; if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) can_move_window = false; if (ImGuiDockNode* node = window->DockNodeAsHost) if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove)) can_move_window = false; if (can_move_window) g.MovingWindow = window; } // We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them. // - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node. // - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window. void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node) { ImGuiContext& g = *GImGui; bool can_undock_node = false; if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0) { // Can undock if: // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy) // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows) ImGuiDockNode* root_node = DockNodeGetRootNode(node); if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL) // -V1051 PVS-Studio thinks node should be root_node and is wrong about that. if (undock_floating_node || root_node->IsDockSpace()) can_undock_node = true; } const bool clicked = IsMouseClicked(0); const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f); if (can_undock_node && dragging) DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window) StartMouseMovingWindow(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); if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window. moving_window->Viewport->Pos = pos; } FocusWindow(g.MovingWindow); } else { // Try to merge the window back into the main viewport. // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports) if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport); // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button. if (!IsDragDropPayloadBeingAccepted()) g.MouseViewport = moving_window->Viewport; // Clear the NoInput window flag set by the Viewport system moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL. 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 void to focus window and start moving // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!) 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->RootWindowDockStop : 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) if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive) 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 void TranslateWindow(ImGuiWindow* window, const ImVec2& delta) { window->Pos += delta; window->ClipRect.Translate(delta); window->OuterRectClipped.Translate(delta); window->InnerRect.Translate(delta); window->DC.CursorPos += delta; window->DC.CursorStartPos += delta; window->DC.CursorMaxPos += delta; window->DC.LastItemRect.Translate(delta); window->DC.LastItemDisplayRect.Translate(delta); } static void ScaleWindow(ImGuiWindow* window, float scale) { ImVec2 origin = window->Viewport->Pos; window->Pos = ImFloor((window->Pos - origin) * scale + origin); window->Size = ImFloor(window->Size * scale); window->SizeFull = ImFloor(window->SizeFull * scale); window->ContentSize = ImFloor(window->ContentSize * scale); } 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->Flags & ImGuiWindowFlags_ChildWindow)) { 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 // Vertical Mouse Wheel scrolling const float wheel_y = (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f; if (wheel_y != 0.0f && !g.IO.KeyCtrl) { 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 const float wheel_x = (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) ? g.IO.MouseWheelH : (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) ? g.IO.MouseWheel : 0.0f; if (wheel_x != 0.0f && !g.IO.KeyCtrl) { 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.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab)); if (g.ActiveId == 0 && g.FocusTabPressed) { // Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also // manipulate the Next fields even, even though they will be turned into Curr fields by the code below. g.FocusRequestNextWindow = g.NavWindow; g.FocusRequestNextCounterRegular = INT_MAX; if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX) g.FocusRequestNextCounterTabStop = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); else g.FocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0; } // Turn queued focus request into current one g.FocusRequestCurrWindow = NULL; g.FocusRequestCurrCounterRegular = g.FocusRequestCurrCounterTabStop = INT_MAX; if (g.FocusRequestNextWindow != NULL) { ImGuiWindow* window = g.FocusRequestNextWindow; g.FocusRequestCurrWindow = window; if (g.FocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1) g.FocusRequestCurrCounterRegular = ImModPositive(g.FocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1); if (g.FocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1) g.FocusRequestCurrCounterTabStop = ImModPositive(g.FocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1); g.FocusRequestNextWindow = NULL; g.FocusRequestNextCounterRegular = g.FocusRequestNextCounterTabStop = 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; // 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(); IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport); // Modal windows prevents mouse from hovering behind them. ImGuiWindow* modal_window = GetTopMostPopupModal(); if (modal_window && g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, 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.HoveredRootWindow = 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; CallContextHooks(&g, ImGuiContextHookType_NewFramePre); // Check and assert for various common IO and Configuration mistakes g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame; ErrorCheckNewFrameSanityChecks(); g.ConfigFlagsCurrFrame = g.IO.ConfigFlags; // 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.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX; UpdateViewportsNewFrame(); // Setup current font and draw list shared data // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! 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 = ImVec4(virtual_space.Min.x, virtual_space.Min.y, virtual_space.Max.x, virtual_space.Max.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; g.DrawListSharedData.SetCircleSegmentMaxError(g.Style.CircleSegmentMaxError); 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->DrawData = NULL; 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(); // Undocking // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame) DockContextNewFrameUpdateUndocking(&g); // 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 g.PlatformImePosViewport = NULL; // 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)); 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_Default_); g.GroupStack.resize(0); ClosePopupsOverWindow(g.NavWindow, false); // Docking DockContextNewFrameUpdateDocking(&g); // [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; ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); if (ImGui::IsKeyPressedMap(ImGuiKey_Escape)) g.DebugItemPickerActive = false; if (ImGui::IsMouseClicked(0) && hovered_id) { g.DebugItemPickerBreakId = hovered_id; g.DebugItemPickerActive = false; } ImGui::SetNextWindowBgAlpha(0.60f); ImGui::BeginTooltip(); ImGui::Text("HoveredId: 0x%08X", hovered_id); ImGui::Text("Press ESC to abort picking."); ImGui::TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!"); ImGui::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); } #ifdef IMGUI_HAS_TABLE // Add .ini handle for ImGuiTable type TableSettingsInstallHandler(context); #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK // Create default viewport ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)(); viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID; viewport->Idx = 0; viewport->PlatformWindowCreated = true; g.Viewports.push_back(viewport); g.PlatformIO.MainViewport = g.Viewports[0]; // Make it accessible in public-facing GetPlatformIO() immediately (before the first call to EndFrame) g.PlatformIO.Viewports.push_back(g.Viewports[0]); // Extensions DockContextInitialize(&g); #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); } // Destroy platform windows ImGuiContext* backup_context = ImGui::GetCurrentContext(); SetCurrentContext(context); DestroyPlatformWindows(); SetCurrentContext(backup_context); // Shutdown extensions DockContextShutdown(&g); 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.HoveredRootWindow = 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(); g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL; 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(); g.CurrentTableStack.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; g.IO.MetricsRenderWindows++; AddDrawListToDrawData(&window->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) { // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode, // and to allow applications/backends to easily skip rendering. // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure. // This is because the work has been done already, and its wasted! We should fix that and add optimizations for // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline. const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0; ImDrawData* draw_data = &viewport->DrawDataP; viewport->DrawData = draw_data; // Make publicly accessible 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 = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size; draw_data->FramebufferScale = ImGui::GetIO().DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis? draw_data->OwnerViewport = viewport; 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(); } static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window) { for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--) if (IsWindowActiveAndVisible(window->DC.ChildWindows[n])) return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]); return window; } static void ImGui::EndFrameDrawDimmedBackgrounds() { ImGuiContext& g = *GImGui; // Draw modal whitening background on _other_ viewports than the one the modal is one ImGuiWindow* modal_window = GetTopMostPopupModal(); const bool dim_bg_for_modal = (modal_window != NULL); const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL); if (dim_bg_for_modal || dim_bg_for_window_list) for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++) { ImGuiViewportP* viewport = g.Viewports[viewport_n]; if (modal_window && viewport == modal_window->Viewport) continue; if (g.NavWindowingListWindow && viewport == g.NavWindowingListWindow->Viewport) continue; if (g.NavWindowingTargetAnim && viewport == g.NavWindowingTargetAnim->Viewport) continue; if (viewport->Window && modal_window && IsWindowAbove(viewport->Window, modal_window)) continue; ImDrawList* draw_list = GetForegroundDrawList(viewport); const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio); draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col); } // Draw modal whitening background between CTRL-TAB list if (dim_bg_for_window_list && g.NavWindowingTargetAnim->Active) { // Choose a draw list that will be front-most across all our children // In the unlikely case that the window wasn't made active we can't rely on its drawlist and skip rendering all-together. ImGuiWindow* window = g.NavWindowingTargetAnim; ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindow)->DrawList; draw_list->PushClipRectFullScreen(); // Docking: draw modal whitening background on other nodes of a same dock tree // For CTRL+TAB within a docking node we need to render the dimming background in 8 steps // (Because the root node renders the background in one shot, in order to avoid flickering when a child dock node is not submitted) if (window->RootWindowDockStop->DockIsActive) if (window->RootWindow != window->RootWindowDockStop) RenderRectFilledWithHole(draw_list, window->RootWindow->Rect(), window->RootWindowDockStop->Rect(), GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio), g.Style.WindowRounding); // Draw navigation selection/windowing rectangle border float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding); ImRect bb = window->Rect(); bb.Expand(g.FontSize); if (bb.Contains(window->Viewport->GetMainRect())) // If a window fits the entire viewport, adjust its highlight inward { bb.Expand(-g.FontSize - 1.0f); rounding = window->WindowRounding; } draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f); draw_list->PopClipRect(); } } // 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.PlatformIO.Platform_SetImeInputPos && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImePos - g.PlatformImeLastPos) > 0.0001f)) if (g.PlatformImePosViewport && g.PlatformImePosViewport->PlatformWindowCreated) { g.PlatformIO.Platform_SetImeInputPos(g.PlatformImePosViewport, g.PlatformImePos); g.PlatformImeLastPos = g.PlatformImePos; g.PlatformImePosViewport = NULL; } // 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(); // Draw modal whitening background on _other_ viewports than the one the modal is one EndFrameDrawDimmedBackgrounds(); // Update navigation: CTRL+Tab, wrap-around requests NavEndFrame(); SetCurrentViewport(NULL, NULL); // 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(); // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) UpdateViewportsEndFrame(); // 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]; 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]); ImVec2 mouse_cursor_offset, mouse_cursor_size, mouse_cursor_uv[4]; if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None) g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &mouse_cursor_offset, &mouse_cursor_size, &mouse_cursor_uv[0], &mouse_cursor_uv[2]); // 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 // (note we scale cursor by current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor) if (mouse_cursor_size.x > 0.0f && mouse_cursor_size.y > 0.0f) { float scale = g.Style.MouseCursorScale * viewport->DpiScale; if (viewport->GetMainRect().Overlaps(ImRect(g.IO.MousePos, g.IO.MousePos + ImVec2(mouse_cursor_size.x + 2, mouse_cursor_size.y + 2) * scale))) RenderMouseCursor(GetForegroundDrawList(viewport), g.IO.MousePos, scale, 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]); g.IO.MetricsRenderVertices += viewport->DrawData->TotalVtxCount; g.IO.MetricsRenderIndices += viewport->DrawData->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 text_size.x = IM_FLOOR(text_size.x + 0.95f); 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; // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame) ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL; if (g.MovingWindow) g.MovingWindow->Viewport = g.MouseViewport; 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_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular; for (int i = g.Windows.Size - 1; i >= 0; i--) { ImGuiWindow* window = g.Windows[i]; if (!window->Active || window->Hidden) continue; if (window->Flags & ImGuiWindowFlags_NoMouseInputs) continue; IM_ASSERT(window->Viewport); if (window->Viewport != g.MouseViewport) 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_from_edges); 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; 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.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window; if (g.MovingWindow) g.MovingWindow->Viewport = moving_window_viewport; } // 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; if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped)) 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; // Special handling for the dummy item 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->ID && window->WriteAccessed) return false; return true; } 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 | ImGuiWindowFlags_NoDocking; 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.NavLayerActiveMask != 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.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened)) { ItemAdd(bb, window->ChildId); RenderNavHighlight(bb, window->ChildId); // When browsing a window that has no activable items (scroll only) we keep a highlight on the child if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow) RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); } else { // Not navigable into ItemAdd(bb, 0); } } g.WithinEndChild = false; } // 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); window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~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) { ImGuiViewport* main_viewport = ImGui::GetMainViewport(); window->ViewportPos = main_viewport->Pos; if (settings->ViewportId) { window->ViewportId = settings->ViewportId; window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y); } window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.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; window->DockId = settings->DockId; window->DockOrder = settings->DockOrder; } 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. ImGuiViewport* main_viewport = ImGui::GetMainViewport(); window->Pos = main_viewport->Pos + ImVec2(60, 60); window->ViewportPos = main_viewport->Pos; // 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); } g.WindowsFocusOrder.push_back(window); 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 ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window) { return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window; } static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window) { return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window; } static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) { ImGuiContext& g = *GImGui; 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 = GetWindowForTitleAndMenuHeight(window); new_size = ImMax(new_size, g.Style.WindowMinSize); new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + 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; ImVec2 size_decorations = ImVec2(0.0f, window->TitleBarHeight() + window->MenuBarHeight()); ImVec2 size_pad = window->WindowPadding * 2.0f; ImVec2 size_desired = size_contents + size_pad + size_decorations; 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 = window->Viewport->Size; if (window->ViewportOwned) avail_size = ImVec2(FLT_MAX, FLT_MAX); const int monitor_idx = window->ViewportAllowPlatformMonitorExtend; if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size) avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize; ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - g.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 - size_decorations.x < 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 - size_decorations.y < 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; } 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) }; struct ImGuiResizeBorderDef { ImVec2 InnerDir; ImVec2 CornerPosN1, CornerPosN2; float OuterAngle; }; static const ImGuiResizeBorderDef resize_border_def[4] = { { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Top { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }, // Bottom { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f } // Left }; 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 == 0) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); } // Top if (border_n == 1) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); } // Right if (border_n == 2) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); } // Bottom if (border_n == 3) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); } // Left IM_ASSERT(0); return ImRect(); } // 0..3: corners (Lower-right, Lower-left, Unused, Unused) // 4..7: borders (Top, Right, Bottom, Left) ImGuiID ImGui::GetWindowResizeID(ImGuiWindow* window, int n) { IM_ASSERT(n >= 0 && n <= 7); ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->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_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f; ImVec2 pos_target(FLT_MAX, FLT_MAX); ImVec2 size_target(FLT_MAX, FLT_MAX); // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time). // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits. // This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it. // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration); if (clip_with_viewport_rect) window->ClipRect = window->Viewport->GetMainRect(); // 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& grip = resize_grip_def[resize_grip_n]; const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.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); bool hovered, held; ButtonBehavior(resize_rect, window->GetID(resize_grip_n), &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 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip ImVec2 clamp_min = ImVec2(grip.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, grip.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX); ImVec2 clamp_max = ImVec2(grip.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, grip.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX); corner_target = ImClamp(corner_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } if (resize_grip_n == 0 || held || hovered) resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); } for (int border_n = 0; border_n < resize_border_count; border_n++) { bool hovered, held; ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); ButtonBehavior(border_rect, window->GetID(border_n + 4), &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 = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; if (held) *border_held = border_n; } if (held) { ImVec2 border_target = window->Pos; ImVec2 border_posn; if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left ImVec2 clamp_min = ImVec2(border_n == 1 ? visibility_rect.Min.x : -FLT_MAX, border_n == 2 ? visibility_rect.Min.y : -FLT_MAX); ImVec2 clamp_max = ImVec2(border_n == 3 ? visibility_rect.Max.x : +FLT_MAX, border_n == 0 ? visibility_rect.Max.y : +FLT_MAX); border_target = ImClamp(border_target, clamp_min, clamp_max); CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &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_NavKeyboard && g.IO.KeyShift) nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); if (g.NavInputSource == ImGuiInputSource_NavGamepad) nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down); if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f) { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); 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, ImDrawCornerFlags_All, 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.CornerPosN1) + 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.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f); window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual } if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) { 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, bool handle_borders_and_resize_grips, 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)) { bool is_docking_transparent_payload = false; if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload) if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window) is_docking_transparent_payload = true; ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); if (window->ViewportOwned) { // No alpha bg_col = (bg_col | IM_COL32_A_MASK); if (is_docking_transparent_payload) window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; } else { // Adjust alpha. For docking bool override_alpha = false; float alpha = 1.0f; if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha) { alpha = g.NextWindowData.BgAlphaVal; override_alpha = true; } if (is_docking_transparent_payload) { alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override? 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) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); } // Title bar // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag, // in order for their pos/size to be matching their undocking state.) if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) { 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, ImDrawCornerFlags_Top); } // Menu bar if (flags & ImGuiWindowFlags_MenuBar) { ImRect menu_bar_rect = window->MenuBarRect(); menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top); if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock ImGuiDockNode* node = window->DockNode; if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar()) { float unhide_sz_draw = ImFloor(g.FontSize * 0.70f); float unhide_sz_hit = ImFloor(g.FontSize * 0.55f); ImVec2 p = node->Pos; ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit)); bool hovered, held; if (ButtonBehavior(r, window->GetID("#UNHIDE"), &hovered, &held, ImGuiButtonFlags_FlattenChildren)) node->WantHiddenTabBarToggle = true; else if (held && IsMouseDragging(0)) StartMouseMovingWindowOrNode(window, node, true); // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size.. ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col); } // 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 (handle_borders_and_resize_grips && !(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 (for dock node host they will be rendered over after the tab bar) if (handle_borders_and_resize_grips && !window->DockNodeAsHost) RenderWindowOuterBorders(window); } } // Render title text, collapse button, close button // When inside a dock node, this is handled in DockNodeUpdateTabBar() instead. 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 = window->DC.ItemFlags; window->DC.ItemFlags |= 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, NULL)) 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; window->DC.ItemFlags = 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 correct. 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, layout_r.Max.x + g.Style.ItemInnerSpacing.x, layout_r.Max.y); //if (g.IO.KeyCtrl) window->DrawList->AddRect(layout_r.Min, layout_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->RootWindowDockStop = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window; if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) { window->RootWindow = parent_window->RootWindow; if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost)) window->RootWindowDockStop = parent_window->RootWindowDockStop; } 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 const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0); 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 || window_just_appearing_after_hidden_for_resize); if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); // Update Flags, LastFrameActive, BeginOrderXXX fields if (first_begin_of_the_frame) { window->FlagsPreviousFrame = window->Flags; 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; } // Docking // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1) IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock) SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond); if (first_begin_of_the_frame) { bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL); bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window); if (has_dock_node || new_auto_dock_node) { BeginDocked(window, p_open); flags = window->Flags; if (window->DockIsActive) IM_ASSERT(window->DockNode != NULL); // Docking currently override constraints g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; } } // 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 = window->DockIsActive ? window->DockNode->HostWindow : 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; } if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow)) window->NavLastIds[0] = 0; // 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_HasWindowClass) window->WindowClass = g.NextWindowData.WindowClass; 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 ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive)) window_title_visible_elsewhere = true; else 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) 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 // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes. UpdateSelectWindowViewport(window); SetCurrentViewport(window, window->Viewport); window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f; SetCurrentWindow(window); flags = window->Flags; // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style. if (flags & ImGuiWindowFlags_ChildWindow) window->WindowBorderSize = style.ChildBorderSize; else window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize; if (!window->DockIsActive && (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); else window->WindowPadding = style.WindowPadding; // 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) && !window->DockIsActive) { // 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); FocusWindow(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); // Late create viewport if we don't fit within our current host viewport. if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized)) if (!window->Viewport->GetMainRect().Contains(window->Rect())) { // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport) //ImGuiViewport* old_viewport = window->Viewport; window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); // FIXME-DPI //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong SetCurrentViewport(window, window->Viewport); window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f; SetCurrentWindow(window); } bool viewport_rect_changed = false; if (window->ViewportOwned) { // Synchronize window --> viewport in most situations // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM if (window->Viewport->PlatformRequestMove) { window->Pos = window->Viewport->Pos; MarkIniSettingsDirty(window); } else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0) { viewport_rect_changed = true; window->Viewport->Pos = window->Pos; } if (window->Viewport->PlatformRequestResize) { window->Size = window->SizeFull = window->Viewport->Size; MarkIniSettingsDirty(window); } else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0) { viewport_rect_changed = true; window->Viewport->Size = window->Size; } // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame() // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect. if (viewport_rect_changed) UpdateViewportPlatformMonitor(window->Viewport); // Update common viewport flags const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear; ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear; const bool is_modal = (flags & ImGuiWindowFlags_Modal) != 0; const bool is_short_lived_floating_window = (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0; if (flags & ImGuiWindowFlags_Tooltip) viewport_flags |= ImGuiViewportFlags_TopMost; if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal) viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon; if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window) viewport_flags |= ImGuiViewportFlags_NoDecoration; // Not correct to set modal as topmost because: // - Because other popups can be stacked above a modal (e.g. combo box in a modal) // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost" //if (flags & ImGuiWindowFlags_Modal) // viewport_flags |= ImGuiViewportFlags_TopMost; // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration). // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app, // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere. if (is_short_lived_floating_window && !is_modal) viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick; // We can overwrite viewport flags using ImGuiWindowClass (advanced users) // We don't default to the main viewport because. if (window->WindowClass.ParentViewportId) window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId; else if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack) window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID; else window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID; if (window->WindowClass.ViewportFlagsOverrideSet) viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet; if (window->WindowClass.ViewportFlagsOverrideClear) viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear; // We also tell the backend that clearing the platform window won't be necessary, as our window is filling the viewport and we have disabled BgAlpha if (!(flags & ImGuiWindowFlags_NoBackground)) viewport_flags &= ~ImGuiViewportFlags_NoRendererClear; window->Viewport->Flags = viewport_flags; } // 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. ImRect viewport_rect(window->Viewport->GetMainRect()); ImRect viewport_work_rect(window->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. // FIXME: Similar to code in GetWindowAllowedExtentRect() if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) { if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f) { ClampWindowRect(window, visibility_rect); } else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0) { if (window->Viewport->PlatformMonitor == -1) { // Fallback for "lost" window (e.g. a monitor disconnected): we move the window back over the main viewport SetWindowPos(window, g.Viewports[0]->Pos + style.DisplayWindowPadding, ImGuiCond_Always); } else { ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->Viewport->PlatformMonitor]; visibility_rect.Min = monitor.WorkPos + visibility_padding; visibility_rect.Max = monitor.WorkPos + monitor.WorkSize - visibility_padding; 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. if (window->ViewportOwned || window->DockIsActive) window->WindowRounding = 0.0f; else 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 ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip)) want_focus = true; } // Decide if we are going to handle borders and resize grips const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive); // 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 (handle_borders_and_resize_grips && !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; // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either) if (window->ViewportOwned) { if (!window->Viewport->PlatformRequestMove) window->Viewport->Pos = window->Pos; if (!window->Viewport->PlatformRequestResize) window->Viewport->Size = window->Size; viewport_rect = window->Viewport->GetMainRect(); } // Save last known viewport position within the window itself (so it can be saved in .ini file and restored) window->ViewportPos = window->Viewport->Pos; // 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; if (window->DockIsActive) window->OuterRectClipped.Min.y += window->TitleBarHeight(); 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 or window list full viewport dimming background (for other viewports we'll render them in EndFrame) ImGuiWindow* window_window_list = g.NavWindowingListWindow; 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) || (window == window_window_list && window_window_list->Viewport != g.NavWindowingTargetAnim->Viewport)); 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. const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible; if (is_undocked_or_docked_visible) { 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 || (window->DockNode && window->DockNode == window_to_highlight->DockNode))); RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, 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.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 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); } // Close requested by platform window if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport()) { if (!window->DockIsActive || window->DockTabIsVisible) { window->Viewport->PlatformRequestClose = false; g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' PlatformRequestClose\n", window->Name); *p_open = false; } } // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive) RenderWindowTitleBarContents(window, title_bar_rect, 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(); */ if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) { // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift)) if ((window->RootWindow->Flags & ImGuiWindowFlags_NoDocking) == 0) BeginDockableDragDropSource(window); // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead. if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking)) if (g.MovingWindow == NULL || g.MovingWindow->RootWindow != window) if ((window == window->RootWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost)) BeginDockableDragDropTarget(window); } // 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. if (window->DockIsActive) SetLastItemData(window, window->ID, window->DockTabItemStatusFlags, window->DockTabItemRect); else 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 SetCurrentViewport(window, window->Viewport); SetCurrentWindow(window); } // Pull/inherit current state window->DC.ItemFlags = g.ItemFlagsStack.back(); // Inherit from shared stack window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // Inherit from parent only // -V595 if (!(flags & ImGuiWindowFlags_DockNodeHost)) 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) { // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. // This is analogous to regular windows being hidden from one frame. // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. if (window->DockIsActive && !window->DockTabIsVisible) { if (window->LastFrameJustFocused == g.FrameCount) window->HiddenFramesCannotSkipItems = 1; else window->HiddenFramesCanSkipItems = 1; } 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 || (window->DockIsActive)); 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); // 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) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive) IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!"); // Close anything that is open if (window->DC.CurrentColumns) EndColumns(); if (!(window->Flags & ImGuiWindowFlags_DockNodeHost)) // Pop inner window clip rectangle PopClipRect(); // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging LogFinish(); // Docking: report contents sizes to parent to allow for auto-resize if (window->DockNode && window->DockTabIsVisible) if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding; // 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()); if (g.CurrentWindow) SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport); } void ImGui::BringWindowToFocusFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.WindowsFocusOrder.back() == window) return; for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the top-most window if (g.WindowsFocusOrder[i] == window) { memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*)); g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window; break; } } 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.NavInitRequest = false; g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId g.NavFocusScopeId = 0; g.NavIdIsAlive = false; g.NavLayer = ImGuiNavLayer_Main; //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->RootWindowDockStop : NULL; ImGuiWindow* display_front_window = window ? window->RootWindow : NULL; ImGuiDockNode* dock_node = window ? window->DockNode : NULL; bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow); // 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) // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindowDockStop != focus_front_window) if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host) ClearActiveID(); // Passing NULL allow to disable keyboard focus if (!window) return; window->LastFrameJustFocused = g.FrameCount; // Select in dock node if (dock_node && dock_node->TabBar) dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->ID; // Bring to front BringWindowToFocusFront(focus_front_window); if (((window->Flags | focus_front_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; int start_idx = g.WindowsFocusOrder.Size - 1; if (under_this_window != NULL) { int under_this_window_idx = FindWindowFocusIndex(under_this_window); if (under_this_window_idx != -1) start_idx = under_this_window_idx - 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]; if (window != ignore_window && window->WasActive && window->RootWindowDockStop == window) if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) { // FIXME-DOCK: This is failing (lagging by one frame) for docked windows. // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B. // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update) // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself? ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window); FocusWindow(focus_window); return; } } FocusWindow(NULL); } 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; ImGuiWindow* window = g.CurrentWindow; ImGuiItemFlags item_flags = window->DC.ItemFlags; IM_ASSERT(item_flags == g.ItemFlagsStack.back()); if (enabled) item_flags |= option; else item_flags &= ~option; window->DC.ItemFlags = item_flags; g.ItemFlagsStack.push_back(item_flags); } void ImGui::PopItemFlag() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; 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(); window->DC.ItemFlags = 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.TextWrapPos = wrap_pos_x; window->DC.TextWrapPosStack.push_back(wrap_pos_x); } void ImGui::PopTextWrapPos() { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPosStack.pop_back(); window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); } 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 (flags & ImGuiHoveredFlags_AnyWindow) { if (g.HoveredWindow == NULL) return false; } else { switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) { case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows: if (g.HoveredWindow == NULL || g.HoveredWindow->RootWindowDockStop != g.CurrentWindow->RootWindowDockStop) return false; break; case ImGuiHoveredFlags_RootWindow: if (g.HoveredWindow != g.CurrentWindow->RootWindowDockStop) return false; break; case ImGuiHoveredFlags_ChildWindows: if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow)) return false; break; default: if (g.HoveredWindow != g.CurrentWindow) return false; break; } } if (!IsWindowContentHoverable(g.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->RootWindowDockStop == g.CurrentWindow->RootWindowDockStop; case ImGuiFocusedFlags_RootWindow: return g.NavWindow == g.CurrentWindow->RootWindowDockStop; case ImGuiFocusedFlags_ChildWindows: return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow); default: return g.NavWindow == g.CurrentWindow; } } ImGuiID ImGui::GetWindowDockID() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockId; } bool ImGui::IsWindowDocked() { ImGuiContext& g = *GImGui; return g.CurrentWindow->DockIsActive; } // 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->RootWindowDockStop && !(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.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; g.NextWindowData.PosUndock = true; } 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; } void ImGui::SetNextWindowViewport(ImGuiID id) { ImGuiContext& g = *GImGui; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport; g.NextWindowData.ViewportId = id; } void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond) { ImGuiContext& g = *GImGui; g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock; g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always; g.NextWindowData.DockId = id; } void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class) { ImGuiContext& g = *GImGui; IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass; g.NextWindowData.WindowClass = *window_class; } ImDrawList* ImGui::GetWindowDrawList() { ImGuiWindow* window = GetCurrentWindow(); return window->DrawList; } float ImGui::GetWindowDpiScale() { ImGuiContext& g = *GImGui; return g.CurrentDpiScale; } ImGuiViewport* ImGui::GetWindowViewport() { ImGuiContext& g = *GImGui; IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport); return g.CurrentViewport; } 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.FocusRequestNextWindow = window; g.FocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset; g.FocusRequestNextCounterTabStop = INT_MAX; } void ImGui::SetItemDefaultFocus() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!window->Appearing) return; if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent) { g.NavInitRequest = false; g.NavInitResultId = g.NavWindow->DC.LastItemId; g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos); NavUpdateAnyRequestFlag(); if (!IsItemVisible()) 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 you 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.CircleSegmentMaxError > 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; // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data. if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0) IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0) IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!"); // Perform simple checks: multi-viewport and platform windows support if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports)) { IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference."); IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?"); IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?"); IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?"); IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?"); IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?"); IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?"); IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?"); IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport."); if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!"); } else { // Disable feature, our backends do not support it g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable; } // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) { ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n]; IM_UNUSED(mon); IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly."); IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them."); IM_ASSERT(mon.DpiScale != 0.0f); } } } 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) { #ifdef IMGUI_HAS_TABLE 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(); } #endif 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) { 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.NavLayerActiveMaskNext |= (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] // 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; } void ImGui::PushItemWidth(float item_width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); 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(w_item_last); for (int i = 0; i < components - 1; i++) window->DC.ItemWidthStack.push_back(w_item_one); window->DC.ItemWidth = window->DC.ItemWidthStack.back(); g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; } void ImGui::PopItemWidth() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidthStack.pop_back(); window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.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.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 Log 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 Log 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 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 center_x_ratio = window->ScrollTargetCenterRatio.x; float scroll_target_x = window->ScrollTarget.x; float snap_x_min = 0.0f; float snap_x_max = window->ScrollMax.x + window->Size.x; if (window->ScrollTargetEdgeSnapDist.x > 0.0f) 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 - window->ScrollbarSizes.x); } if (window->ScrollTarget.y < FLT_MAX) { float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); float center_y_ratio = window->ScrollTargetCenterRatio.y; float scroll_target_y = window->ScrollTarget.y; float snap_y_min = 0.0f; float snap_y_max = window->ScrollMax.y + window->Size.y - decoration_up_height; if (window->ScrollTargetEdgeSnapDist.y > 0.0f) 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 - window->ScrollbarSizes.y - decoration_up_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); local_y -= window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect 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 = 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 = 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 | ImGuiWindowFlags_NoDocking; 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); } // 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 | ImGuiWindowFlags_NoDocking; 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) { ImGuiViewportP* viewport = window->WasActive ? window->Viewport : (ImGuiViewportP*)GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport? SetNextWindowPos(viewport->GetMainRect().GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); } flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking; 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. // - You can pass a NULL str_id to use the identifier of the last item. // - You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // - This is essentially the same as calling OpenPopupOnItemClick() + BeginPopup() but written to avoid // computing the ID twice because BeginPopupContextXXX functions may be called very frequently. 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; ImRect r_screen; if (window->ViewportAllowPlatformMonitorExtend >= 0) { // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here) const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend]; r_screen.Min = monitor.WorkPos; r_screen.Max = monitor.WorkPos + monitor.WorkSize; } else { // Use the full viewport area (not work area) for popups r_screen.Min = window->Viewport->Pos; r_screen.Max = window->Viewport->Pos + window->Viewport->Size; } 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; 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. ImGuiWindow* parent_window = window->ParentWindow; 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_outer = GetWindowAllowedExtentRect(window); 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_outer = GetWindowAllowedExtentRect(window); 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_outer = GetWindowAllowedExtentRect(window); 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 SetNavIDWithRectRel vs SetFocusID is incredibly messy and confusing, // and needs some explanation or serious refactoring. void ImGui::SetNavID(ImGuiID id, int nav_layer, ImGuiID focus_scope_id) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindow); IM_ASSERT(nav_layer == 0 || nav_layer == 1); g.NavId = id; g.NavFocusScopeId = focus_scope_id; g.NavWindow->NavLastIds[nav_layer] = id; } void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel) { ImGuiContext& g = *GImGui; SetNavID(id, nav_layer, focus_scope_id); g.NavWindow->NavRectRel[nav_layer] = rect_rel; g.NavMousePosDirty = true; g.NavDisableHighlight = false; g.NavDisableMouseHover = 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(ImGuiNavMoveResult* 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(ImGuiNavMoveResult* 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 = window->DC.ItemFlags; 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))) { ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; #if IMGUI_DEBUG_NAV_SCORING // [DEBUG] Score all items in NavWindow at all times if (!g.NavMoveRequest) g.NavMoveDir = g.NavMoveDirLast; bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest; #else bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb); #endif if (new_best) 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; g.NavIdTabCounter = window->DC.FocusCounterTabStop; 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->RootWindowDockStop != parent && (parent->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (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; if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar) if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar)) return tab->Window; return window; } static void NavRestoreLayer(ImGuiNavLayer layer) { ImGuiContext& g = *GImGui; g.NavLayer = layer; if (layer == 0) g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow); ImGuiWindow* window = g.NavWindow; if (window->NavLastIds[layer] != 0) ImGui::SetNavIDWithRectRel(window->NavLastIds[layer], layer, 0, g.NavWindow->NavRectRel[layer]); else ImGui::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); bool init_for_nav = false; if (!(window->Flags & ImGuiWindowFlags_NoNavInputs)) if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) init_for_nav = true; 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); 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())); ImRect visible_rect = g.NavWindow->Viewport->GetMainRect(); return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // 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_NavGamepad) { 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_NavGamepad; } // 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_NavKeyboard; } } 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; if (io.KeyAlt && !io.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu. io.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; #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 && (!g.NavDisableHighlight || g.NavInitRequestFromMove)) 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.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow && g.NavWindow != g.NavWindow->RootWindowDockStop) { // Exit child window ImGuiWindow* child_window = g.NavWindow; ImGuiWindow* parent_window = g.NavWindow->ParentWindow; IM_ASSERT(child_window->ChildId != 0); FocusWindow(parent_window); SetNavID(child_window->ChildId, 0, 0); // Reassigning with same value, we're being explicit here. g.NavIdIsAlive = false; // -V1048 if (g.NavDisableMouseHover) g.NavMousePosDirty = true; } else if (g.OpenPopupStack.Size > 0) { // Close open popup/menu if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal)) ClosePopupToLevel(g.OpenPopupStack.Size - 1, true); } else if (g.NavLayer != ImGuiNavLayer_Main) { // Leave the "menu" layer NavRestoreLayer(ImGuiNavLayer_Main); } 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.NavLayerActiveMask == 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_NavGamepad && 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) IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name); if (g.NavInitRequestFromMove) SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel); else SetNavID(g.NavInitResultId, g.NavLayer, 0); g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel; } // 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 ImGuiNavMoveResult* 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); SetNavIDWithRectRel(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel); } // 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.NavLayerActiveMask == 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) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--) if (g.WindowsFocusOrder[i] == window) return i; return -1; } 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->RootWindowDockStop; g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true; g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad; } // Gamepad update g.NavWindowingTimer += g.IO.DeltaTime; if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad) { // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.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_NavKeyboard) { // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.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_NavKeyboard && !g.IO.KeyShift) move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); if (g.NavInputSource == ImGuiInputSource_NavGamepad) move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down); if (move_delta.x != 0.0f || move_delta.y != 0.0f) { const float NAV_MOVE_SPEED = 800.0f; const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // 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->RootWindowDockStop)) { ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL; 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 only has a menu layer, select it directly if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu)) g.NavLayer = ImGuiNavLayer_Menu; // Request OS level focus if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus) g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport); } if (apply_focus_window) g.NavWindowingTarget = NULL; // Apply menu/layer toggle if (apply_toggle_layer && g.NavWindow) { // Move to parent menu if necessary ImGuiWindow* new_nav_window = g.NavWindow; while (new_nav_window->ParentWindow && (new_nav_window->DC.NavLayerActiveMask & (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; // When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID. It however persist on docking tab tabs. const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main; const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL); if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id) g.NavWindow->NavLastIds[ImGuiNavLayer_Menu] = 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)"; if (window->DockNodeAsHost) return "(Dock node)"; 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"); ImGuiViewportP* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ (ImGuiViewportP*)GetMainViewport(); SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); SetNextWindowPos(viewport->Pos + viewport->Size * 0.5f, 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]; 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)); } // Call when current ID is active. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; bool source_drag_active = false; ImGuiID source_id = 0; ImGuiID source_parent_id = 0; ImGuiMouseButton mouse_button = ImGuiMouseButton_Left; if (!(flags & ImGuiDragDropFlags_SourceExtern)) { source_id = window->DC.LastItemId; if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case return false; if (g.IO.MouseDown[mouse_button] == false) return false; if (source_id == 0) { // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID)) { IM_ASSERT(0); return false; } // 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; } else { g.ActiveIdAllowOverlap = false; } 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-DRAG: Settle on a proper default visuals for drop target. r.Expand(3.5f); bool push_clip_rect = !window->ClipRect.Contains(r); if (push_clip_rect) window->DrawList->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) void ImGui::LogText(const char* fmt, ...) { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; va_list args; va_start(args, fmt); 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); } va_end(args); } // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!text_end) text_end = FindRenderedTextEnd(text, text_end); const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1); if (ref_pos) g.LogLinePosY = ref_pos->y; if (log_new_line) g.LogLineFirstItem = true; const char* text_remaining = text; if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth g.LogDepthRef = window->DC.TreeDepth; const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. // We don't add a trailing \n 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_first_line = (line_start == text); const bool is_last_line = (line_end == text_end); if (!is_last_line || (line_start != line_end)) { const int char_count = (int)(line_end - line_start); if (log_new_line || !is_first_line) LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start); else if (g.LogLineFirstItem) LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start); else LogText(" %.*s", char_count, line_start); g.LogLineFirstItem = false; } else if (log_new_line) { // An empty "" string at a different Y position should output a carriage return. LogText(IM_NEWLINE); break; } if (is_last_line) break; text_remaining = line_end + 1; } } // 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.LogDepthRef = window->DC.TreeDepth; g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); g.LogLinePosY = FLT_MAX; g.LogLineFirstItem = true; } 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; ImU32 u1; 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, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; } else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); } else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); } else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; } else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; } else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; } } // 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(window->Pos - window->ViewportPos); settings->Size = ImVec2ih(window->SizeFull); settings->ViewportId = window->ViewportId; settings->ViewportPos = ImVec2ih(window->ViewportPos); IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId); settings->DockId = window->DockId; settings->ClassId = window->WindowClass.ClassId; settings->DockOrder = window->DockOrder; 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); if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID) { buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y); buf->appendf("ViewportId=0x%08X\n", settings->ViewportId); } if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID) buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y); if (settings->Size.x != 0 || settings->Size.y != 0) buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y); buf->appendf("Collapsed=%d\n", settings->Collapsed); if (settings->DockId != 0) { // Write DockId as 4 digits if possible. Automatic DockId are small numbers, but full explicit DockSpace() are full ImGuiID range. if (settings->DockOrder == -1) buf->appendf("DockId=0x%08X\n", settings->DockId); else buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder); if (settings->ClassId != 0) buf->appendf("ClassId=0x%08X\n", settings->ClassId); } buf->append("\n"); } } //----------------------------------------------------------------------------- // [SECTION] VIEWPORTS, PLATFORM WINDOWS //----------------------------------------------------------------------------- // - GetMainViewport() // - FindViewportByID() // - FindViewportByPlatformHandle() // - SetCurrentViewport() [Internal] // - SetWindowViewport() [Internal] // - GetWindowAlwaysWantOwnViewport() [Internal] // - UpdateTryMergeWindowIntoHostViewport() [Internal] // - UpdateTryMergeWindowIntoHostViewports() [Internal] // - TranslateWindowsInViewport() [Internal] // - ScaleWindowsInViewport() [Internal] // - FindHoveredViewportFromPlatformWindowStack() [Internal] // - UpdateViewportsNewFrame() [Internal] // - UpdateViewportsEndFrame() [Internal] // - AddUpdateViewport() [Internal] // - UpdateSelectWindowViewport() [Internal] // - UpdatePlatformWindows() // - RenderPlatformWindowsDefault() // - FindPlatformMonitorForPos() [Internal] // - FindPlatformMonitorForRect() [Internal] // - UpdateViewportPlatformMonitor() [Internal] // - DestroyPlatformWindow() [Internal] // - DestroyPlatformWindows() //----------------------------------------------------------------------------- ImGuiViewport* ImGui::GetMainViewport() { ImGuiContext& g = *GImGui; return g.Viewports[0]; } ImGuiViewport* ImGui::FindViewportByID(ImGuiID id) { ImGuiContext& g = *GImGui; for (int n = 0; n < g.Viewports.Size; n++) if (g.Viewports[n]->ID == id) return g.Viewports[n]; return NULL; } ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle) { ImGuiContext& g = *GImGui; for (int i = 0; i != g.Viewports.Size; i++) if (g.Viewports[i]->PlatformHandle == platform_handle) return g.Viewports[i]; return NULL; } void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport) { ImGuiContext& g = *GImGui; (void)current_window; if (viewport) viewport->LastFrameActive = g.FrameCount; if (g.CurrentViewport == viewport) return; g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f; g.CurrentViewport = viewport; //IMGUI_DEBUG_LOG_VIEWPORT("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0); // Notify platform layer of viewport changes // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport) g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport); } static void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport) { window->Viewport = viewport; window->ViewportId = viewport->ID; window->ViewportOwned = (viewport->Window == window); } static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window) { // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own. ImGuiContext& g = *GImGui; if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge)) if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) if (!window->DockIsActive) if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0) if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0) return true; return false; } static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport) { ImGuiContext& g = *GImGui; if (window->Viewport == viewport) return false; if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0) return false; if ((viewport->Flags & ImGuiViewportFlags_Minimized) != 0) return false; if (!viewport->GetMainRect().Contains(window->Rect())) return false; if (GetWindowAlwaysWantOwnViewport(window)) return false; for (int n = 0; n < g.Windows.Size; n++) { ImGuiWindow* window_behind = g.Windows[n]; if (window_behind == window) break; if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow)) if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect())) return false; } // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child) ImGuiViewportP* old_viewport = window->Viewport; if (window->ViewportOwned) for (int n = 0; n < g.Windows.Size; n++) if (g.Windows[n]->Viewport == old_viewport) SetWindowViewport(g.Windows[n], viewport); SetWindowViewport(window, viewport); BringWindowToDisplayFront(window); return true; } static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window) { ImGuiContext& g = *GImGui; return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]); } // Translate imgui windows when a Host Viewport has been moved // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos) { ImGuiContext& g = *GImGui; IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows)); // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently // translate imgui windows from OS-window-local to absolute coordinates or vice-versa. // 2) If it's not going to fit into the new size, keep it at same absolute position. // One problem with this is that most Win32 applications doesn't update their render while dragging, // and so the window will appear to teleport when releasing the mouse. const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable); ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size); ImVec2 delta_pos = new_pos - old_pos; for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect()))) TranslateWindow(g.Windows[window_n], delta_pos); } // Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale) { ImGuiContext& g = *GImGui; if (viewport->Window) { ScaleWindow(viewport->Window, scale); } else { for (int i = 0; i != g.Windows.Size; i++) if (g.Windows[i]->Viewport == viewport) ScaleWindow(g.Windows[i], scale); } } // If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves. // A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. // B) It requires Platform_GetWindowFocus to be implemented by backend. static ImGuiViewportP* FindHoveredViewportFromPlatformWindowStack(const ImVec2 mouse_platform_pos) { ImGuiContext& g = *GImGui; ImGuiViewportP* best_candidate = NULL; for (int n = 0; n < g.Viewports.Size; n++) { ImGuiViewportP* viewport = g.Viewports[n]; if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos)) if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount) best_candidate = viewport; } return best_candidate; } // Update viewports and monitor infos // Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. static void ImGui::UpdateViewportsNewFrame() { ImGuiContext& g = *GImGui; IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size); // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport) const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0; if (viewports_enabled) { for (int n = 0; n < g.Viewports.Size; n++) { ImGuiViewportP* viewport = g.Viewports[n]; const bool platform_funcs_available = viewport->PlatformWindowCreated; if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available) { bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport); if (minimized) viewport->Flags |= ImGuiViewportFlags_Minimized; else viewport->Flags &= ~ImGuiViewportFlags_Minimized; } } } // Create/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]; IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID); IM_ASSERT(main_viewport->Window == NULL); ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f); ImVec2 main_viewport_size = g.IO.DisplaySize; if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized)) { main_viewport_pos = main_viewport->Pos; // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path) main_viewport_size = main_viewport->Size; } AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_CanHostOtherWindows); g.CurrentDpiScale = 0.0f; g.CurrentViewport = NULL; g.MouseViewport = NULL; for (int n = 0; n < g.Viewports.Size; n++) { ImGuiViewportP* viewport = g.Viewports[n]; viewport->Idx = n; // Erase unused viewports if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2) { // Clear references to this viewport in windows (window->ViewportId becomes the master data) for (int window_n = 0; window_n < g.Windows.Size; window_n++) if (g.Windows[window_n]->Viewport == viewport) { g.Windows[window_n]->Viewport = NULL; g.Windows[window_n]->ViewportOwned = false; } if (viewport == g.MouseLastHoveredViewport) g.MouseLastHoveredViewport = NULL; g.Viewports.erase(g.Viewports.Data + n); // Destroy IMGUI_DEBUG_LOG_VIEWPORT("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here. IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false); IM_DELETE(viewport); n--; continue; } const bool platform_funcs_available = viewport->PlatformWindowCreated; if (viewports_enabled) { // Update Position and Size (from Platform Window to ImGui) if requested. // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities. if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available) { if (viewport->PlatformRequestMove) viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport); if (viewport->PlatformRequestResize) viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport); } } // Update/copy monitor info UpdateViewportPlatformMonitor(viewport); // Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again. viewport->WorkOffsetMin = viewport->CurrWorkOffsetMin; viewport->WorkOffsetMax = viewport->CurrWorkOffsetMax; viewport->CurrWorkOffsetMin = viewport->CurrWorkOffsetMax = ImVec2(0.0f, 0.0f); // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back. viewport->Alpha = 1.0f; // Translate imgui windows when a Host Viewport has been moved // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!) const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos; if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f)) TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos); // Update DPI scale float new_dpi_scale; if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available) new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport); else if (viewport->PlatformMonitor != -1) new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; else new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f; if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale) { float scale_factor = new_dpi_scale / viewport->DpiScale; if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports) ScaleWindowsInViewport(viewport, scale_factor); //if (viewport == GetMainViewport()) // g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor); // Scale our window moving pivot so that the window will rescale roughly around the mouse position. // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border. // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.) //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport) // g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor); } viewport->DpiScale = new_dpi_scale; } if (!viewports_enabled) { g.MouseViewport = main_viewport; return; } // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport. // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set. ImGuiViewportP* viewport_hovered = NULL; if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) { viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL; if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) { // Backend failed at honoring its contract if it returned a viewport with the _NoInputs flag. IM_ASSERT(0); viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); } } else { // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search: // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. // B) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO) viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); } if (viewport_hovered != NULL) g.MouseLastHoveredViewport = viewport_hovered; else if (g.MouseLastHoveredViewport == NULL) g.MouseLastHoveredViewport = g.Viewports[0]; // Update mouse reference viewport // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode) if (g.MovingWindow) g.MouseViewport = g.MovingWindow->Viewport; else g.MouseViewport = g.MouseLastHoveredViewport; // When dragging something, always refer to the last hovered viewport. // - when releasing a moving window we will revert to aiming behind (at viewport_hovered) // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info) // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release. const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive; if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL) viewport_hovered = g.MouseLastHoveredViewport; if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown()) if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs)) g.MouseViewport = viewport_hovered; IM_ASSERT(g.MouseViewport != NULL); } // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) static void ImGui::UpdateViewportsEndFrame() { ImGuiContext& g = *GImGui; g.PlatformIO.MainViewport = g.Viewports[0]; g.PlatformIO.Viewports.resize(0); for (int i = 0; i < g.Viewports.Size; i++) { ImGuiViewportP* viewport = g.Viewports[i]; viewport->LastPos = viewport->Pos; if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f) if (i > 0) // Always include main viewport in the list continue; if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)) continue; if (i > 0) IM_ASSERT(viewport->Window != NULL); g.PlatformIO.Viewports.push_back(viewport); } g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called } // FIXME: We should ideally refactor the system to call this every frame (we currently don't) ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags) { ImGuiContext& g = *GImGui; IM_ASSERT(id != 0); if (window != NULL) { if (g.MovingWindow && g.MovingWindow->RootWindow == window) flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing; if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs)) flags |= ImGuiViewportFlags_NoInputs; if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing) flags |= ImGuiViewportFlags_NoFocusOnAppearing; } ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id); if (viewport) { if (!viewport->PlatformRequestMove) viewport->Pos = pos; if (!viewport->PlatformRequestResize) viewport->Size = size; viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags } else { // New viewport viewport = IM_NEW(ImGuiViewportP)(); viewport->ID = id; viewport->Idx = g.Viewports.Size; viewport->Pos = viewport->LastPos = pos; viewport->Size = size; viewport->Flags = flags; UpdateViewportPlatformMonitor(viewport); g.Viewports.push_back(viewport); IMGUI_DEBUG_LOG_VIEWPORT("Add Viewport %08X (%s)\n", id, window->Name); // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport. // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x); g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y); g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x); g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y); // Store initial DpiScale before the OS platform window creation, based on expected monitor data. // This is so we can select an appropriate font size on the first frame of our window lifetime if (viewport->PlatformMonitor != -1) viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale; } viewport->Window = window; viewport->LastFrameActive = g.FrameCount; IM_ASSERT(window == NULL || viewport->ID == window->ID); if (window != NULL) window->ViewportOwned = true; return viewport; } // FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; window->ViewportAllowPlatformMonitorExtend = -1; // Restore main viewport if multi-viewport is not supported by the backend ImGuiViewportP* main_viewport = g.Viewports[0]; if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) { SetWindowViewport(window, main_viewport); return; } window->ViewportOwned = false; // Appearing popups reset their viewport so they can inherit again if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing) { window->Viewport = NULL; window->ViewportId = 0; } if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0) { // By default inherit from parent window if (window->Viewport == NULL && window->ParentWindow && !window->ParentWindow->IsFallbackWindow) window->Viewport = window->ParentWindow->Viewport; // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file if (window->Viewport == NULL && window->ViewportId != 0) { window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId); if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX) window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None); } } bool lock_viewport = false; if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) { // Code explicitly request a viewport window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId); window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet. lock_viewport = true; } else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu)) { // Always inherit viewport from parent window window->Viewport = window->ParentWindow->Viewport; } else if (flags & ImGuiWindowFlags_Tooltip) { window->Viewport = g.MouseViewport; } else if (GetWindowAlwaysWantOwnViewport(window)) { window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); } else if (g.MovingWindow && g.MovingWindow->RootWindow == window && IsMousePosValid()) { if (window->Viewport != NULL && window->Viewport->Window == window) window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); } else { // Merge into host viewport? // We cannot test window->ViewportOwned as it set lower in the function. bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && g.ActiveId == 0); if (try_to_merge_into_host_viewport) UpdateTryMergeWindowIntoHostViewports(window); } // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport if (window->Viewport == NULL) if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport)) window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None); // Mark window as allowed to protrude outside of its viewport and into the current monitor if (!lock_viewport) { if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) { // We need to take account of the possibility that mouse may become invalid. // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds. ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos; bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow); bool mouse_valid = IsMousePosValid(&mouse_ref); if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid)) window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos()); else window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; } else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow)) { // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code. const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true; if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible) { // Steal/transfer ownership IMGUI_DEBUG_LOG_VIEWPORT("Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name); window->Viewport->Window = window; window->Viewport->ID = window->ID; window->Viewport->LastNameHash = 0; } else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge? { // New viewport window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing); } } else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0) { // Regular (non-child, non-popup) windows by default are also allowed to protrude // Child windows are kept contained within their parent. window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor; } } // Update flags window->ViewportOwned = (window == window->Viewport->Window); window->ViewportId = window->Viewport->ID; // If the OS window has a title bar, hide our imgui title bar //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration)) // window->Flags |= ImGuiWindowFlags_NoTitleBar; } // Called by user at the end of the main loop, after EndFrame() // This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. void ImGui::UpdatePlatformWindows() { ImGuiContext& g = *GImGui; IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?"); IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount); g.FrameCountPlatformEnded = g.FrameCount; if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)) return; // Create/resize/destroy platform windows to match each active viewport. // Skip the main viewport (index 0), which is always fully handled by the application! for (int i = 1; i < g.Viewports.Size; i++) { ImGuiViewportP* viewport = g.Viewports[i]; // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame) bool destroy_platform_window = false; destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1); destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window)); if (destroy_platform_window) { DestroyPlatformWindow(viewport); continue; } // New windows that appears directly in a new viewport won't always have a size on their first frame if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0) continue; // Create window bool is_new_platform_window = (viewport->PlatformWindowCreated == false); if (is_new_platform_window) { IMGUI_DEBUG_LOG_VIEWPORT("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a"); g.PlatformIO.Platform_CreateWindow(viewport); if (g.PlatformIO.Renderer_CreateWindow != NULL) g.PlatformIO.Renderer_CreateWindow(viewport); viewport->LastNameHash = 0; viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?) viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it. viewport->PlatformWindowCreated = true; } // Apply Position and Size (from ImGui to Platform/Renderer backends) if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove) g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos); if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize) g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size); if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize) g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size); viewport->LastPlatformPos = viewport->Pos; viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size; // Update title bar (if it changed) if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window)) { const char* title_begin = window_for_title->Name; char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin); const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin); if (viewport->LastNameHash != title_hash) { char title_end_backup_c = *title_end; *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain. g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin); *title_end = title_end_backup_c; viewport->LastNameHash = title_hash; } } // Update alpha (if it changed) if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha) g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha); viewport->LastAlpha = viewport->Alpha; // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed. if (g.PlatformIO.Platform_UpdateWindow) g.PlatformIO.Platform_UpdateWindow(viewport); if (is_new_platform_window) { // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late) if (g.FrameCount < 3) viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing; // Show window g.PlatformIO.Platform_ShowWindow(viewport); // Even without focus, we assume the window becomes front-most. // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available. if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount) viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount; } // Clear request flags viewport->ClearRequestFlags(); } // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport. // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored. // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab. if (g.PlatformIO.Platform_GetWindowFocus != NULL) { ImGuiViewportP* focused_viewport = NULL; for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++) { ImGuiViewportP* viewport = g.Viewports[n]; if (viewport->PlatformWindowCreated) if (g.PlatformIO.Platform_GetWindowFocus(viewport)) focused_viewport = viewport; } // Store a tag so we can infer z-order easily from all our windows if (focused_viewport && focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount) focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount; } } // This is a default/basic function for performing the rendering/swap of multiple Platform Windows. // Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves. // The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself: // // ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); // for (int i = 1; i < platform_io.Viewports.Size; i++) // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) // MyRenderFunction(platform_io.Viewports[i], my_args); // for (int i = 1; i < platform_io.Viewports.Size; i++) // if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0) // MySwapBufferFunction(platform_io.Viewports[i], my_args); // void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg) { // Skip the main viewport (index 0), which is always fully handled by the application! ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO(); for (int i = 1; i < platform_io.Viewports.Size; i++) { ImGuiViewport* viewport = platform_io.Viewports[i]; if (viewport->Flags & ImGuiViewportFlags_Minimized) continue; if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg); if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg); } for (int i = 1; i < platform_io.Viewports.Size; i++) { ImGuiViewport* viewport = platform_io.Viewports[i]; if (viewport->Flags & ImGuiViewportFlags_Minimized) continue; if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg); if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg); } } static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos) { ImGuiContext& g = *GImGui; for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++) { const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos)) return monitor_n; } return -1; } // Search for the monitor with the largest intersection area with the given rectangle // We generally try to avoid searching loops but the monitor count should be very small here // FIXME-OPT: We could test the last monitor used for that viewport first, and early static int ImGui::FindPlatformMonitorForRect(const ImRect& rect) { ImGuiContext& g = *GImGui; const int monitor_count = g.PlatformIO.Monitors.Size; if (monitor_count <= 1) return monitor_count - 1; // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position. // This is necessary for tooltips which always resize down to zero at first. const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f); int best_monitor_n = -1; float best_monitor_surface = 0.001f; for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++) { const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n]; const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize); if (monitor_rect.Contains(rect)) return monitor_n; ImRect overlapping_rect = rect; overlapping_rect.ClipWithFull(monitor_rect); float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight(); if (overlapping_surface < best_monitor_surface) continue; best_monitor_surface = overlapping_surface; best_monitor_n = monitor_n; } return best_monitor_n; } // Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor) static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport) { viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect()); } void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport) { ImGuiContext& g = *GImGui; if (viewport->PlatformWindowCreated) { if (g.PlatformIO.Renderer_DestroyWindow) g.PlatformIO.Renderer_DestroyWindow(viewport); if (g.PlatformIO.Platform_DestroyWindow) g.PlatformIO.Platform_DestroyWindow(viewport); IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL); // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize() // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public. if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID) viewport->PlatformWindowCreated = false; } else { IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL); } viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL; viewport->ClearRequestFlags(); } void ImGui::DestroyPlatformWindows() { // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling // code to operator a consistent manner. // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without // crashing if it doesn't have data stored. ImGuiContext& g = *GImGui; for (int i = 0; i < g.Viewports.Size; i++) DestroyPlatformWindow(g.Viewports[i]); } //----------------------------------------------------------------------------- // [SECTION] DOCKING //----------------------------------------------------------------------------- // Docking: Internal Types // Docking: Forward Declarations // Docking: ImGuiDockContext // Docking: ImGuiDockContext Docking/Undocking functions // Docking: ImGuiDockNode // Docking: ImGuiDockNode Tree manipulation functions // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) // Docking: Builder Functions // Docking: Begin/End Support Functions (called from Begin/End) // Docking: Settings //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Typical Docking call flow: (root level is generally public API): //----------------------------------------------------------------------------- // - NewFrame() new dear imgui frame // | DockContextNewFrameUpdateUndocking() - process queued undocking requests // | - DockContextProcessUndockWindow() - process one window undocking request // | - DockContextProcessUndockNode() - process one whole node undocking request // | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes // | - update g.HoveredDockNode - [debug] update node hovered by mouse // | - DockContextProcessDock() - process one docking request // | - DockNodeUpdate() // | - DockNodeUpdateForRootNode() // | - DockNodeUpdateVisibleFlagAndInactiveChilds() // | - DockNodeFindInfo() // | - destroy unused node or tab bar // | - create dock node host window // | - Begin() etc. // | - DockNodeStartMouseMovingWindow() // | - DockNodeTreeUpdatePosSize() // | - DockNodeTreeUpdateSplitter() // | - draw node background // | - DockNodeUpdateTabBar() - create/update tab bar for a docking node // | - DockNodeAddTabBar() // | - DockNodeUpdateWindowMenu() // | - DockNodeCalcTabBarLayout() // | - BeginTabBarEx() // | - TabItemEx() calls // | - EndTabBar() // | - BeginDockableDragDropTarget() // | - DockNodeUpdate() - recurse into child nodes... //----------------------------------------------------------------------------- // - DockSpace() user submit a dockspace into a window // | Begin(Child) - create a child window // | DockNodeUpdate() - call main dock node update function // | End(Child) // | ItemSize() //----------------------------------------------------------------------------- // - Begin() // | BeginDocked() // | BeginDockableDragDropSource() // | BeginDockableDragDropTarget() // | - DockNodePreviewDockRender() //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Docking: Internal Types //----------------------------------------------------------------------------- // - ImGuiDockRequestType // - ImGuiDockRequest // - ImGuiDockPreviewData // - ImGuiDockNodeSettings // - ImGuiDockContext //----------------------------------------------------------------------------- enum ImGuiDockRequestType { ImGuiDockRequestType_None = 0, ImGuiDockRequestType_Dock, ImGuiDockRequestType_Undock, ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload }; struct ImGuiDockRequest { ImGuiDockRequestType Type; ImGuiWindow* DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL) ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional] ImGuiDir DockSplitDir; float DockSplitRatio; bool DockSplitOuter; ImGuiWindow* UndockTargetWindow; ImGuiDockNode* UndockTargetNode; ImGuiDockRequest() { Type = ImGuiDockRequestType_None; DockTargetWindow = DockPayload = UndockTargetWindow = NULL; DockTargetNode = UndockTargetNode = NULL; DockSplitDir = ImGuiDir_None; DockSplitRatio = 0.5f; DockSplitOuter = false; } }; struct ImGuiDockPreviewData { ImGuiDockNode FutureNode; bool IsDropAllowed; bool IsCenterAvailable; bool IsSidesAvailable; // Hold your breath, grammar freaks.. bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window) ImGuiDockNode* SplitNode; ImGuiDir SplitDir; float SplitRatio; ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); } }; // Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes) struct ImGuiDockNodeSettings { ImGuiID ID; ImGuiID ParentNodeId; ImGuiID ParentWindowId; ImGuiID SelectedWindowId; signed char SplitAxis; char Depth; ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_) ImVec2ih Pos; ImVec2ih Size; ImVec2ih SizeRef; ImGuiDockNodeSettings() { ID = ParentNodeId = ParentWindowId = SelectedWindowId = 0; SplitAxis = ImGuiAxis_None; Depth = 0; Flags = ImGuiDockNodeFlags_None; } }; //----------------------------------------------------------------------------- // Docking: Forward Declarations //----------------------------------------------------------------------------- namespace ImGui { // ImGuiDockContext static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id); static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node); static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node); static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req); static void DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true); static void DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node); static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx); static ImGuiDockNode* DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id); static ImGuiDockNode* DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window); static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count); static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all // ImGuiDockNode static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar); static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node); static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node); static ImGuiWindow* DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id); static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node); static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id); static void DockNodeHideHostWindow(ImGuiDockNode* node); static void DockNodeUpdate(ImGuiDockNode* node); static void DockNodeUpdateForRootNode(ImGuiDockNode* node); static void DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node); static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window); static void DockNodeAddTabBar(ImGuiDockNode* node); static void DockNodeRemoveTabBar(ImGuiDockNode* node); static ImGuiID DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar); static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node); static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window); static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window); static void DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking); static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data); static void DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos); static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired); static bool DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos); static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; } static int DockNodeGetTabOrder(ImGuiWindow* window); // ImGuiDockNode tree manipulations static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node); static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child); static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes = false); static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node); static ImGuiDockNode* DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos); static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node); // Settings static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id); static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count); static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id); static void DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*); static void DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*); static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); } //----------------------------------------------------------------------------- // Docking: ImGuiDockContext //----------------------------------------------------------------------------- // The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings, // or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active. // At boot time only, we run a simple GC to remove nodes that have no references. // Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures), // we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does). // This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data. //----------------------------------------------------------------------------- // - DockContextInitialize() // - DockContextShutdown() // - DockContextClearNodes() // - DockContextRebuildNodes() // - DockContextNewFrameUpdateUndocking() // - DockContextNewFrameUpdateDocking() // - DockContextFindNodeByID() // - DockContextBindNodeToWindow() // - DockContextGenNodeID() // - DockContextAddNode() // - DockContextRemoveNode() // - ImGuiDockContextPruneNodeData // - DockContextPruneUnusedSettingsNodes() // - DockContextBuildNodesFromSettings() // - DockContextBuildAddWindowsToNodes() //----------------------------------------------------------------------------- void ImGui::DockContextInitialize(ImGuiContext* ctx) { ImGuiContext& g = *ctx; // Add .ini handle for persistent docking data ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Docking"; ini_handler.TypeHash = ImHashStr("Docking"); ini_handler.ClearAllFn = DockSettingsHandler_ClearAll; ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen; ini_handler.ReadLineFn = DockSettingsHandler_ReadLine; ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll; ini_handler.WriteAllFn = DockSettingsHandler_WriteAll; g.SettingsHandlers.push_back(ini_handler); } void ImGui::DockContextShutdown(ImGuiContext* ctx) { ImGuiDockContext* dc = &ctx->DockContext; for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) IM_DELETE(node); } void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs) { IM_UNUSED(ctx); IM_ASSERT(ctx == GImGui); DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs); DockBuilderRemoveNodeChildNodes(root_id); } // [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch // (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) void ImGui::DockContextRebuildNodes(ImGuiContext* ctx) { IMGUI_DEBUG_LOG_DOCKING("DockContextRebuild()\n"); ImGuiDockContext* dc = &ctx->DockContext; SaveIniSettingsToMemory(); ImGuiID root_id = 0; // Rebuild all DockContextClearNodes(ctx, root_id, false); DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); DockContextBuildAddWindowsToNodes(ctx, root_id); } // Docking context update function, called by NewFrame() void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx) { ImGuiContext& g = *ctx; ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) { if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0) DockContextClearNodes(ctx, 0, true); return; } // Setting NoSplit at runtime merges all nodes if (g.IO.ConfigDockingNoSplit) for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (node->IsRootNode() && node->IsSplitNode()) { DockBuilderRemoveNodeChildNodes(node->ID); //dc->WantFullRebuild = true; } // Process full rebuild #if 0 if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C))) dc->WantFullRebuild = true; #endif if (dc->WantFullRebuild) { DockContextRebuildNodes(ctx); dc->WantFullRebuild = false; } // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame) for (int n = 0; n < dc->Requests.Size; n++) { ImGuiDockRequest* req = &dc->Requests[n]; if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow) DockContextProcessUndockWindow(ctx, req->UndockTargetWindow); else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode) DockContextProcessUndockNode(ctx, req->UndockTargetNode); } } // Docking context update function, called by NewFrame() void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx) { ImGuiContext& g = *ctx; ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; // [DEBUG] Store hovered dock node. // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut. // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering. g.HoveredDockNode = NULL; if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow) { if (hovered_window->DockNodeAsHost) g.HoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos); else if (hovered_window->RootWindowDockStop->DockNode) g.HoveredDockNode = hovered_window->RootWindowDockStop->DockNode; } // Process Docking requests for (int n = 0; n < dc->Requests.Size; n++) if (dc->Requests[n].Type == ImGuiDockRequestType_Dock) DockContextProcessDock(ctx, &dc->Requests[n]); dc->Requests.resize(0); // Create windows for each automatic docking nodes // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high) for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (node->IsFloatingNode()) DockNodeUpdate(node); } static ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id) { return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id); } ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx) { // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used) // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry. We should poke in ctx->Nodes to find a suitable ID faster. ImGuiID id = 0x0001; while (DockContextFindNodeByID(ctx, id) != NULL) id++; return id; } static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id) { // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window. if (id == 0) id = DockContextGenNodeID(ctx); else IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL); // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! IMGUI_DEBUG_LOG_DOCKING("DockContextAddNode 0x%08X\n", id); ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id); ctx->DockContext.Nodes.SetVoidPtr(node->ID, node); return node; } static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node) { ImGuiContext& g = *ctx; ImGuiDockContext* dc = &ctx->DockContext; IMGUI_DEBUG_LOG_DOCKING("DockContextRemoveNode 0x%08X\n", node->ID); IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node); IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL); IM_ASSERT(node->Windows.Size == 0); if (node->HostWindow) node->HostWindow->DockNodeAsHost = NULL; ImGuiDockNode* parent_node = node->ParentNode; const bool merge = (merge_sibling_into_parent_node && parent_node != NULL); if (merge) { IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node); ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]); DockNodeTreeMerge(&g, parent_node, sibling_node); } else { for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++) if (parent_node->ChildNodes[n] == node) node->ParentNode->ChildNodes[n] = NULL; dc->Nodes.SetVoidPtr(node->ID, NULL); IM_DELETE(node); } } static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs) { const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs; const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs; return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a); } // Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here. struct ImGuiDockContextPruneNodeData { int CountWindows, CountChildWindows, CountChildNodes; ImGuiID RootId; ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; } }; // Garbage collect unused nodes (run once at init time) static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx) { ImGuiContext& g = *ctx; ImGuiDockContext* dc = &ctx->DockContext; IM_ASSERT(g.Windows.Size == 0); ImPool<ImGuiDockContextPruneNodeData> pool; pool.Reserve(dc->NodesSettings.Size); // Count child nodes and compute RootID for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0; pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID; if (settings->ParentNodeId) pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++; } // Count reference to dock ids from dockspaces // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; if (settings->ParentWindowId != 0) if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->ParentWindowId)) if (window_settings->DockId) if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId)) data->CountChildNodes++; } // Count reference to dock ids from window settings // We guard against the possibility of an invalid .ini file (RootID may point to a missing node) for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) if (ImGuiID dock_id = settings->DockId) if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id)) { data->CountWindows++; if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId)) data_root->CountChildWindows++; } // Prune for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++) { ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n]; ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID); if (data->CountWindows > 1) continue; ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId); bool remove = false; remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode)); // Floating root node with only 1 window remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window remove |= (data_root->CountChildWindows == 0); if (remove) { IMGUI_DEBUG_LOG_DOCKING("DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID); DockSettingsRemoveNodeReferences(&settings->ID, 1); settings->ID = 0; } } } static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count) { // Build nodes for (int node_n = 0; node_n < node_settings_count; node_n++) { ImGuiDockNodeSettings* settings = &node_settings_array[node_n]; if (settings->ID == 0) continue; ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID); node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL; node->Pos = ImVec2(settings->Pos.x, settings->Pos.y); node->Size = ImVec2(settings->Size.x, settings->Size.y); node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y); node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode; if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL) node->ParentNode->ChildNodes[0] = node; else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL) node->ParentNode->ChildNodes[1] = node; node->SelectedTabId = settings->SelectedWindowId; node->SplitAxis = (ImGuiAxis)settings->SplitAxis; node->LocalFlags |= (settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_); // Bind host window immediately if it already exist (in case of a rebuild) // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set. char host_window_title[20]; ImGuiDockNode* root_node = DockNodeGetRootNode(node); node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title))); } } void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id) { // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame) ImGuiContext& g = *ctx; for (int n = 0; n < g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1) continue; if (window->DockNode != NULL) continue; ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId); IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings() if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id) DockNodeAddWindow(node, window, true); } } //----------------------------------------------------------------------------- // Docking: ImGuiDockContext Docking/Undocking functions //----------------------------------------------------------------------------- // - DockContextQueueDock() // - DockContextQueueUndockWindow() // - DockContextQueueUndockNode() // - DockContextQueueNotifyRemovedNode() // - DockContextProcessDock() // - DockContextProcessUndockWindow() // - DockContextProcessUndockNode() // - DockContextCalcDropPosForDocking() //----------------------------------------------------------------------------- void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer) { IM_ASSERT(target != payload); ImGuiDockRequest req; req.Type = ImGuiDockRequestType_Dock; req.DockTargetWindow = target; req.DockTargetNode = target_node; req.DockPayload = payload; req.DockSplitDir = split_dir; req.DockSplitRatio = split_ratio; req.DockSplitOuter = split_outer; ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window) { ImGuiDockRequest req; req.Type = ImGuiDockRequestType_Undock; req.UndockTargetWindow = window; ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) { ImGuiDockRequest req; req.Type = ImGuiDockRequestType_Undock; req.UndockTargetNode = node; ctx->DockContext.Requests.push_back(req); } void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node) { ImGuiDockContext* dc = &ctx->DockContext; for (int n = 0; n < dc->Requests.Size; n++) if (dc->Requests[n].DockTargetNode == node) dc->Requests[n].Type = ImGuiDockRequestType_None; } void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req) { IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL)); IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL); ImGuiContext& g = *ctx; IM_UNUSED(g); ImGuiWindow* payload_window = req->DockPayload; // Optional ImGuiWindow* target_window = req->DockTargetWindow; ImGuiDockNode* node = req->DockTargetNode; if (payload_window) IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window ? payload_window->Name : "NULL", req->DockSplitDir); else IMGUI_DEBUG_LOG_DOCKING("DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir); // Decide which Tab will be selected at the end of the operation ImGuiID next_selected_id = 0; ImGuiDockNode* payload_node = NULL; if (payload_window) { payload_node = payload_window->DockNodeAsHost; payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later. if (payload_node && payload_node->IsLeafNode()) next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId; if (payload_node == NULL) next_selected_id = payload_window->ID; } // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. if (node) IM_ASSERT(node->LastFrameAlive <= g.FrameCount); if (node && target_window && node == target_window->DockNodeAsHost) IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode()); // Create new node and add existing window to it if (node == NULL) { node = DockContextAddNode(ctx, 0); node->Pos = target_window->Pos; node->Size = target_window->Size; if (target_window->DockNodeAsHost == NULL) { DockNodeAddWindow(node, target_window, true); node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted; target_window->DockIsActive = true; } } ImGuiDir split_dir = req->DockSplitDir; if (split_dir != ImGuiDir_None) { // Split into one, one side will be our payload node unless we are dropping a loose window const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side const float split_ratio = req->DockSplitRatio; DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here! ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1]; new_node->HostWindow = node->HostWindow; node = new_node; } node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar; if (node != payload_node) { // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) if (node->Windows.Size > 0 && node->TabBar == NULL) { DockNodeAddTabBar(node); for (int n = 0; n < node->Windows.Size; n++) TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); } if (payload_node != NULL) { // Transfer full payload node (with 1+ child windows or child nodes) if (payload_node->IsSplitNode()) { if (node->Windows.Size > 0) { // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. // In this situation, we move the windows of the target node into the currently visible node of the payload. // This allows us to preserve some of the underlying dock tree settings nicely. IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted. ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows; if (visible_node->TabBar) IM_ASSERT(visible_node->TabBar->Tabs.Size > 0); DockNodeMoveWindows(node, visible_node); DockNodeMoveWindows(visible_node, node); DockSettingsRenameNodeReferences(node->ID, visible_node->ID); } if (node->IsCentralNode()) { // Central node property needs to be moved to a leaf node, pick the last focused one. // FIXME-DOCK: If we had to transfer other flags here, what would the policy be? ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId); IM_ASSERT(last_focused_node != NULL); ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node); IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node)); last_focused_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; node->LocalFlags &= ~ImGuiDockNodeFlags_CentralNode; last_focused_root_node->CentralNode = last_focused_node; } IM_ASSERT(node->Windows.Size == 0); DockNodeMoveChildNodes(node, payload_node); } else { const ImGuiID payload_dock_id = payload_node->ID; DockNodeMoveWindows(node, payload_node); DockSettingsRenameNodeReferences(payload_dock_id, node->ID); } DockContextRemoveNode(ctx, payload_node, true); } else if (payload_window) { // Transfer single window const ImGuiID payload_dock_id = payload_window->DockId; node->VisibleWindow = payload_window; DockNodeAddWindow(node, payload_window, true); if (payload_dock_id != 0) DockSettingsRenameNodeReferences(payload_dock_id, node->ID); } } else { // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar node->WantHiddenTabBarUpdate = true; } // Update selection immediately if (ImGuiTabBar* tab_bar = node->TabBar) tab_bar->NextSelectedTabId = next_selected_id; MarkIniSettingsDirty(); } void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref) { IMGUI_DEBUG_LOG_DOCKING("DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref); IM_UNUSED(ctx); if (window->DockNode) DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId); else window->DockId = 0; window->Collapsed = false; window->DockIsActive = false; window->DockTabIsVisible = false; MarkIniSettingsDirty(); } void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node) { IMGUI_DEBUG_LOG_DOCKING("DockContextProcessUndockNode node %08X\n", node->ID); IM_ASSERT(node->IsLeafNode()); IM_ASSERT(node->Windows.Size >= 1); if (node->IsRootNode() || node->IsCentralNode()) { // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload. ImGuiDockNode* new_node = DockContextAddNode(ctx, 0); DockNodeMoveWindows(new_node, node); DockSettingsRenameNodeReferences(node->ID, new_node->ID); for (int n = 0; n < new_node->Windows.Size; n++) UpdateWindowParentAndRootLinks(new_node->Windows[n], new_node->Windows[n]->Flags, NULL); node = new_node; } else { // Otherwise extract our node and merging our sibling back into the parent node. IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1; node->ParentNode->ChildNodes[index_in_parent] = NULL; DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]); node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport node->ParentNode = NULL; } node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_Window; node->WantMouseMove = true; MarkIniSettingsDirty(); } // This is mostly used for automation. bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos) { if (split_outer) { IM_ASSERT(0); } else { ImGuiDockPreviewData split_data; DockNodePreviewDockSetup(target, target_node, payload, &split_data, false, split_outer); if (split_data.DropRectsDraw[split_dir+1].IsInverted()) return false; *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter(); return true; } return false; } //----------------------------------------------------------------------------- // Docking: ImGuiDockNode //----------------------------------------------------------------------------- // - DockNodeGetTabOrder() // - DockNodeAddWindow() // - DockNodeRemoveWindow() // - DockNodeMoveChildNodes() // - DockNodeMoveWindows() // - DockNodeApplyPosSizeToWindows() // - DockNodeHideHostWindow() // - ImGuiDockNodeFindInfoResults // - DockNodeFindInfo() // - DockNodeFindWindowByID() // - DockNodeUpdateVisibleFlagAndInactiveChilds() // - DockNodeUpdateVisibleFlag() // - DockNodeStartMouseMovingWindow() // - DockNodeUpdate() // - DockNodeUpdateWindowMenu() // - DockNodeBeginAmendTabBar() // - DockNodeEndAmendTabBar() // - DockNodeUpdateTabBar() // - DockNodeAddTabBar() // - DockNodeRemoveTabBar() // - DockNodeIsDropAllowedOne() // - DockNodeIsDropAllowed() // - DockNodeCalcTabBarLayout() // - DockNodeCalcSplitRects() // - DockNodeCalcDropRectsAndTestMousePos() // - DockNodePreviewDockSetup() // - DockNodePreviewDockRender() //----------------------------------------------------------------------------- ImGuiDockNode::ImGuiDockNode(ImGuiID id) { ID = id; SharedFlags = LocalFlags = ImGuiDockNodeFlags_None; ParentNode = ChildNodes[0] = ChildNodes[1] = NULL; TabBar = NULL; SplitAxis = ImGuiAxis_None; State = ImGuiDockNodeState_Unknown; HostWindow = VisibleWindow = NULL; CentralNode = OnlyNodeWithWindows = NULL; LastFrameAlive = LastFrameActive = LastFrameFocused = -1; LastFocusedNodeId = 0; SelectedTabId = 0; WantCloseTabId = 0; AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode; AuthorityForViewport = ImGuiDataAuthority_Auto; IsVisible = true; IsFocused = HasCloseButton = HasWindowMenuButton = EnableCloseButton = false; WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false; MarkedForPosSizeWrite = false; } ImGuiDockNode::~ImGuiDockNode() { IM_DELETE(TabBar); TabBar = NULL; ChildNodes[0] = ChildNodes[1] = NULL; } int ImGui::DockNodeGetTabOrder(ImGuiWindow* window) { ImGuiTabBar* tab_bar = window->DockNode->TabBar; if (tab_bar == NULL) return -1; ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->ID); return tab ? tab_bar->GetTabOrder(tab) : -1; } static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar) { ImGuiContext& g = *GImGui; (void)g; if (window->DockNode) { // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node) IM_ASSERT(window->DockNode->ID != node->ID); DockNodeRemoveWindow(window->DockNode, window, 0); } IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); IMGUI_DEBUG_LOG_DOCKING("DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name); node->Windows.push_back(window); node->WantHiddenTabBarUpdate = true; window->DockNode = node; window->DockId = node->ID; window->DockIsActive = (node->Windows.Size > 1); window->DockTabWantClose = false; // If more than 2 windows appeared on the same frame, we'll create a new hosting DockNode from the point of the second window submission. // Then we need to hide the first window (after its been output) otherwise it would be visible as a standalone window for one frame. if (node->HostWindow == NULL && node->Windows.Size == 2 && node->Windows[0]->WasActive == false) { node->Windows[0]->Hidden = true; node->Windows[0]->HiddenFramesCanSkipItems = 1; } // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage. // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. if (node->HostWindow == NULL && node->IsFloatingNode()) { if (node->AuthorityForPos == ImGuiDataAuthority_Auto) node->AuthorityForPos = ImGuiDataAuthority_Window; if (node->AuthorityForSize == ImGuiDataAuthority_Auto) node->AuthorityForSize = ImGuiDataAuthority_Window; if (node->AuthorityForViewport == ImGuiDataAuthority_Auto) node->AuthorityForViewport = ImGuiDataAuthority_Window; } // Add to tab bar if requested if (add_to_tab_bar) { if (node->TabBar == NULL) { DockNodeAddTabBar(node); node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId; // Add existing windows for (int n = 0; n < node->Windows.Size - 1; n++) TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]); } TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window); } DockNodeUpdateVisibleFlag(node); // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame. if (node->HostWindow) UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow); } static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id) { ImGuiContext& g = *GImGui; IM_ASSERT(window->DockNode == node); //IM_ASSERT(window->RootWindow == node->HostWindow); //IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin() IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID); IMGUI_DEBUG_LOG_DOCKING("DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name); window->DockNode = NULL; window->DockIsActive = window->DockTabWantClose = false; window->DockId = save_dock_id; UpdateWindowParentAndRootLinks(window, window->Flags & ~ImGuiWindowFlags_ChildWindow, NULL); // Update immediately // Remove window bool erased = false; for (int n = 0; n < node->Windows.Size; n++) if (node->Windows[n] == window) { node->Windows.erase(node->Windows.Data + n); erased = true; break; } IM_ASSERT(erased); if (node->VisibleWindow == window) node->VisibleWindow = NULL; // Remove tab and possibly tab bar node->WantHiddenTabBarUpdate = true; if (node->TabBar) { TabBarRemoveTab(node->TabBar, window->ID); const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2; if (node->Windows.Size < tab_count_threshold_for_tab_bar) DockNodeRemoveTabBar(node); } if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID) { // Automatic dock node delete themselves if they are not holding at least one tab DockContextRemoveNode(&g, node, true); return; } if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow) { ImGuiWindow* remaining_window = node->Windows[0]; if (node->HostWindow->ViewportOwned && node->IsRootNode()) { // Transfer viewport back to the remaining loose window IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow); node->HostWindow->Viewport->Window = remaining_window; node->HostWindow->Viewport->ID = remaining_window->ID; } remaining_window->Collapsed = node->HostWindow->Collapsed; } // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree DockNodeUpdateVisibleFlag(node); } static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node) { IM_ASSERT(dst_node->Windows.Size == 0); dst_node->ChildNodes[0] = src_node->ChildNodes[0]; dst_node->ChildNodes[1] = src_node->ChildNodes[1]; if (dst_node->ChildNodes[0]) dst_node->ChildNodes[0]->ParentNode = dst_node; if (dst_node->ChildNodes[1]) dst_node->ChildNodes[1]->ParentNode = dst_node; dst_node->SplitAxis = src_node->SplitAxis; dst_node->SizeRef = src_node->SizeRef; src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL; } static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node) { // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered) IM_ASSERT(src_node && dst_node && dst_node != src_node); ImGuiTabBar* src_tab_bar = src_node->TabBar; if (src_tab_bar != NULL) IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size); // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.) bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL); if (move_tab_bar) { dst_node->TabBar = src_node->TabBar; src_node->TabBar = NULL; } for (int n = 0; n < src_node->Windows.Size; n++) { // DockNode's TabBar may have non-window Tabs manually appended by user if (ImGuiWindow* window = src_tab_bar ? src_tab_bar->Tabs[n].Window : src_node->Windows[n]) { window->DockNode = NULL; window->DockIsActive = false; DockNodeAddWindow(dst_node, window, move_tab_bar ? false : true); } } src_node->Windows.clear(); if (!move_tab_bar && src_node->TabBar) { if (dst_node->TabBar) dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId; DockNodeRemoveTabBar(src_node); } } static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node) { for (int n = 0; n < node->Windows.Size; n++) { SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always); } } static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node) { if (node->HostWindow) { if (node->HostWindow->DockNodeAsHost == node) node->HostWindow->DockNodeAsHost = NULL; node->HostWindow = NULL; } if (node->Windows.Size == 1) { node->VisibleWindow = node->Windows[0]; node->Windows[0]->DockIsActive = false; } if (node->TabBar) DockNodeRemoveTabBar(node); } // Search function called once by root node in DockNodeUpdate() struct ImGuiDockNodeFindInfoResults { ImGuiDockNode* CentralNode; ImGuiDockNode* FirstNodeWithWindows; int CountNodesWithWindows; //ImGuiWindowClass WindowClassForMerges; ImGuiDockNodeFindInfoResults() { CentralNode = FirstNodeWithWindows = NULL; CountNodesWithWindows = 0; } }; static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeFindInfoResults* results) { if (node->Windows.Size > 0) { if (results->FirstNodeWithWindows == NULL) results->FirstNodeWithWindows = node; results->CountNodesWithWindows++; } if (node->IsCentralNode()) { IM_ASSERT(results->CentralNode == NULL); // Should be only one IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this."); results->CentralNode = node; } if (results->CountNodesWithWindows > 1 && results->CentralNode != NULL) return; if (node->ChildNodes[0]) DockNodeFindInfo(node->ChildNodes[0], results); if (node->ChildNodes[1]) DockNodeFindInfo(node->ChildNodes[1], results); } static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id) { IM_ASSERT(id != 0); for (int n = 0; n < node->Windows.Size; n++) if (node->Windows[n]->ID == id) return node->Windows[n]; return NULL; } // - Remove inactive windows/nodes. // - Update visibility flag. static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node) { ImGuiContext& g = *GImGui; IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node); // Inherit most flags if (node->ParentNode) node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; // Recurse into children // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'. // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node' // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless) if (node->ChildNodes[0]) DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[0]); if (node->ChildNodes[1]) DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[1]); // Remove inactive windows // Merge node flags overrides stored in windows for (int window_n = 0; window_n < node->Windows.Size; window_n++) { ImGuiWindow* window = node->Windows[window_n]; IM_ASSERT(window->DockNode == node); bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount); bool remove = false; remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount); remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame remove |= (window->DockTabWantClose); if (remove) { window->DockTabWantClose = false; if (node->Windows.Size == 1 && !node->IsCentralNode()) { DockNodeHideHostWindow(node); node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return return; } DockNodeRemoveWindow(node, window, node->ID); window_n--; } else { node->LocalFlags &= ~window->WindowClass.DockNodeFlagsOverrideClear; node->LocalFlags |= window->WindowClass.DockNodeFlagsOverrideSet; } } // Auto-hide tab bar option ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar()) node->WantHiddenTabBarToggle = true; node->WantHiddenTabBarUpdate = false; // Cancel toggling if we know our tab bar is enforced to be hidden at all times if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar)) node->WantHiddenTabBarToggle = false; // Apply toggles at a single point of the frame (here!) if (node->Windows.Size > 1) node->LocalFlags &= ~ImGuiDockNodeFlags_HiddenTabBar; else if (node->WantHiddenTabBarToggle) node->LocalFlags ^= ImGuiDockNodeFlags_HiddenTabBar; node->WantHiddenTabBarToggle = false; DockNodeUpdateVisibleFlag(node); } static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node) { // Update visibility flag bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode(); is_visible |= (node->Windows.Size > 0); is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible); is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible); node->IsVisible = is_visible; } static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window) { ImGuiContext& g = *GImGui; IM_ASSERT(node->WantMouseMove == true); StartMouseMovingWindow(window); g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos; g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. node->WantMouseMove = false; } // Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node) { DockNodeUpdateVisibleFlagAndInactiveChilds(node); // FIXME-DOCK: Merge this scan into the one above. // - Setup central node pointers // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!) ImGuiDockNodeFindInfoResults results; DockNodeFindInfo(node, &results); node->CentralNode = results.CentralNode; node->OnlyNodeWithWindows = (results.CountNodesWithWindows == 1) ? results.FirstNodeWithWindows : NULL; if (node->LastFocusedNodeId == 0 && results.FirstNodeWithWindows != NULL) node->LastFocusedNodeId = results.FirstNodeWithWindows->ID; // Copy the window class from of our first window so it can be used for proper dock filtering. // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy. // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec. if (ImGuiDockNode* first_node_with_windows = results.FirstNodeWithWindows) { node->WindowClass = first_node_with_windows->Windows[0]->WindowClass; for (int n = 1; n < first_node_with_windows->Windows.Size; n++) if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false) { node->WindowClass = first_node_with_windows->Windows[n]->WindowClass; break; } } } static void ImGui::DockNodeUpdate(ImGuiDockNode* node) { ImGuiContext& g = *GImGui; IM_ASSERT(node->LastFrameActive != g.FrameCount); node->LastFrameAlive = g.FrameCount; node->MarkedForPosSizeWrite = false; node->CentralNode = node->OnlyNodeWithWindows = NULL; if (node->IsRootNode()) DockNodeUpdateForRootNode(node); // Remove tab bar if not needed if (node->TabBar && node->IsNoTabBar()) DockNodeRemoveTabBar(node); // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) bool want_to_hide_host_window = false; if (node->Windows.Size <= 1 && node->IsFloatingNode() && node->IsLeafNode()) if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar)) want_to_hide_host_window = true; if (want_to_hide_host_window) { if (node->Windows.Size == 1) { // Floating window pos/size is authoritative ImGuiWindow* single_window = node->Windows[0]; node->Pos = single_window->Pos; node->Size = single_window->SizeFull; node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; // Transfer focus immediately so when we revert to a regular window it is immediately selected if (node->HostWindow && g.NavWindow == node->HostWindow) FocusWindow(single_window); if (node->HostWindow) { single_window->Viewport = node->HostWindow->Viewport; single_window->ViewportId = node->HostWindow->ViewportId; if (node->HostWindow->ViewportOwned) { single_window->Viewport->Window = single_window; single_window->ViewportOwned = true; } } } DockNodeHideHostWindow(node); node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow; node->WantCloseAll = false; node->WantCloseTabId = 0; node->HasCloseButton = node->HasWindowMenuButton = node->EnableCloseButton = false; node->LastFrameActive = g.FrameCount; if (node->WantMouseMove && node->Windows.Size == 1) DockNodeStartMouseMovingWindow(node, node->Windows[0]); return; } // In some circumstance we will defer creating the host window (so everything will be kept hidden), // while the expected visible window is resizing itself. // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled, // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up: // N+0: Begin(): window created (with no known size), node is created // N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible // N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code. // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin(). // In reality it isn't very important as user quickly ends up with size data in .ini file. if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode()) { IM_ASSERT(node->Windows.Size > 0); ImGuiWindow* ref_window = NULL; if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them! ref_window = DockNodeFindWindowByID(node, node->SelectedTabId); if (ref_window == NULL) ref_window = node->Windows[0]; if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0) { node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing; return; } } const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); // Bind or create host window ImGuiWindow* host_window = NULL; bool beginned_into_host_window = false; if (node->IsDockSpace()) { // [Explicit root dockspace node] IM_ASSERT(node->HostWindow); node->EnableCloseButton = false; node->HasCloseButton = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0; node->HasWindowMenuButton = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; host_window = node->HostWindow; } else { // [Automatic root or child nodes] node->EnableCloseButton = false; node->HasCloseButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0; node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0; for (int window_n = 0; window_n < node->Windows.Size; window_n++) { // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call. ImGuiWindow* window = node->Windows[window_n]; window->DockIsActive = (node->Windows.Size > 1); node->EnableCloseButton |= window->HasCloseButton; } if (node->IsRootNode() && node->IsVisible) { ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL; // Sync Pos if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window) SetNextWindowPos(ref_window->Pos); else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode) SetNextWindowPos(node->Pos); // Sync Size if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) SetNextWindowSize(ref_window->SizeFull); else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode) SetNextWindowSize(node->Size); // Sync Collapsed if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window) SetNextWindowCollapsed(ref_window->Collapsed); // Sync Viewport if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window) SetNextWindowViewport(ref_window->ViewportId); SetNextWindowClass(&node->WindowClass); // Begin into the host window char window_label[20]; DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label)); ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost; window_flags |= ImGuiWindowFlags_NoFocusOnAppearing; window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse; window_flags |= ImGuiWindowFlags_NoTitleBar; PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); Begin(window_label, NULL, window_flags); PopStyleVar(); beginned_into_host_window = true; node->HostWindow = host_window = g.CurrentWindow; host_window->DockNodeAsHost = node; host_window->DC.CursorPos = host_window->Pos; node->Pos = host_window->Pos; node->Size = host_window->Size; // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow) // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags. // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again. // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back // after the dock host window, losing their top-most status. if (node->HostWindow->Appearing) BringWindowToDisplayFront(node->HostWindow); node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; } else if (node->ParentNode) { node->HostWindow = host_window = node->ParentNode->HostWindow; node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto; } if (node->WantMouseMove && node->HostWindow) DockNodeStartMouseMovingWindow(node, node->HostWindow); } // Update focused node (the one whose title bar is highlight) within a node tree if (node->IsSplitNode()) IM_ASSERT(node->TabBar == NULL); if (node->IsRootNode()) if (g.NavWindow && g.NavWindow->RootWindowDockStop->DockNode && g.NavWindow->RootWindowDockStop->ParentWindow == host_window) node->LastFocusedNodeId = g.NavWindow->RootWindowDockStop->DockNode->ID; // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0; if (render_dockspace_bg) { host_window->DrawList->ChannelsSplit(2); host_window->DrawList->ChannelsSetCurrent(1); } // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace const ImGuiDockNode* central_node = node->CentralNode; const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty(); bool central_node_hole_register_hit_test_hole = central_node_hole; if (central_node_hole) if (const ImGuiPayload* payload = ImGui::GetDragDropPayload()) if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data)) central_node_hole_register_hit_test_hole = false; if (central_node_hole_register_hit_test_hole) { // Add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily. IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode ImRect central_hole(central_node->Pos, central_node->Pos + central_node->Size); central_hole.Expand(ImVec2(-WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, -WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)); if (central_node_hole && !central_hole.IsInverted()) { SetWindowHitTestHole(host_window, central_hole.Min, central_hole.Max - central_hole.Min); SetWindowHitTestHole(host_window->ParentWindow, central_hole.Min, central_hole.Max - central_hole.Min); } } // Update position/size, process and draw resizing splitters if (node->IsRootNode() && host_window) { DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size); DockNodeTreeUpdateSplitter(node); } // Draw empty node background (currently can only be the Central Node) if (host_window && node->IsEmpty() && node->IsVisible && !(node_flags & ImGuiDockNodeFlags_PassthruCentralNode)) host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_DockingEmptyBg)); // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set. if (render_dockspace_bg && node->IsVisible) { host_window->DrawList->ChannelsSetCurrent(0); if (central_node_hole) RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f); else host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f); host_window->DrawList->ChannelsMerge(); } // Draw and populate Tab Bar if (host_window && node->Windows.Size > 0) { DockNodeUpdateTabBar(node, host_window); } else { node->WantCloseAll = false; node->WantCloseTabId = 0; node->IsFocused = false; } if (node->TabBar && node->TabBar->SelectedTabId) node->SelectedTabId = node->TabBar->SelectedTabId; else if (node->Windows.Size > 0) node->SelectedTabId = node->Windows[0]->ID; // Draw payload drop target if (host_window && node->IsVisible) if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindow != host_window)) BeginDockableDragDropTarget(host_window); // We update this after DockNodeUpdateTabBar() node->LastFrameActive = g.FrameCount; // Recurse into children // FIXME-DOCK FIXME-OPT: Should not need to recurse into children if (host_window) { if (node->ChildNodes[0]) DockNodeUpdate(node->ChildNodes[0]); if (node->ChildNodes[1]) DockNodeUpdate(node->ChildNodes[1]); // Render outer borders last (after the tab bar) if (node->IsRootNode()) RenderWindowOuterBorders(host_window); } // End host window if (beginned_into_host_window) //-V1020 End(); } // Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame. static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs) { ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window; ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window; if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder)) return d; return (a->BeginOrderWithinContext - b->BeginOrderWithinContext); } static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar) { // Try to position the menu so it is more likely to stays within the same viewport ImGuiContext& g = *GImGui; ImGuiID ret_tab_id = 0; if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left) SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f)); else SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f)); if (BeginPopup("#WindowMenu")) { node->IsFocused = true; if (tab_bar->Tabs.Size == 1) { if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar())) node->WantHiddenTabBarToggle = true; } else { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; if (tab->Flags & ImGuiTabItemFlags_Button) continue; if (Selectable(tab_bar->GetTabName(tab), tab->ID == tab_bar->SelectedTabId)) ret_tab_id = tab->ID; SameLine(); Text(" "); } } EndPopup(); } return ret_tab_id; } // User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button. bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node) { if (node->TabBar == NULL || node->HostWindow == NULL) return false; if (node->SharedFlags & ImGuiDockNodeFlags_KeepAliveOnly) return false; Begin(node->HostWindow->Name); PushOverrideID(node->ID); bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node); IM_ASSERT(ret); IM_UNUSED(ret); return true; } void ImGui::DockNodeEndAmendTabBar() { EndTabBar(); PopID(); End(); } // Submit the tab bar corresponding to a dock node and various housekeeping details. static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount); const bool closed_all = node->WantCloseAll && node_was_active; const ImGuiID closed_one = node->WantCloseTabId && node_was_active; node->WantCloseAll = false; node->WantCloseTabId = 0; // Decide if we should use a focused title bar color bool is_focused = false; ImGuiDockNode* root_node = DockNodeGetRootNode(node); if (g.NavWindowingTarget) is_focused = (g.NavWindowingTarget->DockNode == node); else if (g.NavWindow && g.NavWindow->RootWindowForTitleBarHighlight == host_window->RootWindow && root_node->LastFocusedNodeId == node->ID) is_focused = true; // Hidden tab bar will show a triangle on the upper-left (in Begin) if (node->IsHiddenTabBar() || node->IsNoTabBar()) { node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL; node->IsFocused = is_focused; if (is_focused) node->LastFrameFocused = g.FrameCount; if (node->VisibleWindow) { // Notify root of visible window (used to display title in OS task bar) if (is_focused || root_node->VisibleWindow == NULL) root_node->VisibleWindow = node->VisibleWindow; if (node->TabBar) node->TabBar->VisibleTabId = node->VisibleWindow->ID; } return; } // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed bool backup_skip_item = host_window->SkipItems; if (!node->IsDockSpace()) { host_window->SkipItems = false; host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; } // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID. // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs, // as docked windows themselves will override the stack with their own root ID. PushOverrideID(node->ID); ImGuiTabBar* tab_bar = node->TabBar; bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden if (tab_bar == NULL) { DockNodeAddTabBar(node); tab_bar = node->TabBar; } ImGuiID focus_tab_id = 0; node->IsFocused = is_focused; const ImGuiDockNodeFlags node_flags = node->GetMergedFlags(); const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None); const bool has_close_button = (node_flags & ImGuiDockNodeFlags_NoCloseButton) == 0; // In a dock node, the Collapse Button turns into the Window Menu button. // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes? if (has_window_menu_button && IsPopupOpen("#WindowMenu")) { if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar)) focus_tab_id = tab_bar->NextSelectedTabId = tab_id; is_focused |= node->IsFocused; } // Layout ImRect title_bar_rect, tab_bar_rect; ImVec2 window_menu_button_pos; DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos); // Submit new tabs and apply NavWindow focus back to the tab bar. They will be added as Unsorted and sorted below based on relative DockOrder value. const int tabs_count_old = tab_bar->Tabs.Size; for (int window_n = 0; window_n < node->Windows.Size; window_n++) { ImGuiWindow* window = node->Windows[window_n]; if (g.NavWindow && g.NavWindow->RootWindowDockStop == window) tab_bar->SelectedTabId = window->ID; if (TabBarFindTabByID(tab_bar, window->ID) == NULL) TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window); } // Title bar if (is_focused) node->LastFrameFocused = g.FrameCount; ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, ImDrawCornerFlags_Top); // Docking/Collapse button if (has_window_menu_button) { if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) OpenPopup("#WindowMenu"); if (IsItemActive()) focus_tab_id = tab_bar->SelectedTabId; } // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value int tabs_unsorted_start = tab_bar->Tabs.Size; for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--) { // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted; tabs_unsorted_start = tab_n; } if (tab_bar->Tabs.Size > tabs_unsorted_start) { IMGUI_DEBUG_LOG_DOCKING("In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : ""); for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++) IMGUI_DEBUG_LOG_DOCKING(" - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder); if (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder); } // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL) tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId; else if (tab_bar->Tabs.Size > tabs_count_old) tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->ID; // Begin tab bar ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons); tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode; if (!host_window->Collapsed && is_focused) tab_bar_flags |= ImGuiTabBarFlags_IsFocused; BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node); //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255)); // Backup style colors ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT]; for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]]; // Submit actual tabs node->VisibleWindow = NULL; for (int window_n = 0; window_n < node->Windows.Size; window_n++) { ImGuiWindow* window = node->Windows[window_n]; if ((closed_all || closed_one == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument)) continue; if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active) { ImGuiTabItemFlags tab_item_flags = 0; tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet; if (window->Flags & ImGuiWindowFlags_UnsavedDocument) tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument; if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; // Apply stored style overrides for the window for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]); bool tab_open = true; TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window); if (!tab_open) node->WantCloseTabId = window->ID; if (tab_bar->VisibleTabId == window->ID) node->VisibleWindow = window; // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call window->DockTabItemStatusFlags = host_window->DC.LastItemStatusFlags; window->DockTabItemRect = host_window->DC.LastItemRect; // Update navigation ID on menu layer if (g.NavWindow && g.NavWindow->RootWindowDockStop == window && (window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0) host_window->NavLastIds[1] = window->ID; } } // Restore style colors for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n]; // Notify root of visible window (used to display title in OS task bar) if (node->VisibleWindow) if (is_focused || root_node->VisibleWindow == NULL) root_node->VisibleWindow = node->VisibleWindow; // Close button (after VisibleWindow was updated) // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->ID may be != from tab_bar->SelectedTabId if (has_close_button && node->VisibleWindow) { if (!node->VisibleWindow->HasCloseButton) { PushItemFlag(ImGuiItemFlags_Disabled, true); PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.5f)); } const float button_sz = g.FontSize; if (CloseButton(host_window->GetID("#CLOSE"), title_bar_rect.GetTR() + ImVec2(-style.FramePadding.x * 2.0f - button_sz, 0.0f))) if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->VisibleTabId)) { node->WantCloseTabId = tab->ID; TabBarCloseTab(tab_bar, tab); } //if (IsItemActive()) // focus_tab_id = tab_bar->SelectedTabId; if (!node->VisibleWindow->HasCloseButton) { PopStyleColor(); PopItemFlag(); } } // When clicking on the title bar outside of tabs, we still focus the selected tab for that node // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) ImGuiID title_bar_id = host_window->GetID("#TITLEBAR"); if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id) { bool held; ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap); if (g.HoveredId == title_bar_id) { // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar, // otherwise dragging window will steal HoveredId and amended tabs cannot get them. host_window->DC.LastItemId = title_bar_id; SetItemAllowOverlap(); } if (held) { if (IsMouseClicked(0)) focus_tab_id = tab_bar->SelectedTabId; // Forward moving request to selected window if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); } } // Forward focus from host node to selected window //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget) // focus_tab_id = tab_bar->SelectedTabId; // When clicked on a tab we requested focus to the docked child // This overrides the value set by "forward focus from host node to selected window". if (tab_bar->NextSelectedTabId) focus_tab_id = tab_bar->NextSelectedTabId; // Apply navigation focus if (focus_tab_id != 0) if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id)) if (tab->Window) { FocusWindow(tab->Window); NavInitWindow(tab->Window, false); } EndTabBar(); PopID(); // Restore SkipItems flag if (!node->IsDockSpace()) { host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main; host_window->SkipItems = backup_skip_item; } } static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node) { IM_ASSERT(node->TabBar == NULL); node->TabBar = IM_NEW(ImGuiTabBar); } static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node) { if (node->TabBar == NULL) return; IM_DELETE(node->TabBar); node->TabBar = NULL; } static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window) { if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext) return false; ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass; ImGuiWindowClass* payload_class = &payload->WindowClass; if (host_class->ClassId != payload_class->ClassId) { if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0) return true; if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0) return true; return false; } return true; } static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload) { if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) return true; const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1; for (int payload_n = 0; payload_n < payload_count; payload_n++) { ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload; if (DockNodeIsDropAllowedOne(payload, host_window)) return true; } return false; } // window menu button == collapse button when not in a dock node. // FIXME: This is similar to RenderWindowTitleBarContents, may want to share code. static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos) { ImGuiContext& g = *GImGui; ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f); if (out_title_rect) { *out_title_rect = r; } ImVec2 window_menu_button_pos = r.Min; r.Min.x += g.Style.FramePadding.x; r.Max.x -= g.Style.FramePadding.x; if (node->HasCloseButton) { r.Max.x -= g.FontSize;// +1.0f; // In DockNodeUpdateTabBar() we currently display a disabled close button even if there is none. } if (node->HasWindowMenuButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Left) { r.Min.x += g.FontSize; // + g.Style.ItemInnerSpacing.x; // <-- Adding ItemInnerSpacing makes the title text moves slightly when in a docking tab bar. Instead we adjusted RenderArrowDockMenu() } else if (node->HasWindowMenuButton && g.Style.WindowMenuButtonPosition == ImGuiDir_Right) { r.Max.x -= g.FontSize + g.Style.FramePadding.x; window_menu_button_pos = ImVec2(r.Max.x, r.Min.y); } if (out_tab_bar_rect) { *out_tab_bar_rect = r; } if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; } } void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired) { ImGuiContext& g = *GImGui; const float dock_spacing = g.Style.ItemInnerSpacing.x; const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; pos_new[axis ^ 1] = pos_old[axis ^ 1]; size_new[axis ^ 1] = size_old[axis ^ 1]; // Distribute size on given axis (with a desired size or equally) const float w_avail = size_old[axis] - dock_spacing; if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f) { size_new[axis] = size_new_desired[axis]; size_old[axis] = IM_FLOOR(w_avail - size_new[axis]); } else { size_new[axis] = IM_FLOOR(w_avail * 0.5f); size_old[axis] = IM_FLOOR(w_avail - size_new[axis]); } // Position each node if (dir == ImGuiDir_Right || dir == ImGuiDir_Down) { pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing; } else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up) { pos_new[axis] = pos_old[axis]; pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing; } } // Retrieve the drop rectangles for a given direction or for the center + perform hit testing. bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos) { ImGuiContext& g = *GImGui; const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight()); const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f)); float hs_w; // Half-size, longer axis float hs_h; // Half-size, smaller axis ImVec2 off; // Distance from edge or center if (outer_docking) { //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f)); //hs_h = ImFloor(hs_w * 0.15f); //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h)); hs_w = ImFloor(hs_for_central_nodes * 1.50f); hs_h = ImFloor(hs_for_central_nodes * 0.80f); off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h)); } else { hs_w = ImFloor(hs_for_central_nodes); hs_h = ImFloor(hs_for_central_nodes * 0.90f); off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f)); } ImVec2 c = ImFloor(parent.GetCenter()); if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); } else if (dir == ImGuiDir_Up) { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); } else if (dir == ImGuiDir_Down) { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); } else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); } else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); } if (test_mouse_pos == NULL) return false; ImRect hit_r = out_r; if (!outer_docking) { // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides hit_r.Expand(ImFloor(hs_w * 0.30f)); ImVec2 mouse_delta = (*test_mouse_pos - c); float mouse_delta_len2 = ImLengthSqr(mouse_delta); float r_threshold_center = hs_w * 1.4f; float r_threshold_sides = hs_w * (1.4f + 1.2f); if (mouse_delta_len2 < r_threshold_center * r_threshold_center) return (dir == ImGuiDir_None); if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides) return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y)); } return hit_r.Contains(*test_mouse_pos); } // host_node may be NULL if the window doesn't have a DockNode already. // FIXME-DOCK: This is misnamed since it's also doing the filtering. static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking) { ImGuiContext& g = *GImGui; // There is an edge case when docking into a dockspace which only has inactive nodes. // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive. // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference. ImGuiDockNode* root_payload_as_host = root_payload->DockNodeAsHost; ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node; if (ref_node_for_rect) IM_ASSERT(ref_node_for_rect->IsVisible); // Filter, figure out where we are allowed to dock ImGuiDockNodeFlags src_node_flags = root_payload_as_host ? root_payload_as_host->GetMergedFlags() : root_payload->WindowClass.DockNodeFlagsOverrideSet; ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->GetMergedFlags() : host_window->WindowClass.DockNodeFlagsOverrideSet; data->IsCenterAvailable = true; if (is_outer_docking) data->IsCenterAvailable = false; else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking) data->IsCenterAvailable = false; else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode()) data->IsCenterAvailable = false; else if ((!host_node || !host_node->IsEmpty()) && root_payload_as_host && root_payload_as_host->IsSplitNode() && (root_payload_as_host->OnlyNodeWithWindows == NULL)) // Is _visibly_ split? data->IsCenterAvailable = false; else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther)) data->IsCenterAvailable = false; data->IsSidesAvailable = true; if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit) data->IsSidesAvailable = false; else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode()) data->IsSidesAvailable = false; else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)) data->IsSidesAvailable = false; // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton); data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0); data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos; data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size; // Calculate drop shapes geometry for allowed splitting directions IM_ASSERT(ImGuiDir_None == -1); data->SplitNode = host_node; data->SplitDir = ImGuiDir_None; data->IsSplitDirExplicit = false; if (!host_window->Collapsed) for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++) { if (dir == ImGuiDir_None && !data->IsCenterAvailable) continue; if (dir != ImGuiDir_None && !data->IsSidesAvailable) continue; if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos)) { data->SplitDir = (ImGuiDir)dir; data->IsSplitDirExplicit = true; } } // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable); if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift) data->IsDropAllowed = false; // Calculate split area data->SplitRatio = 0.0f; if (data->SplitDir != ImGuiDir_None) { ImGuiDir split_dir = data->SplitDir; ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y; ImVec2 pos_new, pos_old = data->FutureNode.Pos; ImVec2 size_new, size_old = data->FutureNode.Size; DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, root_payload->Size); // Calculate split ratio so we can pass it down the docking request float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]); data->FutureNode.Pos = pos_new; data->FutureNode.Size = size_new; data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio); } } static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data) { ImGuiContext& g = *GImGui; IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent. // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes. const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload; // In case the two windows involved are on different viewports, we will draw the overlay on each of them. int overlay_draw_lists_count = 0; ImDrawList* overlay_draw_lists[2]; overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport); if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload) overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport); // Draw main preview rectangle const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f); const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f); const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f); const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f); // Display area preview const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0); if (data->IsDropAllowed) { ImRect overlay_rect = data->FutureNode.Rect(); if (data->SplitDir == ImGuiDir_None && can_preview_tabs) overlay_rect.Min.y += GetFrameHeight(); if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable) for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding); } // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read) if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable) { // Compute target tab bar geometry so we can locate our preview tabs ImRect tab_bar_rect; DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL); ImVec2 tab_pos = tab_bar_rect.Min; if (host_node && host_node->TabBar) { if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar()) tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. else tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]->Name, host_node->Windows[0]->HasCloseButton).x; } else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost)) { tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window->Name, host_window->HasCloseButton).x; // Account for slight offset which will be added when changing from title bar to tab bar } // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows) if (root_payload->DockNodeAsHost) IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size); ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL; const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1; for (int payload_n = 0; payload_n < payload_count; payload_n++) { // DockNode's TabBar may have non-window Tabs manually appended by user ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload; if (tab_bar_with_payload && payload_window == NULL) continue; if (!DockNodeIsDropAllowedOne(payload_window, host_window)) continue; // Calculate the tab bounding box for each payload window ImVec2 tab_size = TabItemCalcSize(payload_window->Name, payload_window->HasCloseButton); ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y); tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x; const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]); const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]); PushStyleColor(ImGuiCol_Text, overlay_col_text); for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) { ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0); if (!tab_bar_rect.Contains(tab_bb)) overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max); TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs); TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL); if (!tab_bar_rect.Contains(tab_bb)) overlay_draw_lists[overlay_n]->PopClipRect(); } PopStyleColor(); } } // Display drop boxes const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding); for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++) { if (!data->DropRectsDraw[dir + 1].IsInverted()) { ImRect draw_r = data->DropRectsDraw[dir + 1]; ImRect draw_r_in = draw_r; draw_r_in.Expand(-2.0f); ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop; for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++) { ImVec2 center = ImFloor(draw_r_in.GetCenter()); overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding); overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding); if (dir == ImGuiDir_Left || dir == ImGuiDir_Right) overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines); if (dir == ImGuiDir_Up || dir == ImGuiDir_Down) overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines); } } // Stop after ImGuiDir_None if ((host_node && (host_node->GetMergedFlags() & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit) return; } } //----------------------------------------------------------------------------- // Docking: ImGuiDockNode Tree manipulation functions //----------------------------------------------------------------------------- // - DockNodeTreeSplit() // - DockNodeTreeMerge() // - DockNodeTreeUpdatePosSize() // - DockNodeTreeUpdateSplitterFindTouchingNode() // - DockNodeTreeUpdateSplitter() // - DockNodeTreeFindFallbackLeafNode() // - DockNodeTreeFindNodeByPos() //----------------------------------------------------------------------------- void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node) { ImGuiContext& g = *GImGui; IM_ASSERT(split_axis != ImGuiAxis_None); ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0); child_0->ParentNode = parent_node; ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0); child_1->ParentNode = parent_node; ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1; DockNodeMoveChildNodes(child_inheritor, parent_node); parent_node->ChildNodes[0] = child_0; parent_node->ChildNodes[1] = child_1; parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow; parent_node->SplitAxis = split_axis; parent_node->VisibleWindow = NULL; parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode; float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE); size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f); IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. child_0->SizeRef = child_1->SizeRef = parent_node->Size; child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio); child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]); DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node); DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size); // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property) child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_; child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_; parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; if (child_inheritor->IsCentralNode()) DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor; } void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child) { // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL. ImGuiDockNode* child_0 = parent_node->ChildNodes[0]; ImGuiDockNode* child_1 = parent_node->ChildNodes[1]; IM_ASSERT(child_0 || child_1); IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1); if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0)) { IM_ASSERT(parent_node->TabBar == NULL); IM_ASSERT(parent_node->Windows.Size == 0); } IMGUI_DEBUG_LOG_DOCKING("DockNodeTreeMerge 0x%08X & 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID); ImVec2 backup_last_explicit_size = parent_node->SizeRef; DockNodeMoveChildNodes(parent_node, merge_lead_child); if (child_0) { DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID); } if (child_1) { DockNodeMoveWindows(parent_node, child_1); DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID); } DockNodeApplyPosSizeToWindows(parent_node); parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto; parent_node->VisibleWindow = merge_lead_child->VisibleWindow; parent_node->SizeRef = backup_last_explicit_size; // Flags transfer parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_; if (child_0) { ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL); IM_DELETE(child_0); } if (child_1) { ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL); IM_DELETE(child_1); } } // Update Pos/Size for a node hierarchy (don't affect child Windows yet) void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, bool only_write_to_marked_nodes) { // During the regular dock node update we write to all nodes. // 'only_write_to_marked_nodes' is only set when turning a node visible mid-frame and we need its size right-away. const bool write_to_node = (only_write_to_marked_nodes == false) || (node->MarkedForPosSizeWrite); if (write_to_node) { node->Pos = pos; node->Size = size; } if (node->IsLeafNode()) return; ImGuiDockNode* child_0 = node->ChildNodes[0]; ImGuiDockNode* child_1 = node->ChildNodes[1]; ImVec2 child_0_pos = pos, child_1_pos = pos; ImVec2 child_0_size = size, child_1_size = size; if (child_0->IsVisible && child_1->IsVisible) { const float spacing = DOCKING_SPLITTER_SIZE; const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; const float size_avail = ImMax(size[axis] - spacing, 0.0f); // Size allocation policy // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows. ImGuiContext& g = *GImGui; const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f); // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce) { child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]); child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); } else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce) { child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]); child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]); IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); } else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce) { // FIXME-DOCK: We cannot honor the requested size, so apply ratio. // Currently this path will only be taken if code programmatically sets WantLockSizeOnce float ratio_0 = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]); child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * ratio_0); child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]); IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f); } // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node else if (child_1->IsCentralNode() && child_0->SizeRef[axis] != 0.0f) { child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]); child_1_size[axis] = (size_avail - child_0_size[axis]); } else if (child_0->IsCentralNode() && child_1->SizeRef[axis] != 0.0f) { child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]); child_0_size[axis] = (size_avail - child_1_size[axis]); } else { // 4) Otherwise distribute according to the relative ratio of each SizeRef value float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]); child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5F)); child_1_size[axis] = (size_avail - child_0_size[axis]); } child_1_pos[axis] += spacing + child_0_size[axis]; } child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false; if (child_0->IsVisible) DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size); if (child_1->IsVisible) DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size); } static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes) { if (node->IsLeafNode()) { touching_nodes->push_back(node); return; } if (node->ChildNodes[0]->IsVisible) if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible) DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes); if (node->ChildNodes[1]->IsVisible) if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible) DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes); } void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node) { if (node->IsLeafNode()) return; ImGuiContext& g = *GImGui; ImGuiDockNode* child_0 = node->ChildNodes[0]; ImGuiDockNode* child_1 = node->ChildNodes[1]; if (child_0->IsVisible && child_1->IsVisible) { // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis; IM_ASSERT(axis != ImGuiAxis_None); ImRect bb; bb.Min = child_0->Pos; bb.Max = child_1->Pos; bb.Min[axis] += child_0->Size[axis]; bb.Max[axis ^ 1] += child_1->Size[axis ^ 1]; //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)); const ImGuiDockNodeFlags merged_flags = child_0->GetMergedFlags() | child_1->GetMergedFlags(); const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY; if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag)) { ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding); } else { //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node. //bb.Max[axis] -= 1; PushID(node->ID); // Gather list of nodes that are touching the splitter line. Find resizing limits based on those nodes. ImVector<ImGuiDockNode*> touching_nodes[2]; float min_size = g.Style.WindowMinSize[axis]; float resize_limits[2]; resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size; resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size; ImGuiID splitter_id = GetID("##Splitter"); if (g.ActiveId == splitter_id) { // Only process when splitter is active DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]); DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]); for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++) resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size); for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++) resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size); /* // [DEBUG] Render limits ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); for (int n = 0; n < 2; n++) if (axis == ImGuiAxis_X) draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f); else draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f); */ } // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters float cur_size_0 = child_0->Size[axis]; float cur_size_1 = child_1->Size[axis]; float min_size_0 = resize_limits[0] - child_0->Pos[axis]; float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1]; if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)) { if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0) { child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0; child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis]; child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1; // Lock the size of every node that is a sibling of the node we are touching // This might be less desirable if we can merge sibling of a same axis into the same parental level. for (int side_n = 0; side_n < 2; side_n++) for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++) { ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n]; //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255)); while (touching_node->ParentNode != node) { if (touching_node->ParentNode->SplitAxis == axis) { // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize(). ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n]; node_to_preserve->WantLockSizeOnce = true; //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255)); //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100)); } touching_node = touching_node->ParentNode; } } DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size); DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size); MarkIniSettingsDirty(); } } PopID(); } } if (child_0->IsVisible) DockNodeTreeUpdateSplitter(child_0); if (child_1->IsVisible) DockNodeTreeUpdateSplitter(child_1); } ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node) { if (node->IsLeafNode()) return node; if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0])) return leaf_node; if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1])) return leaf_node; return NULL; } ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos) { if (!node->IsVisible) return NULL; const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE? ImRect r(node->Pos, node->Pos + node->Size); r.Expand(dock_spacing * 0.5f); bool inside = r.Contains(pos); if (!inside) return NULL; if (node->IsLeafNode()) return node; if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos)) return hovered_node; if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos)) return hovered_node; return NULL; } //----------------------------------------------------------------------------- // Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) //----------------------------------------------------------------------------- // - SetWindowDock() [Internal] // - DockSpace() // - DockSpaceOverViewport() //----------------------------------------------------------------------------- // [Internal] Called via SetNextWindowDockID() void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowDockAllowFlags & cond) == 0) return; window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); if (window->DockId == dock_id) return; // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot ImGuiContext* ctx = GImGui; if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id)) if (new_node->IsSplitNode()) { // Policy: Find central node or latest focused node. We first move back to our root node. new_node = DockNodeGetRootNode(new_node); if (new_node->CentralNode) { IM_ASSERT(new_node->CentralNode->IsCentralNode()); dock_id = new_node->CentralNode->ID; } else { dock_id = new_node->LastFocusedNodeId; } } if (window->DockId == dock_id) return; if (window->DockNode) DockNodeRemoveWindow(window->DockNode, window, 0); window->DockId = dock_id; } // Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default. // The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors. // DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app. void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class) { ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; ImGuiWindow* window = GetCurrentWindow(); if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; // Early out if parent window is hidden/collapsed // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960. // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true. if (window->SkipItems) flags |= ImGuiDockNodeFlags_KeepAliveOnly; IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0); IM_ASSERT(id != 0); ImGuiDockNode* node = DockContextFindNodeByID(ctx, id); if (!node) { IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X created\n", id); node = DockContextAddNode(ctx, id); node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; } if (window_class && window_class->ClassId != node->WindowClass.ClassId) IMGUI_DEBUG_LOG_DOCKING("DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId); node->SharedFlags = flags; node->WindowClass = window_class ? *window_class : ImGuiWindowClass(); // When a DockSpace transitioned form implicit to explicit this may be called a second time // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly)) { IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID"); node->LocalFlags |= ImGuiDockNodeFlags_DockSpace; return; } node->LocalFlags |= ImGuiDockNodeFlags_DockSpace; // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible if (flags & ImGuiDockNodeFlags_KeepAliveOnly) { node->LastFrameAlive = g.FrameCount; return; } const ImVec2 content_avail = GetContentRegionAvail(); ImVec2 size = ImFloor(size_arg); 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); IM_ASSERT(size.x > 0.0f && size.y > 0.0f); node->Pos = window->DC.CursorPos; node->Size = node->SizeRef = size; SetNextWindowPos(node->Pos); SetNextWindowSize(node->Size); g.NextWindowData.PosUndock = false; // FIXME-DOCK Why do we need a child window to host a dockspace, could we host it in the existing window? ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost; window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar; window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; char title[256]; ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id); // FIXME-DOCK: What is the reason for not simply calling BeginChild()? if (node->Windows.Size > 0 || node->IsSplitNode()) PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0)); PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f); Begin(title, NULL, window_flags); PopStyleVar(); if (node->Windows.Size > 0 || node->IsSplitNode()) PopStyleColor(); ImGuiWindow* host_window = g.CurrentWindow; host_window->DockNodeAsHost = node; host_window->ChildId = window->GetID(title); node->HostWindow = host_window; node->OnlyNodeWithWindows = NULL; IM_ASSERT(node->IsRootNode()); // We need to handle the rare case were a central node is missing. // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace. // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, // as it doesn't make sense for an empty dockspace to not have this property. if (node->IsLeafNode() && !node->IsCentralNode()) node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; // Update the node DockNodeUpdate(node); End(); ItemSize(size); } // Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode! // The limitation with this call is that your window won't have a menu bar. // Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function. // But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it. ImGuiID ImGui::DockSpaceOverViewport(ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class) { if (viewport == NULL) viewport = GetMainViewport(); SetNextWindowPos(viewport->GetWorkPos()); SetNextWindowSize(viewport->GetWorkSize()); SetNextWindowViewport(viewport->ID); ImGuiWindowFlags host_window_flags = 0; host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking; host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode) host_window_flags |= ImGuiWindowFlags_NoBackground; char label[32]; ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID); PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); Begin(label, NULL, host_window_flags); PopStyleVar(3); ImGuiID dockspace_id = GetID("DockSpace"); DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class); End(); return dockspace_id; } //----------------------------------------------------------------------------- // Docking: Builder Functions //----------------------------------------------------------------------------- // Very early end-user API to manipulate dock nodes. // Only available in imgui_internal.h. Expect this API to change/break! // It is expected that those functions are all called _before_ the dockspace node submission. //----------------------------------------------------------------------------- // - DockBuilderDockWindow() // - DockBuilderGetNode() // - DockBuilderSetNodePos() // - DockBuilderSetNodeSize() // - DockBuilderAddNode() // - DockBuilderRemoveNode() // - DockBuilderRemoveNodeChildNodes() // - DockBuilderRemoveNodeDockedWindows() // - DockBuilderSplitNode() // - DockBuilderCopyNodeRec() // - DockBuilderCopyNode() // - DockBuilderCopyWindowSettings() // - DockBuilderCopyDockSpace() // - DockBuilderFinish() //----------------------------------------------------------------------------- void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id) { // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1) ImGuiID window_id = ImHashStr(window_name); if (ImGuiWindow* window = FindWindowByID(window_id)) { // Apply to created window SetWindowDock(window, node_id, ImGuiCond_Always); window->DockOrder = -1; } else { // Apply to settings ImGuiWindowSettings* settings = FindWindowSettings(window_id); if (settings == NULL) settings = CreateNewWindowSettings(window_name); settings->DockId = node_id; settings->DockOrder = -1; } } ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id) { ImGuiContext* ctx = GImGui; return DockContextFindNodeByID(ctx, node_id); } void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos) { ImGuiContext* ctx = GImGui; ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id); if (node == NULL) return; node->Pos = pos; node->AuthorityForPos = ImGuiDataAuthority_DockNode; } void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size) { ImGuiContext* ctx = GImGui; ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id); if (node == NULL) return; IM_ASSERT(size.x > 0.0f && size.y > 0.0f); node->Size = node->SizeRef = size; node->AuthorityForSize = ImGuiDataAuthority_DockNode; } // Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node! // - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node. // - Dockspace node: calling DockBuilderSetNodePos() is unnecessary. // - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! // For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. // - Use (id == 0) to let the system allocate a node identifier. // - Existing node with a same id will be removed. ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags) { ImGuiContext* ctx = GImGui; ImGuiDockNode* node = NULL; if (id != 0) DockBuilderRemoveNode(id); if (flags & ImGuiDockNodeFlags_DockSpace) { DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly); node = DockContextFindNodeByID(ctx, id); } else { node = DockContextAddNode(ctx, id); node->LocalFlags = flags; } node->LastFrameAlive = ctx->FrameCount; // Set this otherwise BeginDocked will undock during the same frame. return node->ID; } void ImGui::DockBuilderRemoveNode(ImGuiID node_id) { ImGuiContext* ctx = GImGui; ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id); if (node == NULL) return; DockBuilderRemoveNodeDockedWindows(node_id, true); DockBuilderRemoveNodeChildNodes(node_id); if (node->IsCentralNode() && node->ParentNode) node->ParentNode->LocalFlags |= ImGuiDockNodeFlags_CentralNode; DockContextRemoveNode(ctx, node, true); } // root_id = 0 to remove all, root_id != 0 to remove child of given node. void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id) { ImGuiContext* ctx = GImGui; ImGuiDockContext* dc = &ctx->DockContext; ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL; if (root_id && root_node == NULL) return; bool has_central_node = false; ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto; ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto; // Process active windows ImVector<ImGuiDockNode*> nodes_to_remove; for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) { bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id); if (want_removal) { if (node->IsCentralNode()) has_central_node = true; if (root_id != 0) DockContextQueueNotifyRemovedNode(ctx, node); if (root_node) DockNodeMoveWindows(root_node, node); nodes_to_remove.push_back(node); } } // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge) // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead) if (root_node) { root_node->AuthorityForPos = backup_root_node_authority_for_pos; root_node->AuthorityForSize = backup_root_node_authority_for_size; } // Apply to settings for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings)) if (ImGuiID window_settings_dock_id = settings->DockId) for (int n = 0; n < nodes_to_remove.Size; n++) if (nodes_to_remove[n]->ID == window_settings_dock_id) { settings->DockId = root_id; break; } // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes if (nodes_to_remove.Size > 1) ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst); for (int n = 0; n < nodes_to_remove.Size; n++) DockContextRemoveNode(ctx, nodes_to_remove[n], false); if (root_id == 0) { dc->Nodes.Clear(); dc->Requests.clear(); } else if (has_central_node) { root_node->LocalFlags |= ImGuiDockNodeFlags_CentralNode; root_node->CentralNode = root_node; } } void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs) { // Clear references in settings ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; if (clear_settings_refs) { for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) { bool want_removal = (root_id == 0) || (settings->DockId == root_id); if (!want_removal && settings->DockId != 0) if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId)) if (DockNodeGetRootNode(node)->ID == root_id) want_removal = true; if (want_removal) settings->DockId = 0; } } // Clear references in windows for (int n = 0; n < g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id); if (want_removal) { const ImGuiID backup_dock_id = window->DockId; IM_UNUSED(backup_dock_id); DockContextProcessUndockWindow(ctx, window, clear_settings_refs); if (!clear_settings_refs) IM_ASSERT(window->DockId == backup_dock_id); } } } // If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created. // Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set. // FIXME-DOCK: We are not exposing nor using split_outer. ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir) { ImGuiContext* ctx = GImGui; IM_ASSERT(split_dir != ImGuiDir_None); IMGUI_DEBUG_LOG_DOCKING("DockBuilderSplitNode node 0x%08X, split_dir %d\n", id, split_dir); ImGuiDockNode* node = DockContextFindNodeByID(ctx, id); if (node == NULL) { IM_ASSERT(node != NULL); return 0; } IM_ASSERT(!node->IsSplitNode()); // Assert if already Split ImGuiDockRequest req; req.Type = ImGuiDockRequestType_Split; req.DockTargetWindow = NULL; req.DockTargetNode = node; req.DockPayload = NULL; req.DockSplitDir = split_dir; req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir); req.DockSplitOuter = false; DockContextProcessDock(ctx, &req); ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID; ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID; if (out_id_at_dir) *out_id_at_dir = id_at_dir; if (out_id_at_opposite_dir) *out_id_at_opposite_dir = id_at_opposite_dir; return id_at_dir; } static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs) { ImGuiContext* ctx = GImGui; ImGuiDockNode* dst_node = ImGui::DockContextAddNode(ctx, dst_node_id_if_known); dst_node->SharedFlags = src_node->SharedFlags; dst_node->LocalFlags = src_node->LocalFlags; dst_node->Pos = src_node->Pos; dst_node->Size = src_node->Size; dst_node->SizeRef = src_node->SizeRef; dst_node->SplitAxis = src_node->SplitAxis; out_node_remap_pairs->push_back(src_node->ID); out_node_remap_pairs->push_back(dst_node->ID); for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++) if (src_node->ChildNodes[child_n]) { dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs); dst_node->ChildNodes[child_n]->ParentNode = dst_node; } IMGUI_DEBUG_LOG_DOCKING("Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0); return dst_node; } void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs) { ImGuiContext* ctx = GImGui; IM_ASSERT(src_node_id != 0); IM_ASSERT(dst_node_id != 0); IM_ASSERT(out_node_remap_pairs != NULL); ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id); IM_ASSERT(src_node != NULL); out_node_remap_pairs->clear(); DockBuilderRemoveNode(dst_node_id); DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs); IM_ASSERT((out_node_remap_pairs->Size % 2) == 0); } void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name) { ImGuiWindow* src_window = FindWindowByName(src_name); if (src_window == NULL) return; if (ImGuiWindow* dst_window = FindWindowByName(dst_name)) { dst_window->Pos = src_window->Pos; dst_window->Size = src_window->Size; dst_window->SizeFull = src_window->SizeFull; dst_window->Collapsed = src_window->Collapsed; } else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name)) { ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos); if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID) { dst_settings->ViewportPos = window_pos_2ih; dst_settings->ViewportId = src_window->ViewportId; dst_settings->Pos = ImVec2ih(0, 0); } else { dst_settings->Pos = window_pos_2ih; } dst_settings->Size = ImVec2ih(src_window->SizeFull); dst_settings->Collapsed = src_window->Collapsed; } } // FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed. void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs) { IM_ASSERT(src_dockspace_id != 0); IM_ASSERT(dst_dockspace_id != 0); IM_ASSERT(in_window_remap_pairs != NULL); IM_ASSERT((in_window_remap_pairs->Size % 2) == 0); // Duplicate entire dock // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart, // whereas we could attempt to at least keep them together in a new, same floating node. ImVector<ImGuiID> node_remap_pairs; DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs); // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes // (The windows associated to src_dockspace_id are staying in place) ImVector<ImGuiID> src_windows; for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2) { const char* src_window_name = (*in_window_remap_pairs)[remap_window_n]; const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1]; ImGuiID src_window_id = ImHashStr(src_window_name); src_windows.push_back(src_window_id); // Search in the remapping tables ImGuiID src_dock_id = 0; if (ImGuiWindow* src_window = FindWindowByID(src_window_id)) src_dock_id = src_window->DockId; else if (ImGuiWindowSettings* src_window_settings = FindWindowSettings(src_window_id)) src_dock_id = src_window_settings->DockId; ImGuiID dst_dock_id = 0; for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2) if (node_remap_pairs[dock_remap_n] == src_dock_id) { dst_dock_id = node_remap_pairs[dock_remap_n + 1]; //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear break; } if (dst_dock_id != 0) { // Docked windows gets redocked into the new node hierarchy. IMGUI_DEBUG_LOG_DOCKING("Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id); DockBuilderDockWindow(dst_window_name, dst_dock_id); } else { // Floating windows gets their settings transferred (regardless of whether the new window already exist or not) // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together? IMGUI_DEBUG_LOG_DOCKING("Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name); DockBuilderCopyWindowSettings(src_window_name, dst_window_name); } } // Anything else in the source nodes of 'node_remap_pairs' are windows that were docked in src_dockspace_id but are not owned by it (unaffiliated windows, e.g. "ImGui Demo") // Find those windows and move to them to the cloned dock node. This may be optional? for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2) if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n]) { ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1]; ImGuiDockNode* node = DockBuilderGetNode(src_dock_id); for (int window_n = 0; window_n < node->Windows.Size; window_n++) { ImGuiWindow* window = node->Windows[window_n]; if (src_windows.contains(window->ID)) continue; // Docked windows gets redocked into the new node hierarchy. IMGUI_DEBUG_LOG_DOCKING("Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id); DockBuilderDockWindow(window->Name, dst_dock_id); } } } void ImGui::DockBuilderFinish(ImGuiID root_id) { ImGuiContext* ctx = GImGui; //DockContextRebuild(ctx); DockContextBuildAddWindowsToNodes(ctx, root_id); } //----------------------------------------------------------------------------- // Docking: Begin/End Support Functions (called from Begin/End) //----------------------------------------------------------------------------- // - GetWindowAlwaysWantOwnTabBar() // - DockContextBindNodeToWindow() // - BeginDocked() // - BeginDockableDragDropSource() // - BeginDockableDragDropTarget() //----------------------------------------------------------------------------- bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar) if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0) if (!window->IsFallbackWindow) // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise return true; return false; } static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window) { ImGuiContext& g = *ctx; ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId); IM_ASSERT(window->DockNode == NULL); // We should not be docking into a split node (SetWindowDock should avoid this) if (node && node->IsSplitNode()) { DockContextProcessUndockWindow(ctx, window); return NULL; } // Create node if (node == NULL) { node = DockContextAddNode(ctx, window->DockId); node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window; node->LastFrameAlive = g.FrameCount; } // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. if (!node->IsVisible) { ImGuiDockNode* ancestor_node = node; while (!ancestor_node->IsVisible) { ancestor_node->IsVisible = true; ancestor_node->MarkedForPosSizeWrite = true; if (ancestor_node->ParentNode) ancestor_node = ancestor_node->ParentNode; } IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f); DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, true); } // Add window to node DockNodeAddWindow(node, window, true); IM_ASSERT(node == window->DockNode); return node; } void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open) { ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window); if (auto_dock_node) { if (window->DockId == 0) { IM_ASSERT(window->DockNode == NULL); window->DockId = DockContextGenNodeID(ctx); } } else { // Calling SetNextWindowPos() undock windows by default (by setting PosUndock) bool want_undock = false; want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0; want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock; if (want_undock) { DockContextProcessUndockWindow(ctx, window); return; } } // Bind to our dock node ImGuiDockNode* node = window->DockNode; if (node != NULL) IM_ASSERT(window->DockId == node->ID); if (window->DockId != 0 && node == NULL) { node = DockContextBindNodeToWindow(ctx, window); if (node == NULL) return; } #if 0 // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode)) { DockContextProcessUndockWindow(ctx, window); return; } #endif // Undock if our dockspace node disappeared // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly. if (node->LastFrameAlive < g.FrameCount) { // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking() ImGuiDockNode* root_node = DockNodeGetRootNode(node); if (root_node->LastFrameAlive < g.FrameCount) { DockContextProcessUndockWindow(ctx, window); } else { window->DockIsActive = true; window->DockTabIsVisible = false; } return; } // Store style overrides for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]); // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window, // and never create neither a host window neither a tab bar. // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test) if (node->HostWindow == NULL) { window->DockIsActive = (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing); window->DockTabIsVisible = false; return; } // We can have zero-sized nodes (e.g. children of a small-size dockspace) IM_ASSERT(node->HostWindow); IM_ASSERT(node->IsLeafNode()); IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f); node->State = ImGuiDockNodeState_HostWindowVisible; // Undock if we are submitted earlier than the host window if (window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext) { DockContextProcessUndockWindow(ctx, window); return; } // Position/Size window SetNextWindowPos(node->Pos); SetNextWindowSize(node->Size); g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos() window->DockIsActive = true; window->DockTabIsVisible = false; if (node->SharedFlags & ImGuiDockNodeFlags_KeepAliveOnly) return; // When the window is selected we mark it as visible. if (node->VisibleWindow == window) window->DockTabIsVisible = true; // Update window flag IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0); window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize; if (node->IsHiddenTabBar() || node->IsNoTabBar()) window->Flags |= ImGuiWindowFlags_NoTitleBar; else window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! // Save new dock order only if the tab bar has been visible once. // This allows multiple windows to be created in the same frame and have their respective dock orders preserved. if (node->TabBar && node->TabBar->CurrFrameVisible != -1) window->DockOrder = (short)DockNodeGetTabOrder(window); if ((node->WantCloseAll || node->WantCloseTabId == window->ID) && p_open != NULL) *p_open = false; // Update ChildId to allow returning from Child to Parent with Escape ImGuiWindow* parent_window = window->DockNode->HostWindow; window->ChildId = parent_window->GetID(window->Name); } void ImGui::BeginDockableDragDropSource(ImGuiWindow* window) { ImGuiContext& g = *GImGui; IM_ASSERT(g.ActiveId == window->MoveId); IM_ASSERT(g.MovingWindow == window); window->DC.LastItemId = window->MoveId; window = window->RootWindow; IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload)) { SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window)); EndDragDropSource(); // Store style overrides for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++) window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]); } } void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window) { ImGuiContext* ctx = GImGui; ImGuiContext& g = *ctx; //IM_ASSERT(window->RootWindow == window); // May also be a DockSpace IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0); if (!g.DragDropActive) return; //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!BeginDragDropTargetCustom(window->Rect(), window->ID)) return; // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly) const ImGuiPayload* payload = &g.DragDropPayload; if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data)) { EndDragDropTarget(); return; } ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data; if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { // Select target node // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) bool dock_into_floating_window = false; ImGuiDockNode* node = NULL; if (window->DockNodeAsHost) { // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos); // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) // In this case we need to fallback into any leaf mode, possibly the central node. // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. if (node && node->IsDockSpace() && node->IsRootNode()) node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node); } else { if (window->DockNode) node = window->DockNode; else dock_into_floating_window = true; // Dock into a regular window } const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight())); const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max); // Preview docking request and find out split direction/ratio //const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. const bool do_preview = payload->IsPreview() || payload->IsDelivery(); if (do_preview && (node != NULL || dock_into_floating_window)) { ImGuiDockPreviewData split_inner; ImGuiDockPreviewData split_outer; ImGuiDockPreviewData* split_data = &split_inner; if (node && (node->ParentNode || node->IsCentralNode())) if (ImGuiDockNode* root_node = DockNodeGetRootNode(node)) { DockNodePreviewDockSetup(window, root_node, payload_window, &split_outer, is_explicit_target, true); if (split_outer.IsSplitDirExplicit) split_data = &split_outer; } DockNodePreviewDockSetup(window, node, payload_window, &split_inner, is_explicit_target, false); if (split_data == &split_outer) split_inner.IsDropAllowed = false; // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes DockNodePreviewDockRender(window, node, payload_window, &split_inner); DockNodePreviewDockRender(window, node, payload_window, &split_outer); // Queue docking request if (split_data->IsDropAllowed && payload->IsDelivery()) DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer); } } EndDragDropTarget(); } //----------------------------------------------------------------------------- // Docking: Settings //----------------------------------------------------------------------------- // - DockSettingsRenameNodeReferences() // - DockSettingsRemoveNodeReferences() // - DockSettingsFindNodeSettings() // - DockSettingsHandler_ApplyAll() // - DockSettingsHandler_ReadOpen() // - DockSettingsHandler_ReadLine() // - DockSettingsHandler_DockNodeToSettings() // - DockSettingsHandler_WriteAll() //----------------------------------------------------------------------------- static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id) { ImGuiContext& g = *GImGui; IMGUI_DEBUG_LOG_DOCKING("DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id); for (int window_n = 0; window_n < g.Windows.Size; window_n++) { ImGuiWindow* window = g.Windows[window_n]; if (window->DockId == old_node_id && window->DockNode == NULL) window->DockId = new_node_id; } //// FIXME-OPT: We could remove this loop by storing the index in the map for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) if (settings->DockId == old_node_id) settings->DockId = new_node_id; } // Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count) { ImGuiContext& g = *GImGui; int found = 0; //// FIXME-OPT: We could remove this loop by storing the index in the map for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) for (int node_n = 0; node_n < node_ids_count; node_n++) if (settings->DockId == node_ids[node_n]) { settings->DockId = 0; settings->DockOrder = -1; if (++found < node_ids_count) break; return; } } static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id) { // FIXME-OPT ImGuiDockContext* dc = &ctx->DockContext; for (int n = 0; n < dc->NodesSettings.Size; n++) if (dc->NodesSettings[n].ID == id) return &dc->NodesSettings[n]; return NULL; } // Clear settings data static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { ImGuiDockContext* dc = &ctx->DockContext; dc->NodesSettings.clear(); DockContextClearNodes(ctx, 0, true); } // Recreate nodes based on settings data static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*) { // Prune settings at boot time only ImGuiDockContext* dc = &ctx->DockContext; if (ctx->Windows.Size == 0) DockContextPruneUnusedSettingsNodes(ctx); DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size); DockContextBuildAddWindowsToNodes(ctx, 0); } static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { if (strcmp(name, "Data") != 0) return NULL; return (void*)1; } static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line) { char c = 0; int x = 0, y = 0; int r = 0; // Parsing, e.g. // " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 " // " DockNode ID=0x00000002 Parent=0x00000001 " // Important: this code expect currently fields in a fixed order. ImGuiDockNodeSettings node; line = ImStrSkipBlank(line); if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); } else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; } else return; if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return; if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1) { line += r; if (node.ParentNodeId == 0) return; } if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; } if (node.ParentNodeId == 0) { if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return; if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return; } else { if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); } } if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; } if (sscanf(line, " NoResize=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; } if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; } if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; } if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; } if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; } if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1) { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; } if (sscanf(line, " Selected=0x%08X%n", &node.SelectedWindowId,&r) == 1) { line += r; } if (node.ParentNodeId != 0) if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId)) node.Depth = parent_settings->Depth + 1; ctx->DockContext.NodesSettings.push_back(node); } static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth) { ImGuiDockNodeSettings node_settings; IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3))); node_settings.ID = node->ID; node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0; node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0; node_settings.SelectedWindowId = node->SelectedTabId; node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None); node_settings.Depth = (char)depth; node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_); node_settings.Pos = ImVec2ih(node->Pos); node_settings.Size = ImVec2ih(node->Size); node_settings.SizeRef = ImVec2ih(node->SizeRef); dc->NodesSettings.push_back(node_settings); if (node->ChildNodes[0]) DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1); if (node->ChildNodes[1]) DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1); } static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { ImGuiContext& g = *ctx; ImGuiDockContext* dc = &ctx->DockContext; if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)) return; // Gather settings data // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) dc->NodesSettings.resize(0); dc->NodesSettings.reserve(dc->Nodes.Data.Size); for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (node->IsRootNode()) DockSettingsHandler_DockNodeToSettings(dc, node, 0); int max_depth = 0; for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth); // Write to text buffer buf->appendf("[%s][Data]\n", handler->TypeName); for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++) { const int line_start_pos = buf->size(); (void)line_start_pos; const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n]; buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file buf->appendf(" ID=0x%08X", node_settings->ID); if (node_settings->ParentNodeId) { buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y); } else { if (node_settings->ParentWindowId) buf->appendf(" Window=0x%08X", node_settings->ParentWindowId); buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y); } if (node_settings->SplitAxis != ImGuiAxis_None) buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y'); if (node_settings->Flags & ImGuiDockNodeFlags_NoResize) buf->appendf(" NoResize=1"); if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode) buf->appendf(" CentralNode=1"); if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar) buf->appendf(" NoTabBar=1"); if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar) buf->appendf(" HiddenTabBar=1"); if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton) buf->appendf(" NoWindowMenuButton=1"); if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton) buf->appendf(" NoCloseButton=1"); if (node_settings->SelectedWindowId) buf->appendf(" Selected=0x%08X", node_settings->SelectedWindowId); #if IMGUI_DEBUG_INI_SETTINGS // [DEBUG] Include comments in the .ini file to ease debugging if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID)) { buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name); // Iterate settings so we can give info about windows that didn't exist during the session. int contains_window = 0; for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) if (settings->DockId == node_settings->ID) { if (contains_window++ == 0) buf->appendf(" ; contains "); buf->appendf("'%s' ", settings->GetName()); } } #endif buf->appendf("\n"); } buf->appendf("\n"); } //----------------------------------------------------------------------------- // [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 //----------------------------------------------------------------------------- // [SECTION] METRICS/DEBUGGER WINDOW //----------------------------------------------------------------------------- // - RenderViewportThumbnail() [Internal] // - RenderViewportsThumbnails() [Internal] // - MetricsHelpMarker() [Internal] // - ShowMetricsWindow() // - DebugNodeColumns() [Internal] // - DebugNodeDockNode() [Internal] // - DebugNodeDrawList() [Internal] // - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal] // - DebugNodeStorage() [Internal] // - DebugNodeTabBar() [Internal] // - DebugNodeViewport() [Internal] // - DebugNodeWindow() [Internal] // - DebugNodeWindowSettings() [Internal] // - DebugNodeWindowsList() [Internal] //----------------------------------------------------------------------------- #ifndef IMGUI_DISABLE_METRICS_WINDOW static void RenderViewportThumbnail(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 = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f; window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::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; if (thumb_window->SkipItems && (thumb_window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME-DOCK: Skip hidden docked windows. Identify those betters. continue; if (thumb_window->Viewport != viewport) continue; ImRect thumb_r = thumb_window->Rect(); ImRect title_r = thumb_window->TitleBarRect(); ImRect thumb_r_scaled = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale)); ImRect title_r_scaled = 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_scaled.ClipWithFull(bb); title_r_scaled.ClipWithFull(bb); const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight); window->DrawList->AddRectFilled(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_WindowBg, alpha_mul)); window->DrawList->AddRectFilled(title_r_scaled.Min, title_r_scaled.Max, ImGui::GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul)); window->DrawList->AddRect(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul)); if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(thumb_window)) window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r_scaled.Min, ImGui::GetColorU32(ImGuiCol_Text, alpha_mul), window_for_title->Name, ImGui::FindRenderedTextEnd(window_for_title->Name)); } draw_list->AddRect(bb.Min, bb.Max, ImGui::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; //for (int n = 0; n < g.PlatformIO.Monitors.Size; n++) // bb_full.Add(GetPlatformMonitorMainRect(g.PlatformIO.Monitors[n])); 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.PlatformIO.Monitors.Size; n++) // window->DrawList->AddRect(off + g.PlatformIO.Monitors[n].MainPos * SCALE, off + (g.PlatformIO.Monitors[n].MainPos + g.PlatformIO.Monitors[n].MainSize) * SCALE, ImGui::GetColorU32(ImGuiCol_Border)); 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); RenderViewportThumbnail(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(); } } 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(); } // Contents DebugNodeWindowsList(&g.Windows, "Windows"); //DebugNodeWindowsList(&g.WindowsFocusOrder, "WindowsFocusOrder"); if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size)) { Indent(GetTreeNodeToLabelSpacing()); RenderViewportsThumbnails(); Unindent(GetTreeNodeToLabelSpacing()); bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size); ImGui::SameLine(); MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors."); if (open) { for (int i = 0; i < g.PlatformIO.Monitors.Size; i++) { const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i]; BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)", i, mon.DpiScale * 100.0f, mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y, mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y); } TreePop(); } 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 #ifdef IMGUI_HAS_TABLE if (TreeNode("Tables", "Tables (%d)", g.Tables.GetSize())) { for (int n = 0; n < g.Tables.GetSize(); n++) DebugNodeTable(g.Tables.GetByIndex(n)); TreePop(); } #endif // #ifdef IMGUI_HAS_TABLE // Details for Docking #ifdef IMGUI_HAS_DOCK if (TreeNode("Docking")) { static bool root_nodes_only = true; ImGuiDockContext* dc = &g.DockContext; Checkbox("List root nodes", &root_nodes_only); Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes); if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); } SameLine(); if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; } for (int n = 0; n < dc->Nodes.Data.Size; n++) if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p) if (!root_nodes_only || node->IsRootNode()) DebugNodeDockNode(node, "Node"); 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(); } #ifdef IMGUI_HAS_TABLE 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(); } #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK if (ImGui::TreeNode("SettingsDocking", "Settings packed data: Docking")) { ImGuiDockContext* dc = &g.DockContext; ImGui::Text("In SettingsWindows:"); for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings)) if (settings->DockId != 0) ImGui::BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId); ImGui::Text("In SettingsNodes:"); for (int n = 0; n < dc->NodesSettings.Size; n++) { ImGuiDockNodeSettings* settings = &dc->NodesSettings[n]; const char* selected_tab_name = NULL; if (settings->SelectedWindowId) { if (ImGuiWindow* window = FindWindowByID(settings->SelectedWindowId)) selected_tab_name = window->Name; else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedWindowId)) selected_tab_name = window_settings->GetName(); } ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedWindowId, selected_tab_name ? selected_tab_name : settings->SelectedWindowId ? "N/A" : ""); } ImGui::TreePop(); } #endif // #ifdef IMGUI_HAS_DOCK 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(); } TreePop(); } // Misc Details if (TreeNode("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); Text("WINDOWING"); Indent(); Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL"); Text("HoveredDockNode: 0x%08X", g.HoveredDockNode ? g.HoveredDockNode->ID : 0); Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0); 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); } } } #ifdef IMGUI_HAS_TABLE // 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)); } } } #endif // #ifdef IMGUI_HAS_TABLE #ifdef IMGUI_HAS_DOCK // Overlay: Display Docking info if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.HoveredDockNode) { char buf[64] = ""; char* p = buf; ImGuiDockNode* node = g.HoveredDockNode; ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList((ImGuiViewportP*)GetMainViewport()); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : ""); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y); p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y); int depth = DockNodeGetDepth(node); overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255)); ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth; overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255)); overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf); } #endif // #ifdef IMGUI_HAS_DOCK End(); } // [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 ImDockNode void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label) { ImGuiContext& g = *GImGui; const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2); // Submitted with ImGuiDockNodeFlags_KeepAliveOnly const bool is_active = (g.FrameCount - node->LastFrameActive < 2); // Submitted if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); } bool open; if (node->Windows.Size > 0) open = TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); else open = TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" : "n/a", node->VisibleWindow ? node->VisibleWindow->Name : "NULL"); if (!is_alive) { PopStyleColor(); } if (is_active && IsItemHovered()) if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow) GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255)); if (open) { IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node); IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node); BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)", node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y); DebugNodeWindow(node->HostWindow, "HostWindow"); DebugNodeWindow(node->VisibleWindow, "VisibleWindow"); BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId); BulletText("Misc:%s%s%s%s%s", node->IsDockSpace() ? " IsDockSpace" : "", node->IsCentralNode() ? " IsCentralNode" : "", is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->WantLockSizeOnce ? " WantLockSizeOnce" : ""); if (TreeNode("flags", "LocalFlags: 0x%04X SharedFlags: 0x%04X", node->LocalFlags, node->SharedFlags)) { CheckboxFlags("LocalFlags: NoDocking", &node->LocalFlags, ImGuiDockNodeFlags_NoDocking); CheckboxFlags("LocalFlags: NoSplit", &node->LocalFlags, ImGuiDockNodeFlags_NoSplit); CheckboxFlags("LocalFlags: NoResize", &node->LocalFlags, ImGuiDockNodeFlags_NoResize); CheckboxFlags("LocalFlags: NoResizeX", &node->LocalFlags, ImGuiDockNodeFlags_NoResizeX); CheckboxFlags("LocalFlags: NoResizeY", &node->LocalFlags, ImGuiDockNodeFlags_NoResizeY); CheckboxFlags("LocalFlags: NoTabBar", &node->LocalFlags, ImGuiDockNodeFlags_NoTabBar); CheckboxFlags("LocalFlags: HiddenTabBar", &node->LocalFlags, ImGuiDockNodeFlags_HiddenTabBar); CheckboxFlags("LocalFlags: NoWindowMenuButton", &node->LocalFlags, ImGuiDockNodeFlags_NoWindowMenuButton); CheckboxFlags("LocalFlags: NoCloseButton", &node->LocalFlags, ImGuiDockNodeFlags_NoCloseButton); TreePop(); } if (node->ParentNode) DebugNodeDockNode(node->ParentNode, "ParentNode"); if (node->ChildNodes[0]) DebugNodeDockNode(node->ChildNodes[0], "Child[0]"); if (node->ChildNodes[1]) DebugNodeDockNode(node->ChildNodes[1], "Child[1]"); if (node->TabBar) DebugNodeTabBar(node->TabBar, "TabBar"); TreePop(); } } // [DEBUG] Display contents of ImDrawList // Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport. void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, 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 = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list if (window && fg_draw_list && 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), true, 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), true, 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 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*"); p += ImFormatString(p, buf_end - p, " { "); for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", (tab->Window || tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "???"); } p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } "); 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->Window || 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((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A")) { ImGuiWindowFlags flags = viewport->Flags; BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.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, viewport->PlatformMonitor, viewport->DpiScale * 100.0f); if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200,200); if (viewport->Window) viewport->Window->Pos = ImVec2(200,200); } } BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s", viewport->Flags, (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "", (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "", (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "", (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : ""); 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, 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->Viewport, 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("WindowClassId: 0x%08X", window->WindowClass.ClassId); 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); BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); if (!window->NavRectRel[0].IsInverted()) BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y); else BulletText("NavRectRel[0]: <None>"); BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y); BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1); BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible); if (window->DockNode || window->DockNodeAsHost) DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode"); if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); } if (window->RootWindowDockStop != window->RootWindow) { DebugNodeWindow(window->RootWindowDockStop, "RootWindowDockStop"); } 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::DebugNodeColumns(ImGuiOldColumns*) {} void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {} void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {} 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
#include "../Character.hpp" void Character::resetCollide() { objectCollides[0] = 0; objectCollides[1] = 0; objectCollides[2] = 0; objectCollides[3] = 0; }
// 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/password_manager/core/browser/leak_detection/encryption_utils.h" #include <climits> #include <utility> #include "base/cxx17_backports.h" #include "base/strings/strcat.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "crypto/openssl_util.h" #include "crypto/sha2.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/boringssl/src/include/openssl/evp.h" #include "third_party/boringssl/src/include/openssl/nid.h" #include "third_party/private-join-and-compute/src/crypto/ec_commutative_cipher.h" namespace password_manager { namespace { template <typename T, typename CharT = typename T::value_type> std::basic_string<CharT> CanonicalizeUsernameT(T username) { static constexpr CharT kPeriod = '.'; std::basic_string<CharT> email_lower = base::ToLowerASCII(username); // |email_lower| might be an email address. Strip off the mail-address host, // remove periods from the username and return the result. std::basic_string<CharT> user_lower = email_lower.substr(0, email_lower.find_last_of('@')); base::RemoveChars(user_lower, {&kPeriod, 1}, &user_lower); return user_lower; } } // namespace std::string CanonicalizeUsername(base::StringPiece username) { return CanonicalizeUsernameT(username); } std::u16string CanonicalizeUsername(base::StringPiece16 username) { return CanonicalizeUsernameT(username); } std::string HashUsername(base::StringPiece canonicalized_username) { // Needs to stay in sync with server side constant: go/passwords-leak-salts static constexpr char kUsernameSalt[] = { -60, -108, -93, -107, -8, -64, -30, 62, -87, 35, 4, 120, 112, 44, 114, 24, 86, 84, -103, -77, -23, 33, 24, 108, 33, 26, 1, 34, 60, 69, 74, -6}; // Check that |canonicalized_username| is actually canonicalized. // Note: We can't use CanonicalizeUsername() again, since it's not idempotent // if multiple '@' signs are present in the initial username. DCHECK_EQ(base::ToLowerASCII(canonicalized_username), canonicalized_username); return crypto::SHA256HashString(base::StrCat( {canonicalized_username, base::StringPiece(kUsernameSalt, base::size(kUsernameSalt))})); } std::string BucketizeUsername(base::StringPiece canonicalized_username) { // Compute the number of bytes necessary to store `kUsernameHashPrefixLength` // bits. constexpr size_t kPrefixBytes = (kUsernameHashPrefixLength + CHAR_BIT - 1) / CHAR_BIT; // Compute the remainder, and construct a mask that keeps the first // `kPrefixRemainder` bits. constexpr size_t kPrefixRemainder = kUsernameHashPrefixLength % CHAR_BIT; constexpr size_t kPrefixMask = ((1 << kPrefixRemainder) - 1) << (CHAR_BIT - kPrefixRemainder); // Check that |canonicalized_username| is actually canonicalized. // Note: We can't use CanonicalizeUsername() again, since it's not idempotent // if multiple '@' signs are present in the initial username. DCHECK_EQ(base::ToLowerASCII(canonicalized_username), canonicalized_username); std::string prefix = HashUsername(canonicalized_username).substr(0, kPrefixBytes); if (kPrefixRemainder != 0) prefix.back() &= kPrefixMask; return prefix; } absl::optional<std::string> ScryptHashUsernameAndPassword( base::StringPiece canonicalized_username, base::StringPiece password) { // Constant salt added to the password hash on top of canonicalized_username. // Needs to stay in sync with server side constant: go/passwords-leak-salts static constexpr char kPasswordHashSalt[] = { 48, 118, 42, -46, 63, 123, -95, -101, -8, -29, 66, -4, -95, -89, -115, 6, -26, 107, -28, -37, -72, 79, -127, 83, -59, 3, -56, -37, -67, -34, -91, 32}; static constexpr size_t kHashKeyLength = 32; static constexpr uint64_t kScryptCost = 1 << 12; // It must be a power of 2. static constexpr uint64_t kScryptBlockSize = 8; static constexpr uint64_t kScryptParallelization = 1; static constexpr size_t kScryptMaxMemory = 1024 * 1024 * 32; // Check that |canonicalized_username| is actually canonicalized. // Note: We can't use CanonicalizeUsername() again, since it's not idempotent // if multiple '@' signs are present in the initial username. DCHECK_EQ(base::ToLowerASCII(canonicalized_username), canonicalized_username); crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); std::string username_password = base::StrCat({canonicalized_username, password}); std::string salt = base::StrCat( {canonicalized_username, base::StringPiece(kPasswordHashSalt, base::size(kPasswordHashSalt))}); std::string result; uint8_t* key_data = reinterpret_cast<uint8_t*>(base::WriteInto(&result, kHashKeyLength + 1)); int scrypt_ok = EVP_PBE_scrypt(username_password.data(), username_password.size(), reinterpret_cast<const uint8_t*>(salt.data()), salt.size(), kScryptCost, kScryptBlockSize, kScryptParallelization, kScryptMaxMemory, key_data, kHashKeyLength); return scrypt_ok == 1 ? absl::make_optional(std::move(result)) : absl::nullopt; } absl::optional<std::string> CipherEncrypt(const std::string& plaintext, std::string* key) { using ::private_join_and_compute::ECCommutativeCipher; auto cipher = ECCommutativeCipher::CreateWithNewKey( NID_X9_62_prime256v1, ECCommutativeCipher::SHA256); if (cipher.ok()) { auto result = cipher.ValueOrDie()->Encrypt(plaintext); if (result.ok()) { *key = cipher.ValueOrDie()->GetPrivateKeyBytes(); return std::move(result).ValueOrDie(); } } return absl::nullopt; } absl::optional<std::string> CipherEncryptWithKey(const std::string& plaintext, const std::string& key) { using ::private_join_and_compute::ECCommutativeCipher; auto cipher = ECCommutativeCipher::CreateFromKey(NID_X9_62_prime256v1, key, ECCommutativeCipher::SHA256); if (cipher.ok()) { auto result = cipher.ValueOrDie()->Encrypt(plaintext); if (result.ok()) return std::move(result).ValueOrDie(); } return absl::nullopt; } absl::optional<std::string> CipherReEncrypt( const std::string& already_encrypted, std::string* key) { using ::private_join_and_compute::ECCommutativeCipher; auto cipher = ECCommutativeCipher::CreateWithNewKey( NID_X9_62_prime256v1, ECCommutativeCipher::SHA256); if (cipher.ok()) { auto result = cipher.ValueOrDie()->ReEncrypt(already_encrypted); if (result.ok()) { *key = cipher.ValueOrDie()->GetPrivateKeyBytes(); return std::move(result).ValueOrDie(); } } return absl::nullopt; } absl::optional<std::string> CipherDecrypt(const std::string& ciphertext, const std::string& key) { using ::private_join_and_compute::ECCommutativeCipher; auto cipher = ECCommutativeCipher::CreateFromKey(NID_X9_62_prime256v1, key, ECCommutativeCipher::SHA256); if (cipher.ok()) { auto result = cipher.ValueOrDie()->Decrypt(ciphertext); if (result.ok()) return std::move(result).ValueOrDie(); } return absl::nullopt; } absl::optional<std::string> CreateNewKey() { using ::private_join_and_compute::ECCommutativeCipher; auto cipher = ECCommutativeCipher::CreateWithNewKey( NID_X9_62_prime256v1, ECCommutativeCipher::SHA256); if (cipher.ok()) return cipher.ValueOrDie()->GetPrivateKeyBytes(); return absl::nullopt; } } // namespace password_manager
// Copyright 2010-2016 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_GEO_INDEXING_HPP_ #define RDB_PROTOCOL_GEO_INDEXING_HPP_ #include <string> #include <vector> #include "btree/concurrent_traversal.hpp" #include "containers/counted.hpp" #include "rdb_protocol/geo/s2/s2cellid.h" namespace ql { class datum_t; enum class skey_version_t; } class signal_t; /* Polygons and lines are inserted into an index by computing a coverage of them consisting of cells on a pre-defined multi-level grid. This constant determines how many grid cells should be used to cover the polygon/line. If the number is small, index insertion becomes more efficient, but querying the index becomes less efficient. High values make geo indexes larger and inserting into them slower, while usually improving query efficiency. See the comments in s2regioncoverer.h for further explanation and for statistics on the effects of different choices of this parameter.*/ extern const int GEO_INDEX_GOAL_GRID_CELLS; std::vector<std::string> compute_index_grid_keys( const ql::datum_t &key, int goal_cells); std::vector<geo::S2CellId> compute_cell_covering( const ql::datum_t &key, int goal_cells); std::vector<geo::S2CellId> compute_interior_cell_covering( const ql::datum_t &key, const std::vector<geo::S2CellId> &exterior_covering); // TODO (daniel): Support compound indexes somehow. class geo_index_traversal_helper_t : public concurrent_traversal_callback_t { public: geo_index_traversal_helper_t( ql::skey_version_t skey_version, const signal_t *interruptor); void init_query( const std::vector<geo::S2CellId> &query_cell_covering, const std::vector<geo::S2CellId> &query_interior_cell_covering); /* Called for every pair that could potentially intersect with query_grid_keys. Note that this might be called multiple times for the same value. Correct ordering of the call is not guaranteed. Implementations are expected to call waiter.wait_interruptible() before performing ordering-sensitive operations. `definitely_intersects_if_point` is true only if the key is also contained in the interior cell covering. If the key corresponds to a point, that implies that the point is contained in the query geometry. Note that this doesn't hold for more complex geometry, since the keys corresponding to more complex geometry are generated from a covering. The way we compute the covering, we do not guarantee that each cell in the covering actually intersects with the covered geometry (S2RegionCoverer uses `MayIntersect` tests rather than exact `Intersects` tests). `definitely_intersects_if_point` can be used to avoid unnecessary intersection tests during post-filtering. */ virtual continue_bool_t on_candidate( scoped_key_value_t &&keyvalue, concurrent_traversal_fifo_enforcer_signal_t waiter, bool definitely_intersects_if_point) THROWS_ONLY(interrupted_exc_t) = 0; /* concurrent_traversal_callback_t interface */ continue_bool_t handle_pair(scoped_key_value_t &&keyvalue, concurrent_traversal_fifo_enforcer_signal_t waiter) THROWS_ONLY(interrupted_exc_t); void filter_range( const btree_key_t *left_excl_or_null, const btree_key_t *right_incl, bool *skip_out); private: static bool cell_intersects_with_range(const geo::S2CellId c, const geo::S2CellId left_min, const geo::S2CellId right_max); bool any_query_cell_intersects(const btree_key_t *left_excl_or_null, const btree_key_t *right_incl) const; static bool any_cell_intersects(const std::vector<geo::S2CellId> &cells, const geo::S2CellId left_min, const geo::S2CellId right_max); static bool any_cell_contains(const std::vector<geo::S2CellId> &cells, const geo::S2CellId key); std::vector<geo::S2CellId> query_cells_; std::vector<geo::S2CellId> query_interior_cells_; bool is_initialized_; const ql::skey_version_t skey_version_; const signal_t *interruptor_; }; #endif // RDB_PROTOCOL_GEO_INDEXING_HPP_
/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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 __itktubeSpatialObjectToImageFilter_hxx #define __itktubeSpatialObjectToImageFilter_hxx #include "itktubeSpatialObjectToImageFilter.h" #include <itkImageRegionIteratorWithIndex.h> #include <vnl/vnl_vector.h> /** Constructor */ template< unsigned int ObjectDimension, class TOutputImage, class TRadiusImage, class TTangentImage > TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage, TTangentImage > ::TubeSpatialObjectToImageFilter( void ) { m_UseRadius = false; m_Cumulative = false; m_BuildRadiusImage = false; m_BuildTangentImage = false; m_FallOff = 0.0; this->m_Size.Fill(0); unsigned int i; for(i=0; i<ObjectDimension; i++) { this->m_Spacing[i] = 1; this->m_Origin[i] = 0; } // This is a little bit tricky since the 2nd an 3rd outputs are // not always computed this->SetNumberOfRequiredOutputs( 3 ); m_RadiusImage = TRadiusImage::New(); this->SetNthOutput( 1, m_RadiusImage ); m_TangentImage = TTangentImage::New(); this->SetNthOutput( 2, m_TangentImage ); } /** Destructor */ template< unsigned int ObjectDimension, class TOutputImage, class TRadiusImage, class TTangentImage > TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage, TTangentImage > ::~TubeSpatialObjectToImageFilter( void ) { } /** Return the Radius Image */ template< unsigned int ObjectDimension, class TOutputImage, class TRadiusImage, class TTangentImage > typename TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage, TTangentImage >::RadiusImagePointer TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage, TTangentImage > ::GetRadiusImage( void ) { return dynamic_cast< TRadiusImage * >(this->ProcessObject::GetOutput(1) ); } /** Return the tangent Image */ template< unsigned int ObjectDimension, class TOutputImage, class TRadiusImage, class TTangentImage > typename TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage, TTangentImage >::TangentImagePointer TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage, TTangentImage > ::GetTangentImage( void ) { return dynamic_cast< TTangentImage * >(this->ProcessObject::GetOutput(2) ); } /** Update */ template< unsigned int ObjectDimension, class TOutputImage, class TRadiusImage, class TTangentImage > void TubeSpatialObjectToImageFilter< ObjectDimension, TOutputImage, TRadiusImage, TTangentImage > ::GenerateData( void ) { itkDebugMacro( << "TubeSpatialObjectToImageFilter::Update() called." ); //Get the input and output pointers const typename SuperClass::InputSpatialObjectType * InputTube = this->GetInput(); typename SuperClass::OutputImagePointer OutputImage = this->GetOutput(); // Generate the image typename OutputImageType::RegionType region; if( this->m_Size[0] == 0 ) { std::cout << "WARNING: Size not set." << std::endl; std::cout << " Reverting to an incorrect method to compute region." << std::endl; SizeType size; typename SuperClass::InputSpatialObjectType::BoundingBoxType::PointType maxPoint; maxPoint = InputTube->GetBoundingBox()->GetMaximum(); typename OutputImageType::PointType physicalSize; unsigned int buffer = 4; for(unsigned int i=0; i<ObjectDimension; i++) { maxPoint[i] = maxPoint[i] * ( InputTube->GetIndexToObjectTransform() ) ->GetScaleComponent()[i]; physicalSize[i] = maxPoint[i] - this->m_Origin[i]; /** Get the origin point within the image so that the object * remains in the image **/ size[i] = (long unsigned int)( physicalSize[i] / this->m_Spacing[i] ) + buffer; } region.SetSize( size ); } else { region.SetSize( this->m_Size ); } typename OutputImageType::IndexType index; index.Fill(0); region.SetIndex( index ); OutputImage->SetLargestPossibleRegion( region ); // OutputImage->SetBufferedRegion( region ); // set the region OutputImage->SetRequestedRegion( region ); // OutputImage->SetSpacing( this->m_Spacing ); OutputImage->SetOrigin( this->m_Origin ); OutputImage->Allocate(); OutputImage->FillBuffer( 0 ); itk::Point<double, 3> point; m_RadiusImage = this->GetRadiusImage(); //Build radius image for processing if( m_BuildRadiusImage ) { m_RadiusImage->SetRegions( region ); m_RadiusImage->SetSpacing( this->m_Spacing ); m_RadiusImage->SetOrigin( this->m_Origin ); m_RadiusImage->Allocate(); m_RadiusImage->FillBuffer( 0 ); } m_TangentImage = this->GetTangentImage(); //Build radius image for processing if( m_BuildTangentImage ) { m_TangentImage->SetRegions( region ); m_TangentImage->SetSpacing( this->m_Spacing ); m_TangentImage->SetOrigin( this->m_Origin ); m_TangentImage->Allocate(); TangentPixelType v; v.Fill( 0 ); m_TangentImage->FillBuffer( v ); } // Get the list of tubes char tubeName[] = "Tube"; ChildrenListType* tubeList = InputTube->GetChildren(this->m_ChildrenDepth, tubeName); //int size = tubeList->size(); typedef typename ChildrenListType::iterator ChildrenIteratorType; ChildrenIteratorType TubeIterator = tubeList->begin(); typename OutputImageType::IndexType index2; while(TubeIterator != tubeList->end()) { // Force the computation of the tangents if( m_BuildTangentImage ) { ((TubeType *)((*TubeIterator).GetPointer()))->RemoveDuplicatePoints(); ((TubeType *)((*TubeIterator).GetPointer()))->ComputeTangentAndNormals(); } for(unsigned int k=0; k < ((TubeType *)(TubeIterator->GetPointer()))->GetNumberOfPoints(); k++) { bool IsInside = true; typedef typename TubeType::TubePointType TubePointType; const TubePointType* tubePoint = static_cast<const TubePointType*>( ((TubeType *) (TubeIterator->GetPointer())) ->GetPoint(k)); for(unsigned int i=0; i<ObjectDimension; i++) { point[i] = ((tubePoint->GetPosition()[i] * ((TubeType *)(TubeIterator->GetPointer()))-> GetIndexToObjectTransform()-> GetScaleComponent()[i]) - this->m_Origin[i]) / this->m_Spacing[i]; index[i] = (long int)(point[i]+0.5); if( (index[i]<=0) || ( static_cast<unsigned int>(index[i]) >= OutputImage->GetLargestPossibleRegion().GetSize()[i] ) ) { IsInside = false; } } if( IsInside ) { // Density Image if(m_Cumulative) { OutputImage->SetPixel(index,OutputImage->GetPixel(index)+1); } else { OutputImage->SetPixel(index,1); } // Tangent Image if(m_BuildTangentImage) { // Convert the tangent type to the actual tangent image pixel type typename TubeType::VectorType t = tubePoint->GetTangent(); TangentPixelType tp; for(unsigned int tpind = 0;tpind<ObjectDimension;tpind++) { tp[tpind] = t[tpind]; } m_TangentImage->SetPixel(index,tp); } // Radius Image and Density image with radius if(m_UseRadius) { double phys_pt_radius = tubePoint->GetRadius() * ((TubeType *)((TubeIterator) ->GetPointer())) ->GetIndexToObjectTransform() ->GetScaleComponent()[0]; if(m_BuildRadiusImage) { m_RadiusImage->SetPixel(index, static_cast<RadiusPixelType>( phys_pt_radius ) ); } long radius = (long int)( phys_pt_radius / this->m_Spacing[0]); double step = radius/2; while(step > 1) { step /= 2; } if(step < 0.5) { step = 0.5; } if(ObjectDimension == 2) { for(double x=-radius; x<=radius+step/2; x+=step) { for(double y=-radius; y<=radius+step/2; y+=step) { if( ( (x*x) +(y*y)) <= (radius*radius) ) // test inside the sphere { index2[0]=(long)(point[0]+x+0.5); index2[1]=(long)(point[1]+y+0.5); if( (unsigned long)index2[0] < OutputImage->GetLargestPossibleRegion().GetSize()[0] && (unsigned long)index2[1] < OutputImage->GetLargestPossibleRegion().GetSize()[1] ) { typedef typename OutputImageType::PixelType PixelType; if(m_Cumulative) { OutputImage->SetPixel(index2, (PixelType)(OutputImage ->GetPixel(index2) + 0.5)); } else { OutputImage->SetPixel(index2,1); } if(m_BuildRadiusImage) { m_RadiusImage->SetPixel(index2, phys_pt_radius); } } } } } } else if(ObjectDimension == 3) { for(double x=-radius; x<=radius+step/2; x+=step) { for(double y=-radius; y<=radius+step/2; y+=step) { for(double z=-radius; z<=radius+step/2; z+=step) { if( ( (x*x) +(y*y) +(z*z)) <= (radius*radius) ) // test inside the sphere { index2[0]=(long)(point[0]+x+0.5); index2[1]=(long)(point[1]+y+0.5); index2[2]=(long)(point[2]+z+0.5); // Test that point is within the output image boundries if( index2[0] >= 0 && index2[1] >= 0 && index2[2] >= 0 && (unsigned long)index2[0] < OutputImage->GetLargestPossibleRegion() .GetSize()[0] && (unsigned long)index2[1] < OutputImage->GetLargestPossibleRegion() .GetSize()[1] && (unsigned long)index2[2] < OutputImage->GetLargestPossibleRegion() .GetSize()[2]) { OutputImage->SetPixel(index2,1); if(m_BuildRadiusImage) { m_RadiusImage->SetPixel(index2, phys_pt_radius); } } } } } } } } } } ++TubeIterator; } delete tubeList; itkDebugMacro( << "TubeSpatialObjectToImageFilter::Update() finished." ); } // End update function #endif // End !defined(__itktubeSpatialObjectToImageFilter_hxx)
// Distributed under the MIT License. // See LICENSE.txt for details. #include "Framework/TestingFramework.hpp" #include <cstddef> #include <tuple> #include "DataStructures/DataBox/Prefixes.hpp" // IWYU pragma: keep #include "DataStructures/DataVector.hpp" #include "DataStructures/Tensor/TypeAliases.hpp" #include "Domain/CoordinateMaps/Affine.hpp" #include "Domain/CoordinateMaps/CoordinateMap.hpp" #include "Domain/CoordinateMaps/CoordinateMap.tpp" #include "Domain/CoordinateMaps/ProductMaps.hpp" #include "Domain/CoordinateMaps/ProductMaps.tpp" #include "Elliptic/Systems/Poisson/FirstOrderSystem.hpp" #include "Elliptic/Systems/Poisson/Geometry.hpp" #include "Elliptic/Systems/Poisson/Tags.hpp" // IWYU pragma: keep #include "Framework/CheckWithRandomValues.hpp" #include "Framework/SetupLocalPythonEnvironment.hpp" #include "Framework/TestCreation.hpp" #include "Framework/TestHelpers.hpp" #include "Helpers/PointwiseFunctions/AnalyticSolutions/FirstOrderEllipticSolutionsTestHelpers.hpp" #include "NumericalAlgorithms/Spectral/Mesh.hpp" #include "NumericalAlgorithms/Spectral/Spectral.hpp" #include "PointwiseFunctions/AnalyticSolutions/Poisson/Lorentzian.hpp" #include "Utilities/TMPL.hpp" #include "Utilities/TaggedTuple.hpp" namespace { template <size_t Dim> struct LorentzianProxy : Poisson::Solutions::Lorentzian<Dim> { using Poisson::Solutions::Lorentzian<Dim>::Lorentzian; using field_tags = tmpl::list< Poisson::Tags::Field, ::Tags::deriv<Poisson::Tags::Field, tmpl::size_t<Dim>, Frame::Inertial>, ::Tags::Flux<Poisson::Tags::Field, tmpl::size_t<Dim>, Frame::Inertial>>; using source_tags = tmpl::list<Tags::FixedSource<Poisson::Tags::Field>>; tuples::tagged_tuple_from_typelist<field_tags> field_variables( const tnsr::I<DataVector, Dim, Frame::Inertial>& x) const noexcept { return Poisson::Solutions::Lorentzian<Dim>::variables(x, field_tags{}); } tuples::tagged_tuple_from_typelist<source_tags> source_variables( const tnsr::I<DataVector, Dim, Frame::Inertial>& x) const noexcept { return Poisson::Solutions::Lorentzian<Dim>::variables(x, source_tags{}); } }; template <size_t Dim> void test_solution() { const LorentzianProxy<Dim> solution{}; pypp::check_with_random_values<1>( &LorentzianProxy<Dim>::field_variables, solution, "Lorentzian", {"field", "field_gradient", "field_flux"}, {{{-5., 5.}}}, std::make_tuple(), DataVector(5)); pypp::check_with_random_values<1>( &LorentzianProxy<Dim>::source_variables, solution, "Lorentzian", {"source"}, {{{-5., 5.}}}, std::make_tuple(), DataVector(5)); const Poisson::Solutions::Lorentzian<Dim> check_solution{}; const auto created_solution = TestHelpers::test_creation<Poisson::Solutions::Lorentzian<Dim>>(""); CHECK(created_solution == check_solution); test_serialization(check_solution); test_copy_semantics(check_solution); } } // namespace SPECTRE_TEST_CASE( "Unit.PointwiseFunctions.AnalyticSolutions.Poisson.Lorentzian", "[PointwiseFunctions][Unit]") { pypp::SetupLocalPythonEnvironment local_python_env{ "PointwiseFunctions/AnalyticSolutions/Poisson"}; // 1D and 2D solutions are not implemented yet. test_solution<3>(); { // Verify that the solution numerically solves the system and that the // discretization error decreases exponentially with polynomial order using system = Poisson::FirstOrderSystem<3, Poisson::Geometry::FlatCartesian>; const Poisson::Solutions::Lorentzian<3> solution{}; const typename system::fluxes_computer fluxes_computer{}; using AffineMap = domain::CoordinateMaps::Affine; using AffineMap3D = domain::CoordinateMaps::ProductOf3Maps<AffineMap, AffineMap, AffineMap>; const domain::CoordinateMap<Frame::Logical, Frame::Inertial, AffineMap3D> coord_map{ {{-1., 1., -0.5, 0.5}, {-1., 1., -0.5, 0.5}, {-1., 1., -0.5, 0.5}}}; FirstOrderEllipticSolutionsTestHelpers::verify_smooth_solution<system>( solution, fluxes_computer, coord_map, 5.e1, 1.2, [](const auto&... /*unused*/) noexcept { return std::tuple<>{}; }); } { // Verify that the solution also solves the non-euclidean system with a // Euclidean metric. This is more a test of the system than of the solution. using system = Poisson::FirstOrderSystem<3, Poisson::Geometry::Curved>; const Poisson::Solutions::Lorentzian<3> solution{}; const typename system::fluxes_computer fluxes_computer{}; using AffineMap = domain::CoordinateMaps::Affine; using AffineMap3D = domain::CoordinateMaps::ProductOf3Maps<AffineMap, AffineMap, AffineMap>; const domain::CoordinateMap<Frame::Logical, Frame::Inertial, AffineMap3D> coord_map{ {{-1., 1., -0.5, 0.5}, {-1., 1., -0.5, 0.5}, {-1., 1., -0.5, 0.5}}}; Mesh<3> mesh{8, Spectral::Basis::Legendre, Spectral::Quadrature::GaussLobatto}; const DataVector used_for_size{mesh.number_of_grid_points()}; auto inv_spatial_metric = make_with_value<tnsr::II<DataVector, 3>>(used_for_size, 0.); get<0, 0>(inv_spatial_metric) = 1.; get<1, 1>(inv_spatial_metric) = 1.; get<2, 2>(inv_spatial_metric) = 1.; const auto spatial_christoffel_contracted = make_with_value<tnsr::i<DataVector, 3>>(used_for_size, 0.); FirstOrderEllipticSolutionsTestHelpers::verify_solution<system>( solution, fluxes_computer, mesh, coord_map, 0.1, std::make_tuple(inv_spatial_metric), std::make_tuple(spatial_christoffel_contracted)); } }
// Copyright (c) 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 "chromeos/network/geolocation_handler.h" #include <stddef.h> #include <stdint.h> #include "base/bind.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "chromeos/dbus/shill/shill_manager_client.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace chromeos { namespace { constexpr const char* kDevicePropertyNames[] = { shill::kGeoWifiAccessPointsProperty, shill::kGeoCellTowersProperty}; std::string HexToDecimal(std::string hex_str) { return std::to_string(std::stoi(hex_str, nullptr, 16)); } std::string FindStringOrEmpty(const base::Value& dict, const base::StringPiece key) { const std::string* val = dict.FindStringKey(key); return val ? *val : std::string(); } } // namespace GeolocationHandler::GeolocationHandler() : cellular_enabled_(false), wifi_enabled_(false) {} GeolocationHandler::~GeolocationHandler() { if (ShillManagerClient::Get()) ShillManagerClient::Get()->RemovePropertyChangedObserver(this); } void GeolocationHandler::Init() { ShillManagerClient::Get()->GetProperties( base::BindOnce(&GeolocationHandler::ManagerPropertiesCallback, weak_ptr_factory_.GetWeakPtr())); ShillManagerClient::Get()->AddPropertyChangedObserver(this); } bool GeolocationHandler::GetWifiAccessPoints( WifiAccessPointVector* access_points, int64_t* age_ms) { if (!wifi_enabled_) return false; // Always request updated info. RequestGeolocationObjects(); // If no data has been received, return false. if (geolocation_received_time_.is_null() || wifi_access_points_.size() == 0) return false; if (access_points) *access_points = wifi_access_points_; if (age_ms) { base::TimeDelta dtime = base::Time::Now() - geolocation_received_time_; *age_ms = dtime.InMilliseconds(); } return true; } bool GeolocationHandler::GetNetworkInformation( WifiAccessPointVector* access_points, CellTowerVector* cell_towers) { if (!cellular_enabled_ && !wifi_enabled_) return false; // Always request updated info. RequestGeolocationObjects(); // If no data has been received, return false. if (geolocation_received_time_.is_null()) return false; if (cell_towers) *cell_towers = cell_towers_; if (access_points) *access_points = wifi_access_points_; return true; } void GeolocationHandler::OnPropertyChanged(const std::string& key, const base::Value& value) { HandlePropertyChanged(key, value); } //------------------------------------------------------------------------------ // Private methods void GeolocationHandler::ManagerPropertiesCallback( absl::optional<base::Value> properties) { if (!properties) return; const base::Value* value = properties->FindKey(shill::kEnabledTechnologiesProperty); if (value) HandlePropertyChanged(shill::kEnabledTechnologiesProperty, *value); } void GeolocationHandler::HandlePropertyChanged(const std::string& key, const base::Value& value) { if (key != shill::kEnabledTechnologiesProperty) return; const base::ListValue* technologies = nullptr; if (!value.GetAsList(&technologies) || !technologies) return; bool wifi_was_enabled = wifi_enabled_; bool cellular_was_enabled = cellular_enabled_; cellular_enabled_ = false; wifi_enabled_ = false; for (const auto& entry : technologies->GetList()) { const std::string* technology = entry.GetIfString(); if (technology && *technology == shill::kTypeWifi) { wifi_enabled_ = true; } else if (technology && *technology == shill::kTypeCellular) { cellular_enabled_ = true; } if (wifi_enabled_ && cellular_enabled_) break; } // Request initial location data. if ((!wifi_was_enabled && wifi_enabled_) || (!cellular_was_enabled && cellular_enabled_)) { RequestGeolocationObjects(); } } void GeolocationHandler::RequestGeolocationObjects() { ShillManagerClient::Get()->GetNetworksForGeolocation( base::BindOnce(&GeolocationHandler::GeolocationCallback, weak_ptr_factory_.GetWeakPtr())); } void GeolocationHandler::GeolocationCallback( absl::optional<base::Value> properties) { if (!properties || !properties->is_dict()) { LOG(ERROR) << "Failed to get Geolocation data"; return; } wifi_access_points_.clear(); cell_towers_.clear(); if (properties->DictEmpty()) return; // No enabled devices, don't update received time. // Dictionary<device_type, entry_list> // Example dict returned from shill: // { // kGeoWifiAccessPointsProperty: [ {kGeoMacAddressProperty: mac_value, ...}, // ... // ], // kGeoCellTowersProperty: [ {kGeoCellIdProperty: cell_id_value, ...}, ... ] // } for (auto* device_type : kDevicePropertyNames) { const base::Value* entry_list = properties->FindKey(device_type); if (!entry_list) { continue; } if (!entry_list->is_list()) { LOG(WARNING) << "Geolocation dictionary value not a List: " << device_type; continue; } // List[Dictionary<key, value_str>] for (const auto& entry : entry_list->GetList()) { if (!entry.is_dict()) { LOG(WARNING) << "Geolocation list value not a Dictionary"; continue; } if (device_type == shill::kGeoWifiAccessPointsProperty) { AddAccessPointFromDict(entry); } else if (device_type == shill::kGeoCellTowersProperty) { AddCellTowerFromDict(entry); } } } geolocation_received_time_ = base::Time::Now(); } void GeolocationHandler::AddAccessPointFromDict(const base::Value& entry) { // Docs: developers.google.com/maps/documentation/business/geolocation WifiAccessPoint wap; const std::string* age_str = entry.FindStringKey(shill::kGeoAgeProperty); if (age_str) { int64_t age_ms; if (base::StringToInt64(*age_str, &age_ms)) { wap.timestamp = base::Time::Now() - base::Milliseconds(age_ms); } } wap.mac_address = FindStringOrEmpty(entry, shill::kGeoMacAddressProperty); const std::string* strength_str = entry.FindStringKey(shill::kGeoSignalStrengthProperty); if (strength_str) { base::StringToInt(*strength_str, &wap.signal_strength); } const std::string* signal_str = entry.FindStringKey(shill::kGeoSignalToNoiseRatioProperty); if (signal_str) { base::StringToInt(*signal_str, &wap.signal_to_noise); } const std::string* channel_str = entry.FindStringKey(shill::kGeoChannelProperty); if (channel_str) { base::StringToInt(*channel_str, &wap.channel); } wifi_access_points_.push_back(wap); } void GeolocationHandler::AddCellTowerFromDict(const base::Value& entry) { // Docs: developers.google.com/maps/documentation/business/geolocation // Create object. CellTower ct; // Read time fields into object. const std::string* age_str = entry.FindStringKey(shill::kGeoAgeProperty); if (age_str) { int64_t age_ms; if (base::StringToInt64(*age_str, &age_ms)) { ct.timestamp = base::Time::Now() - base::Milliseconds(age_ms); } } // Read hex fields into object. const std::string* hex_cell_id = entry.FindStringKey(shill::kGeoCellIdProperty); if (hex_cell_id) { ct.ci = HexToDecimal(*hex_cell_id); } const std::string* hex_lac = entry.FindStringKey(shill::kGeoLocationAreaCodeProperty); if (hex_lac) { ct.lac = HexToDecimal(*hex_lac); } // Read decimal fields into object. ct.mcc = FindStringOrEmpty(entry, shill::kGeoMobileCountryCodeProperty); ct.mnc = FindStringOrEmpty(entry, shill::kGeoMobileNetworkCodeProperty); // Add new object to vector. cell_towers_.push_back(ct); } } // namespace chromeos
//2012/02/11 //231.cpp //Run time: 0.004 #include <stdio.h> #include <string.h> int missile[70000]; int dp[70000]; int top, caseNum, i, j, ans, once; int max(int a, int b){ return a>b?a:b; } void solve(){ memset(dp, 0, sizeof(int)* top +1); for(ans=i=0; i<top; ++i){ dp[i] = 1; for(j=0; j<i; ++j) if(missile[i] <= missile[j]) dp[i] = max(dp[i], dp[j]+1); ans = max(ans, dp[i]); } if(once) putchar(10); printf("Test #%d:\n maximum possible interceptions: %d\n", ++caseNum, ans); top = 0; once = 1; return; } int main(){ #ifndef ONLINE_JUDGE freopen("231.in", "r", stdin); freopen("231.out", "w", stdout); #endif while(scanf("%d", &missile[top]) != EOF){ if(missile[top] == -1){ if(top == 0) break; solve(); }else ++top; } return 0; }
#include <autoxtime/ui/EventWidget.h> // autoxtime #include <autoxtime/db/EventModel.h> #include <autoxtime/log/Log.h> #include <autoxtime/proto/event.pb.h> #include <autoxtime/ui/EventImportDialog.h> // Qt #include <QDateEdit> #include <QGridLayout> #include <QLabel> #include <QLineEdit> #include <QPushButton> AUTOXTIME_UI_NAMESPACE_BEG EventWidget::EventWidget(QWidget* pParent) : QWidget(pParent), mpEvent(), mpEventNameLineEdit(new QLineEdit(this)), mpEventDateEdit(new QDateEdit(this)), mpEventImportButton(new QPushButton("Import MSR", this)), mpEventSaveButton(new QPushButton("Save", this)), mpEventCancelButton(new QPushButton("Cancel", this)) { mpEventDateEdit->setCalendarPopup(true); mpEventDateEdit->setDate(QDate::currentDate()); QGridLayout* p_evemt_layout = new QGridLayout(this); // row 0 p_evemt_layout->addWidget(new QLabel("Name", this), 0, 0); p_evemt_layout->addWidget(mpEventNameLineEdit, 0, 1, 1, -1); // row 1 p_evemt_layout->addWidget(new QLabel("Date", this), 1, 0); p_evemt_layout->addWidget(mpEventDateEdit, 1, 1, 1, -1); // row 2 p_evemt_layout->addWidget(mpEventImportButton, 2, 1, 1, -1); // row 3 = empty, so it can consume all of the space when stretched p_evemt_layout->setRowStretch(3, 1); // row 4 p_evemt_layout->addWidget(mpEventSaveButton, 4, 0); // so it can consume the wrest of the space p_evemt_layout->setColumnStretch(1, 1); p_evemt_layout->addWidget(mpEventCancelButton, 4, 2); // disable until we click on an event setEnabled(false); mpEventNameLineEdit->setEnabled(false); mpEventDateEdit->setEnabled(false); mpEventImportButton->setEnabled(false); mpEventSaveButton->setEnabled(false); mpEventCancelButton->setEnabled(false); // capture save/cancel events connect(mpEventSaveButton, &QPushButton::clicked, this, &EventWidget::saveClicked); connect(mpEventCancelButton, &QPushButton::clicked, this, &EventWidget::cancelClicked); connect(mpEventImportButton, &QPushButton::clicked, this, &EventWidget::importClicked); } void EventWidget::setEvent(autoxtime::db::EventModel::ProtoPtr pEvent) { mpEvent = pEvent; bool b_event_item = mpEvent != nullptr; if (b_event_item) { // don't put the fake name in the text box if (pEvent->has_name()) { mpEventNameLineEdit->setText(QString::fromStdString(pEvent->name())); } else { mpEventNameLineEdit->clear(); } if (pEvent->has_date()) { QDate d = QDate::fromString(QString::fromStdString(pEvent->date()), Qt::ISODate); mpEventDateEdit->setDate(d); } } setEnabled(b_event_item); mpEventNameLineEdit->setEnabled(b_event_item); mpEventDateEdit->setEnabled(b_event_item); mpEventImportButton->setEnabled(b_event_item); mpEventSaveButton->setEnabled(b_event_item); mpEventCancelButton->setEnabled(b_event_item); } void EventWidget::setEvent(const QString& name, const QString& date) { autoxtime::db::EventModel::ProtoPtr p_event = std::make_shared<autoxtime::proto::Event>(); if (!name.isEmpty()) { p_event->set_name(name.toStdString()); } if (!date.isEmpty()) { p_event->set_date(date.toStdString()); } setEvent(p_event); } void EventWidget::clearEvent() { setEvent(autoxtime::db::EventModel::ProtoPtr()); } void EventWidget::saveClicked(bool checked) { autoxtime::proto::Event event; event.set_name(mpEventNameLineEdit->text().toStdString()); event.set_date(mpEventDateEdit->date().toString(Qt::ISODate).toStdString()); emit eventSaved(event); } void EventWidget::cancelClicked(bool checked) { // reset name edit mpEventNameLineEdit->clear(); // reset date edit mpEventDateEdit->setDate(QDate::currentDate()); emit eventCancelled(); } void EventWidget::importClicked(bool checked) { if (mpEvent) { EventImportDialog dialog(mpEvent, this); dialog.exec(); } } AUTOXTIME_UI_NAMESPACE_END
/*************************************************************************/ /* object.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "object.h" #include "core/class_db.h" #include "core/core_string_names.h" #include "core/message_queue.h" #include "core/os/os.h" #include "core/print_string.h" #include "core/resource.h" #include "core/script_language.h" #include "core/translation.h" #ifdef DEBUG_ENABLED struct _ObjectDebugLock { Object *obj; _ObjectDebugLock(Object *p_obj) { obj = p_obj; obj->_lock_index.ref(); } ~_ObjectDebugLock() { obj->_lock_index.unref(); } }; #define OBJ_DEBUG_LOCK _ObjectDebugLock _debug_lock(this); #else #define OBJ_DEBUG_LOCK #endif PropertyInfo::operator Dictionary() const { Dictionary d; d["name"] = name; d["class_name"] = class_name; d["type"] = type; d["hint"] = hint; d["hint_string"] = hint_string; d["usage"] = usage; return d; } PropertyInfo PropertyInfo::from_dict(const Dictionary &p_dict) { PropertyInfo pi; if (p_dict.has("type")) { pi.type = Variant::Type(int(p_dict["type"])); } if (p_dict.has("name")) { pi.name = p_dict["name"]; } if (p_dict.has("class_name")) { pi.class_name = p_dict["class_name"]; } if (p_dict.has("hint")) { pi.hint = PropertyHint(int(p_dict["hint"])); } if (p_dict.has("hint_string")) { pi.hint_string = p_dict["hint_string"]; } if (p_dict.has("usage")) { pi.usage = p_dict["usage"]; } return pi; } Array convert_property_list(const List<PropertyInfo> *p_list) { Array va; for (const List<PropertyInfo>::Element *E = p_list->front(); E; E = E->next()) { va.push_back(Dictionary(E->get())); } return va; } MethodInfo::operator Dictionary() const { Dictionary d; d["name"] = name; d["args"] = convert_property_list(&arguments); Array da; for (int i = 0; i < default_arguments.size(); i++) { da.push_back(default_arguments[i]); } d["default_args"] = da; d["flags"] = flags; d["id"] = id; Dictionary r = return_val; d["return"] = r; return d; } MethodInfo MethodInfo::from_dict(const Dictionary &p_dict) { MethodInfo mi; if (p_dict.has("name")) { mi.name = p_dict["name"]; } Array args; if (p_dict.has("args")) { args = p_dict["args"]; } for (int i = 0; i < args.size(); i++) { Dictionary d = args[i]; mi.arguments.push_back(PropertyInfo::from_dict(d)); } Array defargs; if (p_dict.has("default_args")) { defargs = p_dict["default_args"]; } for (int i = 0; i < defargs.size(); i++) { mi.default_arguments.push_back(defargs[i]); } if (p_dict.has("return")) { mi.return_val = PropertyInfo::from_dict(p_dict["return"]); } if (p_dict.has("flags")) { mi.flags = p_dict["flags"]; } return mi; } MethodInfo::MethodInfo() : flags(METHOD_FLAG_NORMAL) {} MethodInfo::MethodInfo(const String &p_name) : name(p_name), flags(METHOD_FLAG_NORMAL) { } MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1) : name(p_name), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); } MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2) : name(p_name), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); arguments.push_back(p_param2); } MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3) : name(p_name), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); } MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4) : name(p_name), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); arguments.push_back(p_param4); } MethodInfo::MethodInfo(const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5) : name(p_name), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); arguments.push_back(p_param4); arguments.push_back(p_param5); } MethodInfo::MethodInfo(Variant::Type ret) : flags(METHOD_FLAG_NORMAL) { return_val.type = ret; } MethodInfo::MethodInfo(Variant::Type ret, const String &p_name) : name(p_name), flags(METHOD_FLAG_NORMAL) { return_val.type = ret; } MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1) : name(p_name), flags(METHOD_FLAG_NORMAL) { return_val.type = ret; arguments.push_back(p_param1); } MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2) : name(p_name), flags(METHOD_FLAG_NORMAL) { return_val.type = ret; arguments.push_back(p_param1); arguments.push_back(p_param2); } MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3) : name(p_name), flags(METHOD_FLAG_NORMAL) { return_val.type = ret; arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); } MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4) : name(p_name), flags(METHOD_FLAG_NORMAL) { return_val.type = ret; arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); arguments.push_back(p_param4); } MethodInfo::MethodInfo(Variant::Type ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5) : name(p_name), flags(METHOD_FLAG_NORMAL) { return_val.type = ret; arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); arguments.push_back(p_param4); arguments.push_back(p_param5); } MethodInfo::MethodInfo(const PropertyInfo &p_ret, const String &p_name) : name(p_name), return_val(p_ret), flags(METHOD_FLAG_NORMAL) { } MethodInfo::MethodInfo(const PropertyInfo &p_ret, const String &p_name, const PropertyInfo &p_param1) : name(p_name), return_val(p_ret), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); } MethodInfo::MethodInfo(const PropertyInfo &p_ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2) : name(p_name), return_val(p_ret), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); arguments.push_back(p_param2); } MethodInfo::MethodInfo(const PropertyInfo &p_ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3) : name(p_name), return_val(p_ret), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); } MethodInfo::MethodInfo(const PropertyInfo &p_ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4) : name(p_name), return_val(p_ret), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); arguments.push_back(p_param4); } MethodInfo::MethodInfo(const PropertyInfo &p_ret, const String &p_name, const PropertyInfo &p_param1, const PropertyInfo &p_param2, const PropertyInfo &p_param3, const PropertyInfo &p_param4, const PropertyInfo &p_param5) : name(p_name), return_val(p_ret), flags(METHOD_FLAG_NORMAL) { arguments.push_back(p_param1); arguments.push_back(p_param2); arguments.push_back(p_param3); arguments.push_back(p_param4); arguments.push_back(p_param5); } Object::Connection::operator Variant() const { Dictionary d; d["signal"] = signal; d["callable"] = callable; d["flags"] = flags; d["binds"] = binds; return d; } bool Object::Connection::operator<(const Connection &p_conn) const { if (signal == p_conn.signal) { return callable < p_conn.callable; } else { return signal < p_conn.signal; } } Object::Connection::Connection(const Variant &p_variant) { Dictionary d = p_variant; if (d.has("signal")) { signal = d["signal"]; } if (d.has("callable")) { callable = d["callable"]; } if (d.has("flags")) { flags = d["flags"]; } if (d.has("binds")) { binds = d["binds"]; } } bool Object::_predelete() { _predelete_ok = 1; notification(NOTIFICATION_PREDELETE, true); if (_predelete_ok) { _class_ptr = nullptr; //must restore so destructors can access class ptr correctly } return _predelete_ok; } void Object::_postinitialize() { _class_ptr = _get_class_namev(); _initialize_classv(); notification(NOTIFICATION_POSTINITIALIZE); } void Object::get_valid_parents_static(List<String> *p_parents) { } void Object::_get_valid_parents_static(List<String> *p_parents) { } void Object::set(const StringName &p_name, const Variant &p_value, bool *r_valid) { #ifdef TOOLS_ENABLED _edited = true; #endif if (script_instance) { if (script_instance->set(p_name, p_value)) { if (r_valid) { *r_valid = true; } return; } } //try built-in setgetter { if (ClassDB::set_property(this, p_name, p_value, r_valid)) { /* if (r_valid) *r_valid=true; */ return; } } if (p_name == CoreStringNames::get_singleton()->_script) { set_script(p_value); if (r_valid) { *r_valid = true; } return; } else if (p_name == CoreStringNames::get_singleton()->_meta) { //set_meta(p_name,p_value); metadata = p_value.duplicate(); if (r_valid) { *r_valid = true; } return; } //something inside the object... :| bool success = _setv(p_name, p_value); if (success) { if (r_valid) { *r_valid = true; } return; } { bool valid; setvar(p_name, p_value, &valid); if (valid) { if (r_valid) { *r_valid = true; } return; } } #ifdef TOOLS_ENABLED if (script_instance) { bool valid; script_instance->property_set_fallback(p_name, p_value, &valid); if (valid) { if (r_valid) { *r_valid = true; } return; } } #endif if (r_valid) { *r_valid = false; } } Variant Object::get(const StringName &p_name, bool *r_valid) const { Variant ret; if (script_instance) { if (script_instance->get(p_name, ret)) { if (r_valid) { *r_valid = true; } return ret; } } //try built-in setgetter { if (ClassDB::get_property(const_cast<Object *>(this), p_name, ret)) { if (r_valid) { *r_valid = true; } return ret; } } if (p_name == CoreStringNames::get_singleton()->_script) { ret = get_script(); if (r_valid) { *r_valid = true; } return ret; } else if (p_name == CoreStringNames::get_singleton()->_meta) { ret = metadata; if (r_valid) { *r_valid = true; } return ret; } else { //something inside the object... :| bool success = _getv(p_name, ret); if (success) { if (r_valid) { *r_valid = true; } return ret; } //if nothing else, use getvar { bool valid; ret = getvar(p_name, &valid); if (valid) { if (r_valid) { *r_valid = true; } return ret; } } #ifdef TOOLS_ENABLED if (script_instance) { bool valid; ret = script_instance->property_get_fallback(p_name, &valid); if (valid) { if (r_valid) { *r_valid = true; } return ret; } } #endif if (r_valid) { *r_valid = false; } return Variant(); } } void Object::set_indexed(const Vector<StringName> &p_names, const Variant &p_value, bool *r_valid) { if (p_names.empty()) { if (r_valid) { *r_valid = false; } return; } if (p_names.size() == 1) { set(p_names[0], p_value, r_valid); return; } bool valid = false; if (!r_valid) { r_valid = &valid; } List<Variant> value_stack; value_stack.push_back(get(p_names[0], r_valid)); if (!*r_valid) { value_stack.clear(); return; } for (int i = 1; i < p_names.size() - 1; i++) { value_stack.push_back(value_stack.back()->get().get_named(p_names[i], r_valid)); if (!*r_valid) { value_stack.clear(); return; } } value_stack.push_back(p_value); // p_names[p_names.size() - 1] for (int i = p_names.size() - 1; i > 0; i--) { value_stack.back()->prev()->get().set_named(p_names[i], value_stack.back()->get(), r_valid); value_stack.pop_back(); if (!*r_valid) { value_stack.clear(); return; } } set(p_names[0], value_stack.back()->get(), r_valid); value_stack.pop_back(); ERR_FAIL_COND(!value_stack.empty()); } Variant Object::get_indexed(const Vector<StringName> &p_names, bool *r_valid) const { if (p_names.empty()) { if (r_valid) { *r_valid = false; } return Variant(); } bool valid = false; Variant current_value = get(p_names[0], &valid); for (int i = 1; i < p_names.size(); i++) { current_value = current_value.get_named(p_names[i], &valid); if (!valid) { break; } } if (r_valid) { *r_valid = valid; } return current_value; } void Object::get_property_list(List<PropertyInfo> *p_list, bool p_reversed) const { if (script_instance && p_reversed) { p_list->push_back(PropertyInfo(Variant::NIL, "Script Variables", PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY)); script_instance->get_property_list(p_list); } _get_property_listv(p_list, p_reversed); if (!is_class("Script")) { // can still be set, but this is for userfriendlyness #ifdef TOOLS_ENABLED p_list->push_back(PropertyInfo(Variant::NIL, "Script", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_GROUP)); #endif p_list->push_back(PropertyInfo(Variant::OBJECT, "script", PROPERTY_HINT_RESOURCE_TYPE, "Script", PROPERTY_USAGE_DEFAULT)); } if (!metadata.empty()) { p_list->push_back(PropertyInfo(Variant::DICTIONARY, "__meta__", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL)); } if (script_instance && !p_reversed) { p_list->push_back(PropertyInfo(Variant::NIL, "Script Variables", PROPERTY_HINT_NONE, String(), PROPERTY_USAGE_CATEGORY)); script_instance->get_property_list(p_list); } } void Object::_validate_property(PropertyInfo &property) const { } void Object::get_method_list(List<MethodInfo> *p_list) const { ClassDB::get_method_list(get_class_name(), p_list); if (script_instance) { script_instance->get_method_list(p_list); } } Variant Object::_call_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) { if (p_argcount < 1) { r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.argument = 0; return Variant(); } if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; r_error.argument = 0; r_error.expected = Variant::STRING_NAME; return Variant(); } StringName method = *p_args[0]; return call(method, &p_args[1], p_argcount - 1, r_error); } Variant Object::_call_deferred_bind(const Variant **p_args, int p_argcount, Callable::CallError &r_error) { if (p_argcount < 1) { r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; r_error.argument = 0; return Variant(); } if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; r_error.argument = 0; r_error.expected = Variant::STRING_NAME; return Variant(); } r_error.error = Callable::CallError::CALL_OK; StringName method = *p_args[0]; MessageQueue::get_singleton()->push_call(get_instance_id(), method, &p_args[1], p_argcount - 1, true); return Variant(); } bool Object::has_method(const StringName &p_method) const { if (p_method == CoreStringNames::get_singleton()->_free) { return true; } if (script_instance && script_instance->has_method(p_method)) { return true; } MethodBind *method = ClassDB::get_method(get_class_name(), p_method); return method != nullptr; } Variant Object::getvar(const Variant &p_key, bool *r_valid) const { if (r_valid) { *r_valid = false; } return Variant(); } void Object::setvar(const Variant &p_key, const Variant &p_value, bool *r_valid) { if (r_valid) { *r_valid = false; } } Variant Object::callv(const StringName &p_method, const Array &p_args) { const Variant **argptrs = nullptr; if (p_args.size() > 0) { argptrs = (const Variant **)alloca(sizeof(Variant *) * p_args.size()); for (int i = 0; i < p_args.size(); i++) { argptrs[i] = &p_args[i]; } } Callable::CallError ce; Variant ret = call(p_method, argptrs, p_args.size(), ce); if (ce.error != Callable::CallError::CALL_OK) { ERR_FAIL_V_MSG(Variant(), "Error calling method from 'callv': " + Variant::get_call_error_text(this, p_method, argptrs, p_args.size(), ce) + "."); } return ret; } Variant Object::call(const StringName &p_name, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc = 0; for (int i = 0; i < VARIANT_ARG_MAX; i++) { if (argptr[i]->get_type() == Variant::NIL) { break; } argc++; } Callable::CallError error; Variant ret = call(p_name, argptr, argc, error); return ret; } Variant Object::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) { r_error.error = Callable::CallError::CALL_OK; if (p_method == CoreStringNames::get_singleton()->_free) { //free must be here, before anything, always ready #ifdef DEBUG_ENABLED if (p_argcount != 0) { r_error.argument = 0; r_error.error = Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS; return Variant(); } if (Object::cast_to<Reference>(this)) { r_error.argument = 0; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; ERR_FAIL_V_MSG(Variant(), "Can't 'free' a reference."); } if (_lock_index.get() > 1) { r_error.argument = 0; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; ERR_FAIL_V_MSG(Variant(), "Object is locked and can't be freed."); } #endif //must be here, must be before everything, memdelete(this); r_error.error = Callable::CallError::CALL_OK; return Variant(); } Variant ret; OBJ_DEBUG_LOCK if (script_instance) { ret = script_instance->call(p_method, p_args, p_argcount, r_error); //force jumptable switch (r_error.error) { case Callable::CallError::CALL_OK: return ret; case Callable::CallError::CALL_ERROR_INVALID_METHOD: break; case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS: case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS: return ret; case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL: { } } } MethodBind *method = ClassDB::get_method(get_class_name(), p_method); if (method) { ret = method->call(this, p_args, p_argcount, r_error); } else { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; } return ret; } void Object::notification(int p_notification, bool p_reversed) { _notificationv(p_notification, p_reversed); if (script_instance) { script_instance->notification(p_notification); } } String Object::to_string() { if (script_instance) { bool valid; String ret = script_instance->to_string(&valid); if (valid) { return ret; } } return "[" + get_class() + ":" + itos(get_instance_id()) + "]"; } void Object::_changed_callback(Object *p_changed, const char *p_prop) { } void Object::add_change_receptor(Object *p_receptor) { change_receptors.insert(p_receptor); } void Object::remove_change_receptor(Object *p_receptor) { change_receptors.erase(p_receptor); } void Object::property_list_changed_notify() { _change_notify(); } void Object::cancel_delete() { _predelete_ok = true; } void Object::set_script_and_instance(const Variant &p_script, ScriptInstance *p_instance) { //this function is not meant to be used in any of these ways ERR_FAIL_COND(p_script.is_null()); ERR_FAIL_COND(!p_instance); ERR_FAIL_COND(script_instance != nullptr || !script.is_null()); script = p_script; script_instance = p_instance; } void Object::set_script(const Variant &p_script) { if (script == p_script) { return; } if (script_instance) { memdelete(script_instance); script_instance = nullptr; } script = p_script; Ref<Script> s = script; if (!s.is_null()) { if (s->can_instance()) { OBJ_DEBUG_LOCK script_instance = s->instance_create(this); } else if (Engine::get_singleton()->is_editor_hint()) { OBJ_DEBUG_LOCK script_instance = s->placeholder_instance_create(this); } } _change_notify(); //scripts may add variables, so refresh is desired emit_signal(CoreStringNames::get_singleton()->script_changed); } void Object::set_script_instance(ScriptInstance *p_instance) { if (script_instance == p_instance) { return; } if (script_instance) { memdelete(script_instance); } script_instance = p_instance; if (p_instance) { script = p_instance->get_script(); } else { script = Variant(); } } Variant Object::get_script() const { return script; } bool Object::has_meta(const String &p_name) const { return metadata.has(p_name); } void Object::set_meta(const String &p_name, const Variant &p_value) { if (p_value.get_type() == Variant::NIL) { metadata.erase(p_name); return; } metadata[p_name] = p_value; } Variant Object::get_meta(const String &p_name) const { ERR_FAIL_COND_V(!metadata.has(p_name), Variant()); return metadata[p_name]; } void Object::remove_meta(const String &p_name) { metadata.erase(p_name); } Array Object::_get_property_list_bind() const { List<PropertyInfo> lpi; get_property_list(&lpi); return convert_property_list(&lpi); } Array Object::_get_method_list_bind() const { List<MethodInfo> ml; get_method_list(&ml); Array ret; for (List<MethodInfo>::Element *E = ml.front(); E; E = E->next()) { Dictionary d = E->get(); //va.push_back(d); ret.push_back(d); } return ret; } Vector<String> Object::_get_meta_list_bind() const { Vector<String> _metaret; List<Variant> keys; metadata.get_key_list(&keys); for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _metaret.push_back(E->get()); } return _metaret; } void Object::get_meta_list(List<String> *p_list) const { List<Variant> keys; metadata.get_key_list(&keys); for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { p_list->push_back(E->get()); } } void Object::add_user_signal(const MethodInfo &p_signal) { ERR_FAIL_COND_MSG(p_signal.name == "", "Signal name cannot be empty."); ERR_FAIL_COND_MSG(ClassDB::has_signal(get_class_name(), p_signal.name), "User signal's name conflicts with a built-in signal of '" + get_class_name() + "'."); ERR_FAIL_COND_MSG(signal_map.has(p_signal.name), "Trying to add already existing signal '" + p_signal.name + "'."); SignalData s; s.user = p_signal; signal_map[p_signal.name] = s; } bool Object::_has_user_signal(const StringName &p_name) const { if (!signal_map.has(p_name)) { return false; } return signal_map[p_name].user.name.length() > 0; } struct _ObjectSignalDisconnectData { StringName signal; Callable callable; }; Variant Object::_emit_signal(const Variant **p_args, int p_argcount, Callable::CallError &r_error) { r_error.error = Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS; ERR_FAIL_COND_V(p_argcount < 1, Variant()); if (p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; r_error.argument = 0; r_error.expected = Variant::STRING_NAME; ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING, Variant()); } r_error.error = Callable::CallError::CALL_OK; StringName signal = *p_args[0]; const Variant **args = nullptr; int argc = p_argcount - 1; if (argc) { args = &p_args[1]; } emit_signal(signal, args, argc); return Variant(); } Error Object::emit_signal(const StringName &p_name, const Variant **p_args, int p_argcount) { if (_block_signals) { return ERR_CANT_ACQUIRE_RESOURCE; //no emit, signals blocked } SignalData *s = signal_map.getptr(p_name); if (!s) { #ifdef DEBUG_ENABLED bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_name); //check in script ERR_FAIL_COND_V_MSG(!signal_is_valid && !script.is_null() && !Ref<Script>(script)->has_script_signal(p_name), ERR_UNAVAILABLE, "Can't emit non-existing signal " + String("\"") + p_name + "\"."); #endif //not connected? just return return ERR_UNAVAILABLE; } List<_ObjectSignalDisconnectData> disconnect_data; //copy on write will ensure that disconnecting the signal or even deleting the object will not affect the signal calling. //this happens automatically and will not change the performance of calling. //awesome, isn't it? VMap<Callable, SignalData::Slot> slot_map = s->slot_map; int ssize = slot_map.size(); OBJ_DEBUG_LOCK Vector<const Variant *> bind_mem; Error err = OK; for (int i = 0; i < ssize; i++) { const Connection &c = slot_map.getv(i).conn; Object *target = c.callable.get_object(); if (!target) { // Target might have been deleted during signal callback, this is expected and OK. continue; } const Variant **args = p_args; int argc = p_argcount; if (c.binds.size()) { //handle binds bind_mem.resize(p_argcount + c.binds.size()); for (int j = 0; j < p_argcount; j++) { bind_mem.write[j] = p_args[j]; } for (int j = 0; j < c.binds.size(); j++) { bind_mem.write[p_argcount + j] = &c.binds[j]; } args = (const Variant **)bind_mem.ptr(); argc = bind_mem.size(); } if (c.flags & CONNECT_DEFERRED) { MessageQueue::get_singleton()->push_callable(c.callable, args, argc, true); } else { Callable::CallError ce; _emitting = true; Variant ret; c.callable.call(args, argc, ret, ce); _emitting = false; if (ce.error != Callable::CallError::CALL_OK) { #ifdef DEBUG_ENABLED if (c.flags & CONNECT_PERSIST && Engine::get_singleton()->is_editor_hint() && (script.is_null() || !Ref<Script>(script)->is_tool())) { continue; } #endif if (ce.error == Callable::CallError::CALL_ERROR_INVALID_METHOD && !ClassDB::class_exists(target->get_class_name())) { //most likely object is not initialized yet, do not throw error. } else { ERR_PRINT("Error calling from signal '" + String(p_name) + "' to callable: " + Variant::get_callable_error_text(c.callable, args, argc, ce) + "."); err = ERR_METHOD_NOT_FOUND; } } } bool disconnect = c.flags & CONNECT_ONESHOT; #ifdef TOOLS_ENABLED if (disconnect && (c.flags & CONNECT_PERSIST) && Engine::get_singleton()->is_editor_hint()) { //this signal was connected from the editor, and is being edited. just don't disconnect for now disconnect = false; } #endif if (disconnect) { _ObjectSignalDisconnectData dd; dd.signal = p_name; dd.callable = c.callable; disconnect_data.push_back(dd); } } while (!disconnect_data.empty()) { const _ObjectSignalDisconnectData &dd = disconnect_data.front()->get(); _disconnect(dd.signal, dd.callable); disconnect_data.pop_front(); } return err; } Error Object::emit_signal(const StringName &p_name, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc = 0; for (int i = 0; i < VARIANT_ARG_MAX; i++) { if (argptr[i]->get_type() == Variant::NIL) { break; } argc++; } return emit_signal(p_name, argptr, argc); } void Object::_add_user_signal(const String &p_name, const Array &p_args) { // this version of add_user_signal is meant to be used from scripts or external apis // without access to ADD_SIGNAL in bind_methods // added events are per instance, as opposed to the other ones, which are global MethodInfo mi; mi.name = p_name; for (int i = 0; i < p_args.size(); i++) { Dictionary d = p_args[i]; PropertyInfo param; if (d.has("name")) { param.name = d["name"]; } if (d.has("type")) { param.type = (Variant::Type)(int)d["type"]; } mi.arguments.push_back(param); } add_user_signal(mi); } Array Object::_get_signal_list() const { List<MethodInfo> signal_list; get_signal_list(&signal_list); Array ret; for (List<MethodInfo>::Element *E = signal_list.front(); E; E = E->next()) { ret.push_back(Dictionary(E->get())); } return ret; } Array Object::_get_signal_connection_list(const String &p_signal) const { List<Connection> conns; get_all_signal_connections(&conns); Array ret; for (List<Connection>::Element *E = conns.front(); E; E = E->next()) { Connection &c = E->get(); if (c.signal.get_name() == p_signal) { ret.push_back(c); } } return ret; } Array Object::_get_incoming_connections() const { Array ret; int connections_amount = connections.size(); for (int idx_conn = 0; idx_conn < connections_amount; idx_conn++) { ret.push_back(connections[idx_conn]); } return ret; } bool Object::has_signal(const StringName &p_name) const { if (!script.is_null()) { Ref<Script> scr = script; if (scr.is_valid() && scr->has_script_signal(p_name)) { return true; } } if (ClassDB::has_signal(get_class_name(), p_name)) { return true; } if (_has_user_signal(p_name)) { return true; } return false; } void Object::get_signal_list(List<MethodInfo> *p_signals) const { if (!script.is_null()) { Ref<Script> scr = script; if (scr.is_valid()) { scr->get_script_signal_list(p_signals); } } ClassDB::get_signal_list(get_class_name(), p_signals); //find maybe usersignals? const StringName *S = nullptr; while ((S = signal_map.next(S))) { if (signal_map[*S].user.name != "") { //user signal p_signals->push_back(signal_map[*S].user); } } } void Object::get_all_signal_connections(List<Connection> *p_connections) const { const StringName *S = nullptr; while ((S = signal_map.next(S))) { const SignalData *s = &signal_map[*S]; for (int i = 0; i < s->slot_map.size(); i++) { p_connections->push_back(s->slot_map.getv(i).conn); } } } void Object::get_signal_connection_list(const StringName &p_signal, List<Connection> *p_connections) const { const SignalData *s = signal_map.getptr(p_signal); if (!s) { return; //nothing } for (int i = 0; i < s->slot_map.size(); i++) { p_connections->push_back(s->slot_map.getv(i).conn); } } int Object::get_persistent_signal_connection_count() const { int count = 0; const StringName *S = nullptr; while ((S = signal_map.next(S))) { const SignalData *s = &signal_map[*S]; for (int i = 0; i < s->slot_map.size(); i++) { if (s->slot_map.getv(i).conn.flags & CONNECT_PERSIST) { count += 1; } } } return count; } void Object::get_signals_connected_to_this(List<Connection> *p_connections) const { for (const List<Connection>::Element *E = connections.front(); E; E = E->next()) { p_connections->push_back(E->get()); } } Error Object::connect_compat(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method, const Vector<Variant> &p_binds, uint32_t p_flags) { return connect(p_signal, Callable(p_to_object, p_to_method), p_binds, p_flags); } Error Object::connect(const StringName &p_signal, const Callable &p_callable, const Vector<Variant> &p_binds, uint32_t p_flags) { ERR_FAIL_COND_V(p_callable.is_null(), ERR_INVALID_PARAMETER); Object *target_object = p_callable.get_object(); ERR_FAIL_COND_V(!target_object, ERR_INVALID_PARAMETER); SignalData *s = signal_map.getptr(p_signal); if (!s) { bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal); //check in script if (!signal_is_valid && !script.is_null()) { if (Ref<Script>(script)->has_script_signal(p_signal)) { signal_is_valid = true; } #ifdef TOOLS_ENABLED else { //allow connecting signals anyway if script is invalid, see issue #17070 if (!Ref<Script>(script)->is_valid()) { signal_is_valid = true; } } #endif } ERR_FAIL_COND_V_MSG(!signal_is_valid, ERR_INVALID_PARAMETER, "In Object of type '" + String(get_class()) + "': Attempt to connect nonexistent signal '" + p_signal + "' to callable '" + p_callable + "'."); signal_map[p_signal] = SignalData(); s = &signal_map[p_signal]; } Callable target = p_callable; if (s->slot_map.has(target)) { if (p_flags & CONNECT_REFERENCE_COUNTED) { s->slot_map[target].reference_count++; return OK; } else { ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, "Signal '" + p_signal + "' is already connected to given callable '" + p_callable + "' in that object."); } } SignalData::Slot slot; Connection conn; conn.callable = target; conn.signal = ::Signal(this, p_signal); conn.flags = p_flags; conn.binds = p_binds; slot.conn = conn; slot.cE = target_object->connections.push_back(conn); if (p_flags & CONNECT_REFERENCE_COUNTED) { slot.reference_count = 1; } s->slot_map[target] = slot; return OK; } bool Object::is_connected_compat(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method) const { return is_connected(p_signal, Callable(p_to_object, p_to_method)); } bool Object::is_connected(const StringName &p_signal, const Callable &p_callable) const { ERR_FAIL_COND_V(p_callable.is_null(), false); const SignalData *s = signal_map.getptr(p_signal); if (!s) { bool signal_is_valid = ClassDB::has_signal(get_class_name(), p_signal); if (signal_is_valid) { return false; } if (!script.is_null() && Ref<Script>(script)->has_script_signal(p_signal)) { return false; } ERR_FAIL_V_MSG(false, "Nonexistent signal: " + p_signal + "."); } Callable target = p_callable; return s->slot_map.has(target); //const Map<Signal::Target,Signal::Slot>::Element *E = s->slot_map.find(target); //return (E!=nullptr ); } void Object::disconnect_compat(const StringName &p_signal, Object *p_to_object, const StringName &p_to_method) { _disconnect(p_signal, Callable(p_to_object, p_to_method)); } void Object::disconnect(const StringName &p_signal, const Callable &p_callable) { _disconnect(p_signal, p_callable); } void Object::_disconnect(const StringName &p_signal, const Callable &p_callable, bool p_force) { ERR_FAIL_COND(p_callable.is_null()); Object *target_object = p_callable.get_object(); ERR_FAIL_COND(!target_object); SignalData *s = signal_map.getptr(p_signal); ERR_FAIL_COND_MSG(!s, vformat("Nonexistent signal '%s' in %s.", p_signal, to_string())); ERR_FAIL_COND_MSG(!s->slot_map.has(p_callable), "Disconnecting nonexistent signal '" + p_signal + "', callable: " + p_callable + "."); SignalData::Slot *slot = &s->slot_map[p_callable]; if (!p_force) { slot->reference_count--; // by default is zero, if it was not referenced it will go below it if (slot->reference_count >= 0) { return; } } target_object->connections.erase(slot->cE); s->slot_map.erase(p_callable); if (s->slot_map.empty() && ClassDB::has_signal(get_class_name(), p_signal)) { //not user signal, delete signal_map.erase(p_signal); } } void Object::_set_bind(const String &p_set, const Variant &p_value) { set(p_set, p_value); } Variant Object::_get_bind(const String &p_name) const { return get(p_name); } void Object::_set_indexed_bind(const NodePath &p_name, const Variant &p_value) { set_indexed(p_name.get_as_property_path().get_subnames(), p_value); } Variant Object::_get_indexed_bind(const NodePath &p_name) const { return get_indexed(p_name.get_as_property_path().get_subnames()); } void Object::initialize_class() { static bool initialized = false; if (initialized) { return; } ClassDB::_add_class<Object>(); _bind_methods(); initialized = true; } StringName Object::tr(const StringName &p_message) const { if (!_can_translate || !TranslationServer::get_singleton()) { return p_message; } return TranslationServer::get_singleton()->translate(p_message); } void Object::_clear_internal_resource_paths(const Variant &p_var) { switch (p_var.get_type()) { case Variant::OBJECT: { RES r = p_var; if (!r.is_valid()) { return; } if (!r->get_path().begins_with("res://") || r->get_path().find("::") == -1) { return; //not an internal resource } Object *object = p_var; if (!object) { return; } r->set_path(""); r->clear_internal_resource_paths(); } break; case Variant::ARRAY: { Array a = p_var; for (int i = 0; i < a.size(); i++) { _clear_internal_resource_paths(a[i]); } } break; case Variant::DICTIONARY: { Dictionary d = p_var; List<Variant> keys; d.get_key_list(&keys); for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { _clear_internal_resource_paths(E->get()); _clear_internal_resource_paths(d[E->get()]); } } break; default: { } } } #ifdef TOOLS_ENABLED void Object::editor_set_section_unfold(const String &p_section, bool p_unfolded) { set_edited(true); if (p_unfolded) { editor_section_folding.insert(p_section); } else { editor_section_folding.erase(p_section); } } bool Object::editor_is_section_unfolded(const String &p_section) { return editor_section_folding.has(p_section); } #endif void Object::clear_internal_resource_paths() { List<PropertyInfo> pinfo; get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { _clear_internal_resource_paths(get(E->get().name)); } } void Object::_bind_methods() { ClassDB::bind_method(D_METHOD("get_class"), &Object::get_class); ClassDB::bind_method(D_METHOD("is_class", "class"), &Object::is_class); ClassDB::bind_method(D_METHOD("set", "property", "value"), &Object::_set_bind); ClassDB::bind_method(D_METHOD("get", "property"), &Object::_get_bind); ClassDB::bind_method(D_METHOD("set_indexed", "property", "value"), &Object::_set_indexed_bind); ClassDB::bind_method(D_METHOD("get_indexed", "property"), &Object::_get_indexed_bind); ClassDB::bind_method(D_METHOD("get_property_list"), &Object::_get_property_list_bind); ClassDB::bind_method(D_METHOD("get_method_list"), &Object::_get_method_list_bind); ClassDB::bind_method(D_METHOD("notification", "what", "reversed"), &Object::notification, DEFVAL(false)); ClassDB::bind_method(D_METHOD("to_string"), &Object::to_string); ClassDB::bind_method(D_METHOD("get_instance_id"), &Object::get_instance_id); ClassDB::bind_method(D_METHOD("set_script", "script"), &Object::set_script); ClassDB::bind_method(D_METHOD("get_script"), &Object::get_script); ClassDB::bind_method(D_METHOD("set_meta", "name", "value"), &Object::set_meta); ClassDB::bind_method(D_METHOD("remove_meta", "name"), &Object::remove_meta); ClassDB::bind_method(D_METHOD("get_meta", "name"), &Object::get_meta); ClassDB::bind_method(D_METHOD("has_meta", "name"), &Object::has_meta); ClassDB::bind_method(D_METHOD("get_meta_list"), &Object::_get_meta_list_bind); ClassDB::bind_method(D_METHOD("add_user_signal", "signal", "arguments"), &Object::_add_user_signal, DEFVAL(Array())); ClassDB::bind_method(D_METHOD("has_user_signal", "signal"), &Object::_has_user_signal); { MethodInfo mi; mi.name = "emit_signal"; mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "signal")); ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "emit_signal", &Object::_emit_signal, mi, varray(), false); } { MethodInfo mi; mi.name = "call"; mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method")); ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call", &Object::_call_bind, mi); } { MethodInfo mi; mi.name = "call_deferred"; mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method")); ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_deferred", &Object::_call_deferred_bind, mi, varray(), false); } ClassDB::bind_method(D_METHOD("set_deferred", "property", "value"), &Object::set_deferred); ClassDB::bind_method(D_METHOD("callv", "method", "arg_array"), &Object::callv); ClassDB::bind_method(D_METHOD("has_method", "method"), &Object::has_method); ClassDB::bind_method(D_METHOD("has_signal", "signal"), &Object::has_signal); ClassDB::bind_method(D_METHOD("get_signal_list"), &Object::_get_signal_list); ClassDB::bind_method(D_METHOD("get_signal_connection_list", "signal"), &Object::_get_signal_connection_list); ClassDB::bind_method(D_METHOD("get_incoming_connections"), &Object::_get_incoming_connections); ClassDB::bind_method(D_METHOD("connect", "signal", "callable", "binds", "flags"), &Object::connect, DEFVAL(Array()), DEFVAL(0)); ClassDB::bind_method(D_METHOD("disconnect", "signal", "callable"), &Object::disconnect); ClassDB::bind_method(D_METHOD("is_connected", "signal", "callable"), &Object::is_connected); ClassDB::bind_method(D_METHOD("set_block_signals", "enable"), &Object::set_block_signals); ClassDB::bind_method(D_METHOD("is_blocking_signals"), &Object::is_blocking_signals); ClassDB::bind_method(D_METHOD("property_list_changed_notify"), &Object::property_list_changed_notify); ClassDB::bind_method(D_METHOD("set_message_translation", "enable"), &Object::set_message_translation); ClassDB::bind_method(D_METHOD("can_translate_messages"), &Object::can_translate_messages); ClassDB::bind_method(D_METHOD("tr", "message"), &Object::tr); ClassDB::bind_method(D_METHOD("is_queued_for_deletion"), &Object::is_queued_for_deletion); ClassDB::add_virtual_method("Object", MethodInfo("free"), false); ADD_SIGNAL(MethodInfo("script_changed")); BIND_VMETHOD(MethodInfo("_notification", PropertyInfo(Variant::INT, "what"))); BIND_VMETHOD(MethodInfo(Variant::BOOL, "_set", PropertyInfo(Variant::STRING_NAME, "property"), PropertyInfo(Variant::NIL, "value"))); #ifdef TOOLS_ENABLED MethodInfo miget("_get", PropertyInfo(Variant::STRING_NAME, "property")); miget.return_val.name = "Variant"; miget.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; BIND_VMETHOD(miget); MethodInfo plget("_get_property_list"); plget.return_val.type = Variant::ARRAY; BIND_VMETHOD(plget); #endif BIND_VMETHOD(MethodInfo("_init")); BIND_VMETHOD(MethodInfo(Variant::STRING, "_to_string")); BIND_CONSTANT(NOTIFICATION_POSTINITIALIZE); BIND_CONSTANT(NOTIFICATION_PREDELETE); BIND_ENUM_CONSTANT(CONNECT_DEFERRED); BIND_ENUM_CONSTANT(CONNECT_PERSIST); BIND_ENUM_CONSTANT(CONNECT_ONESHOT); BIND_ENUM_CONSTANT(CONNECT_REFERENCE_COUNTED); } void Object::call_deferred(const StringName &p_method, VARIANT_ARG_DECLARE) { MessageQueue::get_singleton()->push_call(this, p_method, VARIANT_ARG_PASS); } void Object::set_deferred(const StringName &p_property, const Variant &p_value) { MessageQueue::get_singleton()->push_set(this, p_property, p_value); } void Object::set_block_signals(bool p_block) { _block_signals = p_block; } bool Object::is_blocking_signals() const { return _block_signals; } void Object::get_translatable_strings(List<String> *p_strings) const { List<PropertyInfo> plist; get_property_list(&plist); for (List<PropertyInfo>::Element *E = plist.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_INTERNATIONALIZED)) { continue; } String text = get(E->get().name); if (text == "") { continue; } p_strings->push_back(text); } } Variant::Type Object::get_static_property_type(const StringName &p_property, bool *r_valid) const { bool valid; Variant::Type t = ClassDB::get_property_type(get_class_name(), p_property, &valid); if (valid) { if (r_valid) { *r_valid = true; } return t; } if (get_script_instance()) { return get_script_instance()->get_property_type(p_property, r_valid); } if (r_valid) { *r_valid = false; } return Variant::NIL; } Variant::Type Object::get_static_property_type_indexed(const Vector<StringName> &p_path, bool *r_valid) const { if (p_path.size() == 0) { if (r_valid) { *r_valid = false; } return Variant::NIL; } bool valid = false; Variant::Type t = get_static_property_type(p_path[0], &valid); if (!valid) { if (r_valid) { *r_valid = false; } return Variant::NIL; } Callable::CallError ce; Variant check = Variant::construct(t, nullptr, 0, ce); for (int i = 1; i < p_path.size(); i++) { if (check.get_type() == Variant::OBJECT || check.get_type() == Variant::DICTIONARY || check.get_type() == Variant::ARRAY) { // We cannot be sure about the type of properties this types can have if (r_valid) { *r_valid = false; } return Variant::NIL; } check = check.get_named(p_path[i], &valid); if (!valid) { if (r_valid) { *r_valid = false; } return Variant::NIL; } } if (r_valid) { *r_valid = true; } return check.get_type(); } bool Object::is_queued_for_deletion() const { return _is_queued_for_deletion; } #ifdef TOOLS_ENABLED void Object::set_edited(bool p_edited) { _edited = p_edited; _edited_version++; } bool Object::is_edited() const { return _edited; } uint32_t Object::get_edited_version() const { return _edited_version; } #endif void *Object::get_script_instance_binding(int p_script_language_index) { #ifdef DEBUG_ENABLED ERR_FAIL_INDEX_V(p_script_language_index, MAX_SCRIPT_INSTANCE_BINDINGS, nullptr); #endif //it's up to the script language to make this thread safe, if the function is called twice due to threads being out of syncro //just return the same pointer. //if you want to put a big lock in the entire function and keep allocated pointers in a map or something, feel free to do it //as it should not really affect performance much (won't be called too often), as in far most caes the condition below will be false afterwards if (!_script_instance_bindings[p_script_language_index]) { void *script_data = ScriptServer::get_language(p_script_language_index)->alloc_instance_binding_data(this); if (script_data) { atomic_increment(&instance_binding_count); _script_instance_bindings[p_script_language_index] = script_data; } } return _script_instance_bindings[p_script_language_index]; } bool Object::has_script_instance_binding(int p_script_language_index) { return _script_instance_bindings[p_script_language_index] != nullptr; } void Object::set_script_instance_binding(int p_script_language_index, void *p_data) { #ifdef DEBUG_ENABLED CRASH_COND(_script_instance_bindings[p_script_language_index] != nullptr); #endif _script_instance_bindings[p_script_language_index] = p_data; } void Object::_construct_object(bool p_reference) { type_is_reference = p_reference; _instance_id = ObjectDB::add_instance(this); memset(_script_instance_bindings, 0, sizeof(void *) * MAX_SCRIPT_INSTANCE_BINDINGS); #ifdef DEBUG_ENABLED _lock_index.init(1); #endif } Object::Object(bool p_reference) { _construct_object(p_reference); } Object::Object() { _construct_object(false); } Object::~Object() { if (script_instance) { memdelete(script_instance); } script_instance = nullptr; const StringName *S = nullptr; if (_emitting) { //@todo this may need to actually reach the debugger prioritarily somehow because it may crash before ERR_PRINT("Object " + to_string() + " was freed or unreferenced while a signal is being emitted from it. Try connecting to the signal using 'CONNECT_DEFERRED' flag, or use queue_free() to free the object (if this object is a Node) to avoid this error and potential crashes."); } while ((S = signal_map.next(nullptr))) { SignalData *s = &signal_map[*S]; //brute force disconnect for performance int slot_count = s->slot_map.size(); const VMap<Callable, SignalData::Slot>::Pair *slot_list = s->slot_map.get_array(); for (int i = 0; i < slot_count; i++) { slot_list[i].value.conn.callable.get_object()->connections.erase(slot_list[i].value.cE); } signal_map.erase(*S); } //signals from nodes that connect to this node while (connections.size()) { Connection c = connections.front()->get(); c.signal.get_object()->_disconnect(c.signal.get_name(), c.callable, true); } ObjectDB::remove_instance(this); _instance_id = ObjectID(); _predelete_ok = 2; if (!ScriptServer::are_languages_finished()) { for (int i = 0; i < MAX_SCRIPT_INSTANCE_BINDINGS; i++) { if (_script_instance_bindings[i]) { ScriptServer::get_language(i)->free_instance_binding_data(_script_instance_bindings[i]); } } } } bool predelete_handler(Object *p_object) { return p_object->_predelete(); } void postinitialize_handler(Object *p_object) { p_object->_postinitialize(); } void ObjectDB::debug_objects(DebugFunc p_func) { spin_lock.lock(); for (uint32_t i = 0; i < slot_count; i++) { uint32_t slot = object_slots[i].next_free; p_func(object_slots[slot].object); } spin_lock.unlock(); } void Object::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const { } SpinLock ObjectDB::spin_lock; uint32_t ObjectDB::slot_count = 0; uint32_t ObjectDB::slot_max = 0; ObjectDB::ObjectSlot *ObjectDB::object_slots = nullptr; uint64_t ObjectDB::validator_counter = 0; int ObjectDB::get_object_count() { return slot_count; } ObjectID ObjectDB::add_instance(Object *p_object) { spin_lock.lock(); if (unlikely(slot_count == slot_max)) { CRASH_COND(slot_count == (1 << OBJECTDB_SLOT_MAX_COUNT_BITS)); uint32_t new_slot_max = slot_max > 0 ? slot_max * 2 : 1; object_slots = (ObjectSlot *)memrealloc(object_slots, sizeof(ObjectSlot) * new_slot_max); for (uint32_t i = slot_max; i < new_slot_max; i++) { object_slots[i].object = nullptr; object_slots[i].is_reference = false; object_slots[i].next_free = i; object_slots[i].validator = 0; } slot_max = new_slot_max; } uint32_t slot = object_slots[slot_count].next_free; if (object_slots[slot].object != nullptr) { spin_lock.unlock(); ERR_FAIL_COND_V(object_slots[slot].object != nullptr, ObjectID()); } object_slots[slot].object = p_object; object_slots[slot].is_reference = p_object->is_reference(); validator_counter = (validator_counter + 1) & OBJECTDB_VALIDATOR_MASK; if (unlikely(validator_counter == 0)) { validator_counter = 1; } object_slots[slot].validator = validator_counter; uint64_t id = validator_counter; id <<= OBJECTDB_SLOT_MAX_COUNT_BITS; id |= uint64_t(slot); if (p_object->is_reference()) { id |= OBJECTDB_REFERENCE_BIT; } slot_count++; spin_lock.unlock(); return ObjectID(id); } void ObjectDB::remove_instance(Object *p_object) { uint64_t t = p_object->get_instance_id(); uint32_t slot = t & OBJECTDB_SLOT_MAX_COUNT_MASK; //slot is always valid on valid object spin_lock.lock(); #ifdef DEBUG_ENABLED if (object_slots[slot].object != p_object) { spin_lock.unlock(); ERR_FAIL_COND(object_slots[slot].object != p_object); } { uint64_t validator = (t >> OBJECTDB_SLOT_MAX_COUNT_BITS) & OBJECTDB_VALIDATOR_MASK; if (object_slots[slot].validator != validator) { spin_lock.unlock(); ERR_FAIL_COND(object_slots[slot].validator != validator); } } #endif //decrease slot count slot_count--; //set the free slot properly object_slots[slot_count].next_free = slot; //invalidate, so checks against it fail object_slots[slot].validator = 0; object_slots[slot].is_reference = false; object_slots[slot].object = nullptr; spin_lock.unlock(); } void ObjectDB::setup() { //nothing to do now } void ObjectDB::cleanup() { if (slot_count > 0) { spin_lock.lock(); WARN_PRINT("ObjectDB instances leaked at exit (run with --verbose for details)."); if (OS::get_singleton()->is_stdout_verbose()) { // Ensure calling the native classes because if a leaked instance has a script // that overrides any of those methods, it'd not be OK to call them at this point, // now the scripting languages have already been terminated. MethodBind *node_get_name = ClassDB::get_method("Node", "get_name"); MethodBind *resource_get_path = ClassDB::get_method("Resource", "get_path"); Callable::CallError call_error; for (uint32_t i = 0; i < slot_count; i++) { uint32_t slot = object_slots[i].next_free; Object *obj = object_slots[slot].object; String extra_info; if (obj->is_class("Node")) { extra_info = " - Node name: " + String(node_get_name->call(obj, nullptr, 0, call_error)); } if (obj->is_class("Resource")) { extra_info = " - Resource path: " + String(resource_get_path->call(obj, nullptr, 0, call_error)); } uint64_t id = uint64_t(slot) | (uint64_t(object_slots[slot].validator) << OBJECTDB_VALIDATOR_BITS) | (object_slots[slot].is_reference ? OBJECTDB_REFERENCE_BIT : 0); print_line("Leaked instance: " + String(obj->get_class()) + ":" + itos(id) + extra_info); } print_line("Hint: Leaked instances typically happen when nodes are removed from the scene tree (with `remove_child()`) but not freed (with `free()` or `queue_free()`)."); } spin_lock.unlock(); } if (object_slots) { memfree(object_slots); } }
#ifndef GAMEBOY_EMULATOR_SIODATAREGISTER_H #define GAMEBOY_EMULATOR_SIODATAREGISTER_H #include <emulator/mmu/MMIORegister.hpp> namespace nsfgbe { class SerialLinkManager; class SIODataRegister : public MMIORegister<MMIOPermissions::READ_WRITE> { private: SerialLinkManager &serialLinkManager; protected: Byte getValue() const override; void setValue(Byte value) override; public: explicit SIODataRegister(SerialLinkManager &serialLinkManager); SIODataRegister &operator=(Byte value) override; }; } #endif //GAMEBOY_EMULATOR_SIODATAREGISTER_H
#include <cstdio> #include <algorithm> #include <vector> #ifdef _MSC_VER #include <random> #else #include <tr1/random> #endif const int NumBuckets = 16; const int NumValues = 32 * 16; const int WarpSize = 16; const int ValsPerSegment = 16; const bool EmitHTML = true; std::tr1::mt19937 mt19937; std::vector<int> keys(NumValues); std::tr1::uniform_int<int> r1(0, NumBuckets - 1); std::tr1::uniform_int<int> r2(0, ValsPerSegment - 1); std::vector<int> counts(NumBuckets), gather(NumBuckets), scatter(NumBuckets); const char* Ticks = "| | | | | |"; const char* Marks = "0 16 32 48 64 80"; void PrintArray(const int* vals, int count, int valsPerLine, int spacing, int leadingSpaces) { for(int i(0); i < count; ++i) { if(0 == (i % valsPerLine)) { if(i) printf("\n"); for(int j(0); j < leadingSpaces; ++j) printf(" "); } else if(0 == (i % spacing)) printf(" "); printf("%x", vals[i]); } printf("\n"); } int PrintTransactionsSimple(int digit, int gather, int scatter, int count, int* prevTrans, int transCol) { // Print the radix digit and space up to the first scattered value. printf("%x: ", digit); for(int i(0); i < scatter; ++i) printf(" "); int prevSegment = -1; int prevWarp = -1; int transCount = 0; for(int i(0); i < count; ++i) { int curSegment = (scatter + i) / ValsPerSegment; int curWarp = (gather + i) / WarpSize; if((prevSegment != curSegment) || (prevWarp != curWarp)) { if(EmitHTML) { if(i) printf("</span>"); printf("<span class=\"%s\">", *prevTrans ? "blue" : "red"); *prevTrans ^= 1; } prevSegment = curSegment; prevWarp = curWarp; ++transCount; } printf("%x", (WarpSize - 1) & (gather + i)); } if(count && EmitHTML) printf("</span>"); int offset = 4 + scatter + count; while(offset < transCol) { printf(" "); ++offset; } if(EmitHTML) printf("<strong>%2d</strong> vals, <strong>%d</strong> trans\n", count, transCount); else printf("%2d vals, %d trans\n", count, transCount); return transCount; } int PrintTransactionsAligned(int digit, int gather, int scatter, int count, int* prevTrans, int transCol) { // Print the radix digit and space up to the first scattered value. printf("%x: ", digit); for(int i(0); i < scatter; ++i) printf(" "); int seg = -1; int segStart = -1; int transCount = 0; for(int i(0); i < count; ++i) { int curSeg = (scatter + i) / WarpSize; if(seg != curSeg) { if(EmitHTML) { if(i) printf("</span>"); printf("<span class=\"%s\">", *prevTrans ? "blue" : "red"); *prevTrans ^= 1; } seg = curSeg; segStart = i; ++transCount; } printf("%x", i - segStart); } if(count && EmitHTML) printf("</span>"); int offset = 4 + scatter + count; while(offset < transCol) { printf(" "); ++offset; } if(EmitHTML) printf("<strong>%2d</strong> vals, <strong>%d</strong> trans\n", count, transCount); else printf("%2d vals, %d trans\n", count, transCount); return transCount; } int PrintScatter(bool aligned) { printf("*** %s scatter:\n", aligned ? "Aligned" : "Simple"); printf(" %s\n %s\n", Marks, Ticks); int prevTrans = 0; int transTotal = 0; for(int i(0); i < NumBuckets; ++i) { int transCount; if(aligned) transCount = PrintTransactionsAligned(i, gather[i], scatter[i], counts[i], &prevTrans, 69); else transCount = PrintTransactionsSimple(i, gather[i], scatter[i], counts[i], &prevTrans, 69); transTotal += transCount; } printf(" %s\n %s\n", Ticks, Marks); printf(EmitHTML ? "*** Total transactions: <strong>%2d</strong>\n" : "*** Total transactions: %2d\n", transTotal); return transTotal; } int main() { printf("Sorting %d values with a warp and segment size of %d.\n", NumValues, WarpSize); printf("Number of radix digits is %d.\n\n", NumBuckets); for(int i(0); i < NumValues; ++i) { keys[i] = r1(mt19937); ++counts[keys[i]]; } printf("sequence:\n"); PrintArray(&keys[0], NumValues, 64, 16, 4); std::sort(keys.begin(), keys.end()); printf("\n"); printf("sorted:\n"); PrintArray(&keys[0], NumValues, 64, 16, 4); printf("\n"); for(int i(0); i < NumBuckets; ++i) { if(i) gather[i] = gather[i - 1] + counts[i - 1]; scatter[i] = r2(mt19937); if(EmitHTML) { printf("\t* digit <strong>%x</strong> count <strong>%2d</strong>" " gather <strong>%3d</strong> (lane <strong>%x</strong>)" " scatter lane <strong>%x</strong>\n", i, counts[i], gather[i], 0xf & gather[i], scatter[i]); } else { printf("\t* digit %x count %2d gather %3d (lane %x)" " scatter lane %x\n", i, counts[i], gather[i], 0xf & gather[i], scatter[i]); } } printf("\n"); for(int i(0); i < 85; ++i) printf("-"); printf("\n"); int simpleTrans = PrintScatter(false); printf("\n"); for(int i(0); i < 85; ++i) printf("-"); printf("\n"); int alignedTrans = PrintScatter(true); printf("\n"); for(int i(0); i < 85; ++i) printf("-"); printf("\n"); double ratio = (double)alignedTrans / simpleTrans; printf(EmitHTML ? "*** Aligned:Simple transaction ratio: <strong>%3.2lf</strong>\n" : "*** Aligned:Simple transaction ratio: %3.2lf\n", ratio); }
#include "SaveFileFactory.hpp" #include "Platform.hpp" #include "Player.hpp" #include "Button.hpp" #include "Crate.hpp" #include "Coin.hpp" #include "Door.hpp" SaveFileFactory::SaveFileFactory(std::ifstream& file) : FileFactory(file) {} GameObj* SaveFileFactory::createObj() { unsigned char id; m_file.read((char*) &id, sizeof(id)); if (m_file.eof()) return nullptr; if (id == Player::getSaveId()) return new (std::nothrow) Player(m_file); else if (id == Platform::getSaveId()) return new (std::nothrow) Platform(m_file); else if (id == Crate::getSaveId()) return new (std::nothrow) Crate(m_file); else if (id == Coin::getSaveId()) return new (std::nothrow) Coin(m_file); else if (id == Door::getSaveId()) return new (std::nothrow) Door(m_file); else if (id == Button::getSaveId()) return new (std::nothrow) Button(m_file); return nullptr; }
// Copyright (c) 2015-2020 Hartmut Kaiser // Copyright (c) 2021 Akhil J Nair // // SPDX-License-Identifier: BSL-1.0 // 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) /// \file parallel/container_algorithms/shift_right.hpp #pragma once #if defined(DOXYGEN) namespace hpx { // clang-format off /////////////////////////////////////////////////////////////////////////// /// Shifts the elements in the range [first, last) by n positions towards /// the end of the range. For every integer i in [0, last - first - n), /// moves the element originally at position first + i to position first /// + n + i. /// /// \note Complexity: At most (last - first) - n assignments. /// /// \tparam FwdIter The type of the source iterators used (deduced). /// This iterator type must meet the requirements of an /// forward iterator. /// \tparam Sent The type of the source sentinel (deduced). This /// sentinel type must be a sentinel for FwdIter. /// \tparam Size The type of the argument specifying the number of /// positions to shift by. /// /// \param first Refers to the beginning of the sequence of elements /// the algorithm will be applied to. /// \param last Refers to sentinel value denoting the end of the /// sequence of elements the algorithm will be applied. /// \param n Refers to the number of positions to shift. /// /// The assignment operations in the parallel \a shift_right algorithm /// invoked without an execution policy object will execute in sequential /// order in the calling thread. /// /// \note The type of dereferenced \a FwdIter must meet the requirements /// of \a MoveAssignable. /// /// \returns The \a shift_right algorithm returns \a FwdIter. /// The \a shift_right algorithm returns an iterator to the /// end of the resulting range. /// template <typename FwdIter, typename Sent, typename Size> FwdIter shift_right(FwdIter first, Sent last, Size n); /////////////////////////////////////////////////////////////////////////// /// Shifts the elements in the range [first, last) by n positions towards /// the end of the range. For every integer i in [0, last - first - n), /// moves the element originally at position first + i to position first /// + n + i. /// /// \note Complexity: At most (last - first) - n assignments. /// /// \tparam ExPolicy The type of the execution policy to use (deduced). /// It describes the manner in which the execution /// of the algorithm may be parallelized and the manner /// in which it executes the assignments. /// \tparam FwdIter The type of the source iterators used (deduced). /// This iterator type must meet the requirements of an /// forward iterator. /// \tparam Sent The type of the source sentinel (deduced). This /// sentinel type must be a sentinel for FwdIter. /// \tparam Size The type of the argument specifying the number of /// positions to shift by. /// /// \param policy The execution policy to use for the scheduling of /// the iterations. /// \param first Refers to the beginning of the sequence of elements /// the algorithm will be applied to. /// \param last Refers to sentinel value denoting the end of the /// sequence of elements the algorithm will be applied. /// \param n Refers to the number of positions to shift. /// /// The assignment operations in the parallel \a shift_right algorithm /// invoked with an execution policy object of type \a sequenced_policy /// execute in sequential order in the calling thread. /// /// The assignment operations in the parallel \a shift_right algorithm /// invoked with an execution policy object of type \a parallel_policy /// or \a parallel_task_policy are permitted to execute in an unordered /// fashion in unspecified threads, and indeterminately sequenced /// within each thread. /// /// \note The type of dereferenced \a FwdIter must meet the requirements /// of \a MoveAssignable. /// /// \returns The \a shift_right algorithm returns a /// \a hpx::future<FwdIter> if /// the execution policy is of type /// \a sequenced_task_policy or /// \a parallel_task_policy and /// returns \a FwdIter otherwise. /// The \a shift_right algorithm returns an iterator to the /// end of the resulting range. /// template <typename ExPolicy, typename FwdIter, typename Sent, typename Size> typename parallel::util::detail::algorithm_result<ExPolicy, FwdIter> shift_right(ExPolicy&& policy, FwdIter first, Sent last, Size n); /////////////////////////////////////////////////////////////////////////// /// Shifts the elements in the range [first, last) by n positions towards /// the end of the range. For every integer i in [0, last - first - n), /// moves the element originally at position first + i to position first /// + n + i. /// /// \note Complexity: At most (last - first) - n assignments. /// /// \tparam Rng The type of the range used (deduced). /// The iterators extracted from this range type must /// meet the requirements of an forward iterator. /// \tparam Size The type of the argument specifying the number of /// positions to shift by. /// /// \param rng Refers to the range in which the elements /// will be shifted. /// \param n Refers to the number of positions to shift. /// /// The assignment operations in the parallel \a shift_right algorithm /// invoked without an execution policy object will execute in sequential /// order in the calling thread. /// /// \note The type of dereferenced \a hpx::traits::range_iterator_t<Rng> /// must meet the requirements of \a MoveAssignable. /// /// \returns The \a shift_right algorithm returns \a /// hpx::traits::range_iterator_t<Rng>. /// The \a shift_right algorithm returns an iterator to the /// end of the resulting range. /// template <typename Rng, typename Size> hpx::traits::range_iterator_t<Rng> shift_right(Rng&& rng, Size n); /////////////////////////////////////////////////////////////////////////// /// Shifts the elements in the range [first, last) by n positions towards /// the end of the range. For every integer i in [0, last - first - n), /// moves the element originally at position first + i to position first /// + n + i. /// /// \note Complexity: At most (last - first) - n assignments. /// /// \tparam ExPolicy The type of the execution policy to use (deduced). /// It describes the manner in which the execution /// of the algorithm may be parallelized and the manner /// in which it executes the assignments. /// \tparam Rng The type of the range used (deduced). /// The iterators extracted from this range type must /// meet the requirements of an forward iterator. /// \tparam Size The type of the argument specifying the number of /// positions to shift by. /// /// \param policy The execution policy to use for the scheduling of /// the iterations. /// \param rng Refers to the range in which the elements /// will be shifted. /// \param n Refers to the number of positions to shift. /// /// The assignment operations in the parallel \a shift_right algorithm /// invoked with an execution policy object of type \a sequenced_policy /// execute in sequential order in the calling thread. /// /// The assignment operations in the parallel \a shift_right algorithm /// invoked with an execution policy object of type \a parallel_policy /// or \a parallel_task_policy are permitted to execute in an unordered /// fashion in unspecified threads, and indeterminately sequenced /// within each thread. /// /// \note The type of dereferenced \a hpx::traits::range_iterator_t<Rng> /// must meet the requirements of \a MoveAssignable. /// /// \returns The \a shift_right algorithm returns a /// \a hpx::future<hpx::traits::range_iterator_t<Rng>> if /// the execution policy is of type /// \a sequenced_task_policy or /// \a parallel_task_policy and /// returns \a hpx::traits::range_iterator_t<Rng> otherwise. /// The \a shift_right algorithm returns an iterator to the /// end of the resulting range. /// template <typename ExPolicy, typename Rng, typename Size> typename parallel::util::detail::algorithm_result<ExPolicy, hpx::traits::range_iterator_t<Rng>>::type shift_right(ExPolicy&& policy, Rng&& rng, Size n); // clang-format on } // namespace hpx #else // DOXYGEN #include <hpx/local/config.hpp> #include <hpx/concepts/concepts.hpp> #include <hpx/iterator_support/range.hpp> #include <hpx/iterator_support/traits/is_range.hpp> #include <hpx/algorithms/traits/projected_range.hpp> #include <hpx/parallel/algorithms/shift_right.hpp> #include <hpx/parallel/util/projection_identity.hpp> #include <type_traits> #include <utility> namespace hpx { namespace ranges { inline constexpr struct shift_right_t final : hpx::functional::detail::tag_fallback<shift_right_t> { private: // clang-format off template <typename FwdIter, typename Sent, typename Size, HPX_CONCEPT_REQUIRES_( hpx::traits::is_iterator_v<FwdIter> && hpx::traits::is_sentinel_for<Sent, FwdIter>::value )> // clang-format on friend FwdIter tag_fallback_invoke( hpx::ranges::shift_right_t, FwdIter first, Sent last, Size n) { static_assert(hpx::traits::is_forward_iterator_v<FwdIter>, "Requires at least forward iterator."); return hpx::parallel::v1::detail::shift_right<FwdIter>().call( hpx::execution::seq, first, last, n); } // clang-format off template <typename ExPolicy, typename FwdIter, typename Sent, typename Size, HPX_CONCEPT_REQUIRES_( hpx::is_execution_policy<ExPolicy>::value && hpx::traits::is_iterator_v<FwdIter> && hpx::traits::is_sentinel_for<Sent, FwdIter>::value )> // clang-format on friend typename hpx::parallel::util::detail::algorithm_result<ExPolicy, FwdIter>::type tag_fallback_invoke(hpx::ranges::shift_right_t, ExPolicy&& policy, FwdIter first, Sent last, Size n) { static_assert(hpx::traits::is_forward_iterator_v<FwdIter>, "Requires at least forward iterator."); return hpx::parallel::v1::detail::shift_right<FwdIter>().call( HPX_FORWARD(ExPolicy, policy), first, last, n); } // clang-format off template <typename Rng, typename Size, HPX_CONCEPT_REQUIRES_( hpx::traits::is_range<Rng>::value )> // clang-format on friend hpx::traits::range_iterator_t<Rng> tag_fallback_invoke( hpx::ranges::shift_right_t, Rng&& rng, Size n) { static_assert(hpx::traits::is_forward_iterator_v< hpx::traits::range_iterator_t<Rng>>, "Requires at least forward iterator."); return hpx::parallel::v1::detail::shift_right< hpx::traits::range_iterator_t<Rng>>() .call(hpx::execution::seq, std::begin(rng), std::end(rng), n); } // clang-format off template <typename ExPolicy, typename Rng, typename Size, HPX_CONCEPT_REQUIRES_( hpx::is_execution_policy<ExPolicy>::value && hpx::traits::is_range<Rng>::value )> // clang-format on friend typename parallel::util::detail::algorithm_result<ExPolicy, hpx::traits::range_iterator_t<Rng>>::type tag_fallback_invoke( hpx::ranges::shift_right_t, ExPolicy&& policy, Rng&& rng, Size n) { static_assert(hpx::traits::is_forward_iterator_v< hpx::traits::range_iterator_t<Rng>>, "Requires at least forward iterator."); return hpx::parallel::v1::detail::shift_right< hpx::traits::range_iterator_t<Rng>>() .call(HPX_FORWARD(ExPolicy, policy), std::begin(rng), std::end(rng), n); } } shift_right{}; }} // namespace hpx::ranges #endif // DOXYGEN
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef _THRIFT_PROTOCOL_TCOMPACTPROTOCOL_TCC_ #define _THRIFT_PROTOCOL_TCOMPACTPROTOCOL_TCC_ 1 #include <limits> #include <cstdlib> #include "thrift/thrift-config.h" /* * TCompactProtocol::i*ToZigzag depend on the fact that the right shift * operator on a signed integer is an arithmetic (sign-extending) shift. * If this is not the case, the current implementation will not work. * If anyone encounters this error, we can try to figure out the best * way to implement an arithmetic right shift on their platform. */ #if !defined(SIGNED_RIGHT_SHIFT_IS) || !defined(ARITHMETIC_RIGHT_SHIFT) # error "Unable to determine the behavior of a signed right shift" #endif #if SIGNED_RIGHT_SHIFT_IS != ARITHMETIC_RIGHT_SHIFT # error "TCompactProtocol currently only works if a signed right shift is arithmetic" #endif #ifdef __GNUC__ #define UNLIKELY(val) (__builtin_expect((val), 0)) #else #define UNLIKELY(val) (val) #endif namespace apache { namespace thrift { namespace protocol { namespace detail { namespace compact { enum Types { CT_STOP = 0x00, CT_BOOLEAN_TRUE = 0x01, CT_BOOLEAN_FALSE = 0x02, CT_BYTE = 0x03, CT_I16 = 0x04, CT_I32 = 0x05, CT_I64 = 0x06, CT_DOUBLE = 0x07, CT_BINARY = 0x08, CT_LIST = 0x09, CT_SET = 0x0A, CT_MAP = 0x0B, CT_STRUCT = 0x0C }; const int8_t TTypeToCType[16] = { CT_STOP, // T_STOP 0, // unused CT_BOOLEAN_TRUE, // T_BOOL CT_BYTE, // T_BYTE CT_DOUBLE, // T_DOUBLE 0, // unused CT_I16, // T_I16 0, // unused CT_I32, // T_I32 0, // unused CT_I64, // T_I64 CT_BINARY, // T_STRING CT_STRUCT, // T_STRUCT CT_MAP, // T_MAP CT_SET, // T_SET CT_LIST, // T_LIST }; }} // end detail::compact namespace template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeMessageBegin( const std::string& name, const TMessageType messageType, const int32_t seqid) { uint32_t wsize = 0; wsize += writeByte(PROTOCOL_ID); wsize += writeByte((VERSION_N & VERSION_MASK) | (((int32_t)messageType << TYPE_SHIFT_AMOUNT) & TYPE_MASK)); wsize += writeVarint32(seqid); wsize += writeString(name); return wsize; } /** * Write a field header containing the field id and field type. If the * difference between the current field id and the last one is small (< 15), * then the field id will be encoded in the 4 MSB as a delta. Otherwise, the * field id will follow the type header as a zigzag varint. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeFieldBegin(const char* name, const TType fieldType, const int16_t fieldId) { if (fieldType == T_BOOL) { booleanField_.name = name; booleanField_.fieldType = fieldType; booleanField_.fieldId = fieldId; } else { return writeFieldBeginInternal(name, fieldType, fieldId, -1); } return 0; } /** * Write the STOP symbol so we know there are no more fields in this struct. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeFieldStop() { return writeByte(T_STOP); } /** * Write a struct begin. This doesn't actually put anything on the wire. We * use it as an opportunity to put special placeholder markers on the field * stack so we can get the field id deltas correct. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeStructBegin(const char* name) { (void) name; lastField_.push(lastFieldId_); lastFieldId_ = 0; return 0; } /** * Write a struct end. This doesn't actually put anything on the wire. We use * this as an opportunity to pop the last field from the current struct off * of the field stack. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeStructEnd() { lastFieldId_ = lastField_.top(); lastField_.pop(); return 0; } /** * Write a List header. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeListBegin(const TType elemType, const uint32_t size) { return writeCollectionBegin(elemType, size); } /** * Write a set header. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeSetBegin(const TType elemType, const uint32_t size) { return writeCollectionBegin(elemType, size); } /** * Write a map header. If the map is empty, omit the key and value type * headers, as we don't need any additional information to skip it. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeMapBegin(const TType keyType, const TType valType, const uint32_t size) { uint32_t wsize = 0; if (size == 0) { wsize += writeByte(0); } else { wsize += writeVarint32(size); wsize += writeByte(getCompactType(keyType) << 4 | getCompactType(valType)); } return wsize; } /** * Write a boolean value. Potentially, this could be a boolean field, in * which case the field header info isn't written yet. If so, decide what the * right type header is for the value and then write the field header. * Otherwise, write a single byte. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeBool(const bool value) { uint32_t wsize = 0; if (booleanField_.name != nullptr) { // we haven't written the field header yet wsize += writeFieldBeginInternal(booleanField_.name, booleanField_.fieldType, booleanField_.fieldId, static_cast<int8_t>(value ? detail::compact::CT_BOOLEAN_TRUE : detail::compact::CT_BOOLEAN_FALSE)); booleanField_.name = nullptr; } else { // we're not part of a field, so just write the value wsize += writeByte(static_cast<int8_t>(value ? detail::compact::CT_BOOLEAN_TRUE : detail::compact::CT_BOOLEAN_FALSE)); } return wsize; } template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeByte(const int8_t byte) { trans_->write((uint8_t*)&byte, 1); return 1; } /** * Write an i16 as a zigzag varint. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeI16(const int16_t i16) { return writeVarint32(i32ToZigzag(i16)); } /** * Write an i32 as a zigzag varint. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeI32(const int32_t i32) { return writeVarint32(i32ToZigzag(i32)); } /** * Write an i64 as a zigzag varint. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeI64(const int64_t i64) { return writeVarint64(i64ToZigzag(i64)); } /** * Write a double to the wire as 8 bytes. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeDouble(const double dub) { static_assert(sizeof(double) == sizeof(uint64_t), "sizeof(double) == sizeof(uint64_t)"); static_assert(std::numeric_limits<double>::is_iec559, "std::numeric_limits<double>::is_iec559"); auto bits = bitwise_cast<uint64_t>(dub); bits = THRIFT_htolell(bits); trans_->write((uint8_t*)&bits, 8); return 8; } /** * Write a string to the wire with a varint size preceding. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeString(const std::string& str) { return writeBinary(str); } template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeBinary(const std::string& str) { if(str.size() > (std::numeric_limits<uint32_t>::max)()) throw TProtocolException(TProtocolException::SIZE_LIMIT); auto ssize = static_cast<uint32_t>(str.size()); uint32_t wsize = writeVarint32(ssize) ; // checking ssize + wsize > uint_max, but we don't want to overflow while checking for overflows. // transforming the check to ssize > uint_max - wsize if(ssize > (std::numeric_limits<uint32_t>::max)() - wsize) throw TProtocolException(TProtocolException::SIZE_LIMIT); wsize += ssize; trans_->write((uint8_t*)str.data(), ssize); return wsize; } // // Internal Writing methods // /** * The workhorse of writeFieldBegin. It has the option of doing a * 'type override' of the type header. This is used specifically in the * boolean field case. */ template <class Transport_> int32_t TCompactProtocolT<Transport_>::writeFieldBeginInternal( const char* name, const TType fieldType, const int16_t fieldId, int8_t typeOverride) { (void) name; uint32_t wsize = 0; // if there's a type override, use that. int8_t typeToWrite = (typeOverride == -1 ? getCompactType(fieldType) : typeOverride); // check if we can use delta encoding for the field id if (fieldId > lastFieldId_ && fieldId - lastFieldId_ <= 15) { // write them together wsize += writeByte(static_cast<int8_t>((fieldId - lastFieldId_) << 4 | typeToWrite)); } else { // write them separate wsize += writeByte(typeToWrite); wsize += writeI16(fieldId); } lastFieldId_ = fieldId; return wsize; } /** * Abstract method for writing the start of lists and sets. List and sets on * the wire differ only by the type indicator. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeCollectionBegin(const TType elemType, int32_t size) { uint32_t wsize = 0; if (size <= 14) { wsize += writeByte(static_cast<int8_t>(size << 4 | getCompactType(elemType))); } else { wsize += writeByte(0xf0 | getCompactType(elemType)); wsize += writeVarint32(size); } return wsize; } /** * Write an i32 as a varint. Results in 1-5 bytes on the wire. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeVarint32(uint32_t n) { uint8_t buf[5]; uint32_t wsize = 0; while (true) { if ((n & ~0x7F) == 0) { buf[wsize++] = (int8_t)n; break; } else { buf[wsize++] = (int8_t)((n & 0x7F) | 0x80); n >>= 7; } } trans_->write(buf, wsize); return wsize; } /** * Write an i64 as a varint. Results in 1-10 bytes on the wire. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::writeVarint64(uint64_t n) { uint8_t buf[10]; uint32_t wsize = 0; while (true) { if ((n & ~0x7FL) == 0) { buf[wsize++] = (int8_t)n; break; } else { buf[wsize++] = (int8_t)((n & 0x7F) | 0x80); n >>= 7; } } trans_->write(buf, wsize); return wsize; } /** * Convert l into a zigzag long. This allows negative numbers to be * represented compactly as a varint. */ template <class Transport_> uint64_t TCompactProtocolT<Transport_>::i64ToZigzag(const int64_t l) { return (static_cast<uint64_t>(l) << 1) ^ (l >> 63); } /** * Convert n into a zigzag int. This allows negative numbers to be * represented compactly as a varint. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::i32ToZigzag(const int32_t n) { return (static_cast<uint32_t>(n) << 1) ^ (n >> 31); } /** * Given a TType value, find the appropriate detail::compact::Types value */ template <class Transport_> int8_t TCompactProtocolT<Transport_>::getCompactType(const TType ttype) { return detail::compact::TTypeToCType[ttype]; } // // Reading Methods // /** * Read a message header. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readMessageBegin( std::string& name, TMessageType& messageType, int32_t& seqid) { uint32_t rsize = 0; int8_t protocolId; int8_t versionAndType; int8_t version; rsize += readByte(protocolId); if (protocolId != PROTOCOL_ID) { throw TProtocolException(TProtocolException::BAD_VERSION, "Bad protocol identifier"); } rsize += readByte(versionAndType); version = (int8_t)(versionAndType & VERSION_MASK); if (version != VERSION_N) { throw TProtocolException(TProtocolException::BAD_VERSION, "Bad protocol version"); } messageType = (TMessageType)((versionAndType >> TYPE_SHIFT_AMOUNT) & TYPE_BITS); rsize += readVarint32(seqid); rsize += readString(name); return rsize; } /** * Read a struct begin. There's nothing on the wire for this, but it is our * opportunity to push a new struct begin marker on the field stack. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readStructBegin(std::string& name) { name = ""; lastField_.push(lastFieldId_); lastFieldId_ = 0; return 0; } /** * Doesn't actually consume any wire data, just removes the last field for * this struct from the field stack. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readStructEnd() { lastFieldId_ = lastField_.top(); lastField_.pop(); return 0; } /** * Read a field header off the wire. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readFieldBegin(std::string& name, TType& fieldType, int16_t& fieldId) { (void) name; uint32_t rsize = 0; int8_t byte; int8_t type; rsize += readByte(byte); type = (byte & 0x0f); // if it's a stop, then we can return immediately, as the struct is over. if (type == T_STOP) { fieldType = T_STOP; fieldId = 0; return rsize; } // mask off the 4 MSB of the type header. it could contain a field id delta. auto modifier = (int16_t)(((uint8_t)byte & 0xf0) >> 4); if (modifier == 0) { // not a delta, look ahead for the zigzag varint field id. rsize += readI16(fieldId); } else { fieldId = (int16_t)(lastFieldId_ + modifier); } fieldType = getTType(type); // if this happens to be a boolean field, the value is encoded in the type if (type == detail::compact::CT_BOOLEAN_TRUE || type == detail::compact::CT_BOOLEAN_FALSE) { // save the boolean value in a special instance variable. boolValue_.hasBoolValue = true; boolValue_.boolValue = (type == detail::compact::CT_BOOLEAN_TRUE ? true : false); } // push the new field onto the field stack so we can keep the deltas going. lastFieldId_ = fieldId; return rsize; } /** * Read a map header off the wire. If the size is zero, skip reading the key * and value type. This means that 0-length maps will yield TMaps without the * "correct" types. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readMapBegin(TType& keyType, TType& valType, uint32_t& size) { uint32_t rsize = 0; int8_t kvType = 0; int32_t msize = 0; rsize += readVarint32(msize); if (msize != 0) rsize += readByte(kvType); if (msize < 0) { throw TProtocolException(TProtocolException::NEGATIVE_SIZE); } else if (container_limit_ && msize > container_limit_) { throw TProtocolException(TProtocolException::SIZE_LIMIT); } keyType = getTType((int8_t)((uint8_t)kvType >> 4)); valType = getTType((int8_t)((uint8_t)kvType & 0xf)); size = (uint32_t)msize; TMap map(keyType, valType, size); checkReadBytesAvailable(map); return rsize; } /** * Read a list header off the wire. If the list size is 0-14, the size will * be packed into the element type header. If it's a longer list, the 4 MSB * of the element type header will be 0xF, and a varint will follow with the * true size. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readListBegin(TType& elemType, uint32_t& size) { int8_t size_and_type; uint32_t rsize = 0; int32_t lsize; rsize += readByte(size_and_type); lsize = ((uint8_t)size_and_type >> 4) & 0x0f; if (lsize == 15) { rsize += readVarint32(lsize); } if (lsize < 0) { throw TProtocolException(TProtocolException::NEGATIVE_SIZE); } else if (container_limit_ && lsize > container_limit_) { throw TProtocolException(TProtocolException::SIZE_LIMIT); } elemType = getTType((int8_t)(size_and_type & 0x0f)); size = (uint32_t)lsize; TList list(elemType, size); checkReadBytesAvailable(list); return rsize; } /** * Read a set header off the wire. If the set size is 0-14, the size will * be packed into the element type header. If it's a longer set, the 4 MSB * of the element type header will be 0xF, and a varint will follow with the * true size. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readSetBegin(TType& elemType, uint32_t& size) { return readListBegin(elemType, size); } /** * Read a boolean off the wire. If this is a boolean field, the value should * already have been read during readFieldBegin, so we'll just consume the * pre-stored value. Otherwise, read a byte. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readBool(bool& value) { if (boolValue_.hasBoolValue == true) { value = boolValue_.boolValue; boolValue_.hasBoolValue = false; return 0; } else { int8_t val; readByte(val); value = (val == detail::compact::CT_BOOLEAN_TRUE); return 1; } } /** * Read a single byte off the wire. Nothing interesting here. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readByte(int8_t& byte) { uint8_t b[1]; trans_->readAll(b, 1); byte = *(int8_t*)b; return 1; } /** * Read an i16 from the wire as a zigzag varint. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readI16(int16_t& i16) { int32_t value; uint32_t rsize = readVarint32(value); i16 = (int16_t)zigzagToI32(value); return rsize; } /** * Read an i32 from the wire as a zigzag varint. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readI32(int32_t& i32) { int32_t value; uint32_t rsize = readVarint32(value); i32 = zigzagToI32(value); return rsize; } /** * Read an i64 from the wire as a zigzag varint. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readI64(int64_t& i64) { int64_t value; uint32_t rsize = readVarint64(value); i64 = zigzagToI64(value); return rsize; } /** * No magic here - just read a double off the wire. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readDouble(double& dub) { static_assert(sizeof(double) == sizeof(uint64_t), "sizeof(double) == sizeof(uint64_t)"); static_assert(std::numeric_limits<double>::is_iec559, "std::numeric_limits<double>::is_iec559"); union { uint64_t bits; uint8_t b[8]; } u; trans_->readAll(u.b, 8); u.bits = THRIFT_letohll(u.bits); dub = bitwise_cast<double>(u.bits); return 8; } template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readString(std::string& str) { return readBinary(str); } /** * Read a byte[] from the wire. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readBinary(std::string& str) { int32_t rsize = 0; int32_t size; rsize += readVarint32(size); // Catch empty string case if (size == 0) { str = ""; return rsize; } // Catch error cases if (size < 0) { throw TProtocolException(TProtocolException::NEGATIVE_SIZE); } if (string_limit_ > 0 && size > string_limit_) { throw TProtocolException(TProtocolException::SIZE_LIMIT); } // Use the heap here to prevent stack overflow for v. large strings if (size > string_buf_size_ || string_buf_ == nullptr) { void* new_string_buf = std::realloc(string_buf_, (uint32_t)size); if (new_string_buf == nullptr) { throw std::bad_alloc(); } string_buf_ = (uint8_t*)new_string_buf; string_buf_size_ = size; } trans_->readAll(string_buf_, size); str.assign((char*)string_buf_, size); trans_->checkReadBytesAvailable(rsize + (uint32_t)size); return rsize + (uint32_t)size; } /** * Read an i32 from the wire as a varint. The MSB of each byte is set * if there is another byte to follow. This can read up to 5 bytes. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readVarint32(int32_t& i32) { int64_t val; uint32_t rsize = readVarint64(val); i32 = (int32_t)val; return rsize; } /** * Read an i64 from the wire as a proper varint. The MSB of each byte is set * if there is another byte to follow. This can read up to 10 bytes. */ template <class Transport_> uint32_t TCompactProtocolT<Transport_>::readVarint64(int64_t& i64) { uint32_t rsize = 0; uint64_t val = 0; int shift = 0; uint8_t buf[10]; // 64 bits / (7 bits/byte) = 10 bytes. uint32_t buf_size = sizeof(buf); const uint8_t* borrowed = trans_->borrow(buf, &buf_size); // Fast path. if (borrowed != nullptr) { while (true) { uint8_t byte = borrowed[rsize]; rsize++; val |= (uint64_t)(byte & 0x7f) << shift; shift += 7; if (!(byte & 0x80)) { i64 = val; trans_->consume(rsize); return rsize; } // Have to check for invalid data so we don't crash. if (UNLIKELY(rsize == sizeof(buf))) { throw TProtocolException(TProtocolException::INVALID_DATA, "Variable-length int over 10 bytes."); } } } // Slow path. else { while (true) { uint8_t byte; rsize += trans_->readAll(&byte, 1); val |= (uint64_t)(byte & 0x7f) << shift; shift += 7; if (!(byte & 0x80)) { i64 = val; return rsize; } // Might as well check for invalid data on the slow path too. if (UNLIKELY(rsize >= sizeof(buf))) { throw TProtocolException(TProtocolException::INVALID_DATA, "Variable-length int over 10 bytes."); } } } } /** * Convert from zigzag int to int. */ template <class Transport_> int32_t TCompactProtocolT<Transport_>::zigzagToI32(uint32_t n) { return (n >> 1) ^ static_cast<uint32_t>(-static_cast<int32_t>(n & 1)); } /** * Convert from zigzag long to long. */ template <class Transport_> int64_t TCompactProtocolT<Transport_>::zigzagToI64(uint64_t n) { return (n >> 1) ^ static_cast<uint64_t>(-static_cast<int64_t>(n & 1)); } template <class Transport_> TType TCompactProtocolT<Transport_>::getTType(int8_t type) { switch (type) { case T_STOP: return T_STOP; case detail::compact::CT_BOOLEAN_FALSE: case detail::compact::CT_BOOLEAN_TRUE: return T_BOOL; case detail::compact::CT_BYTE: return T_BYTE; case detail::compact::CT_I16: return T_I16; case detail::compact::CT_I32: return T_I32; case detail::compact::CT_I64: return T_I64; case detail::compact::CT_DOUBLE: return T_DOUBLE; case detail::compact::CT_BINARY: return T_STRING; case detail::compact::CT_LIST: return T_LIST; case detail::compact::CT_SET: return T_SET; case detail::compact::CT_MAP: return T_MAP; case detail::compact::CT_STRUCT: return T_STRUCT; default: throw TException(std::string("don't know what type: ") + (char)type); } } // Return the minimum number of bytes a type will consume on the wire template <class Transport_> int TCompactProtocolT<Transport_>::getMinSerializedSize(TType type) { switch (type) { case T_STOP: return 0; case T_VOID: return 0; case T_BOOL: return sizeof(int8_t); case T_DOUBLE: return 8; // uses fixedLongToBytes() which always writes 8 bytes case T_BYTE: return sizeof(int8_t); case T_I16: return sizeof(int8_t); // zigzag case T_I32: return sizeof(int8_t); // zigzag case T_I64: return sizeof(int8_t); // zigzag case T_STRING: return sizeof(int8_t); // string length case T_STRUCT: return 0; // empty struct case T_MAP: return sizeof(int8_t); // element count case T_SET: return sizeof(int8_t); // element count case T_LIST: return sizeof(int8_t); // element count default: throw TProtocolException(TProtocolException::UNKNOWN, "unrecognized type code"); } } }}} // apache::thrift::protocol #endif // _THRIFT_PROTOCOL_TCOMPACTPROTOCOL_TCC_
#include "Messages.h" Messages::Messages(const wxString& title) : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(210, 110)) { wxPanel *panel = new wxPanel(this, wxID_ANY); wxBoxSizer *hbox = new wxBoxSizer(wxHORIZONTAL); wxGridSizer *gs = new wxGridSizer(2, 2, 2, 2); wxButton *btn1 = new wxButton(panel, ID_INFO, wxT("Info")); wxButton *btn2 = new wxButton(panel, ID_ERROR, wxT("Error")); wxButton *btn3 = new wxButton(panel, ID_QUESTION, wxT("Question")); wxButton *btn4 = new wxButton(panel, ID_ALERT, wxT("Alert")); Connect(ID_INFO, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Messages::ShowMessage1)); Connect(ID_ERROR, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Messages::ShowMessage2)); Connect(ID_QUESTION, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Messages::ShowMessage3)); Connect(ID_ALERT, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(Messages::ShowMessage4)); gs->Add(btn1, 1, wxEXPAND); gs->Add(btn2, 1); gs->Add(btn3, 1); gs->Add(btn4, 1); hbox->Add(gs, 0, wxALL, 15); panel->SetSizer(hbox); Center(); } void Messages::ShowMessage1(wxCommandEvent& event) { wxMessageDialog *dial = new wxMessageDialog(NULL, wxT("Download completed"), wxT("Info"), wxOK); dial->ShowModal(); } void Messages::ShowMessage2(wxCommandEvent& event) { wxMessageDialog *dial = new wxMessageDialog(NULL, wxT("Error loading file"), wxT("Error"), wxOK | wxICON_ERROR); dial->ShowModal(); } void Messages::ShowMessage3(wxCommandEvent& event) { wxMessageDialog *dial = new wxMessageDialog(NULL, wxT("Are you sure to quit?"), wxT("Question"), wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION); dial->ShowModal(); } void Messages::ShowMessage4(wxCommandEvent& event) { wxMessageDialog *dial = new wxMessageDialog(NULL, wxT("Unallowed operation"), wxT("Exclamation"), wxOK | wxICON_EXCLAMATION); dial->ShowModal(); }
// Copyright (c) 2019 by Robert Bosch GmbH. 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 "iceoryx_posh/internal/mepoo/mem_pool.hpp" #include "iceoryx_utils/cxx/helplets.hpp" #include "iceoryx_utils/error_handling/error_handling.hpp" #include <algorithm> namespace iox { namespace mepoo { MemPool::MemPool(const cxx::greater_or_equal<uint32_t, MEMORY_ALIGNMENT> f_chunkSize, const cxx::greater_or_equal<uint32_t, 1> f_numberOfChunks, posix::Allocator* f_managementAllocator, posix::Allocator* f_payloadAllocator) : m_chunkSize(f_chunkSize) , m_numberOfChunks(f_numberOfChunks) , m_minFree(f_numberOfChunks) { if (isMultipleOf32(f_chunkSize)) { m_rawMemory = static_cast<uint8_t*>(f_payloadAllocator->allocate(static_cast<uint64_t>(m_numberOfChunks) * m_chunkSize)); auto memoryLoFFLi = static_cast<uint32_t*>(f_managementAllocator->allocate(freeList_t::requiredMemorySize(m_numberOfChunks))); m_freeIndices.init(memoryLoFFLi, m_numberOfChunks); } else { std::cerr << f_chunkSize << " :: " << f_numberOfChunks << std::endl; errorHandler(Error::kMEPOO__MEMPOOL_CHUNKSIZE_MUST_BE_LARGER_32_AND_MULTIPLE_OF_32); } } bool MemPool::isMultipleOf32(const uint32_t value) const { return (value % 32 == 0); } void MemPool::adjustMinFree() { // @todo rethink the concurrent change that can happen. do we need a CAS loop? m_minFree.store(std::min(m_numberOfChunks - m_usedChunks.load(std::memory_order_relaxed), m_minFree.load(std::memory_order_relaxed))); } void* MemPool::getChunk() { uint32_t l_index{0}; if (!m_freeIndices.pop(l_index)) { std::cerr << "Mempool [m_chunkSize = " << m_chunkSize << ", numberOfChunks = " << m_numberOfChunks << ", used_chunks = " << m_usedChunks << " ] has no more space left" << std::endl; return nullptr; } /// @todo: verify that m_usedChunk is not changed during adjustMInFree /// without changing m_minFree m_usedChunks.fetch_add(1, std::memory_order_relaxed); adjustMinFree(); return m_rawMemory + l_index * m_chunkSize; } void MemPool::freeChunk(const void* chunk) { cxx::Expects(m_rawMemory <= chunk && chunk <= m_rawMemory + (static_cast<uint64_t>(m_chunkSize) * (m_numberOfChunks - 1))); auto offset = static_cast<const uint8_t*>(chunk) - m_rawMemory; cxx::Expects(offset % m_chunkSize == 0); uint32_t index = static_cast<uint32_t>(offset / m_chunkSize); if (!m_freeIndices.push(index)) { errorHandler(Error::kPOSH__MEMPOOL_POSSIBLE_DOUBLE_FREE); } m_usedChunks.fetch_sub(1, std::memory_order_relaxed); } uint32_t MemPool::getChunkSize() const { return m_chunkSize; } uint32_t MemPool::getChunkCount() const { return m_numberOfChunks; } uint32_t MemPool::getUsedChunks() const { return m_usedChunks.load(std::memory_order_relaxed); } uint32_t MemPool::getMinFree() const { return m_minFree.load(std::memory_order_relaxed); } MemPoolInfo MemPool::getInfo() const { return {m_usedChunks.load(std::memory_order_relaxed), m_minFree.load(std::memory_order_relaxed), m_numberOfChunks, m_chunkSize}; } } // namespace mepoo } // namespace iox
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/bfloat16_propagation.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_dce.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/tuple_simplifier.h" #include "tensorflow/compiler/xla/shape_tree.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/core/lib/gtl/cleanup.h" #include "tensorflow/core/platform/logging.h" namespace xla { BFloat16Propagation::BFloat16Propagation( const BFloat16Support* bfloat16_support) : bfloat16_support_(bfloat16_support) {} void BFloat16Propagation::DetermineFusionComputationPrecision( HloInstruction* fusion) { CHECK_EQ(fusion->opcode(), HloOpcode::kFusion); if (!bfloat16_support_->SupportsMixedPrecisions(*fusion)) { return; } // We are depending on the fusion node itself having already been analyzed // for whether it can output BF16 and this has been adjusted in the output // shape, and now we're looking to update the interior of the fusion node to // match the new output shape, as well as recursively process the whole fusion // node even if the output shape was not modified. auto root = fusion->fused_instructions_computation()->root_instruction(); // Adjust root's element types according to the fusion's output shape. ShapeUtil::ForEachSubshape( root->shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (subshape.element_type() != F32) { return; } if (OutputTypeAfterChange(fusion, index) == BF16) { AddToOrRemoveFromBF16ChangeSet(root, index, BF16); VLOG(2) << "Fused root " << root->ToString() << " at shape index " << index << " changed to BF16 precision for fusion " << fusion->ToString(); } }); // Propagate BF16 in the fusion computation. auto insts = fusion->fused_instructions_computation()->MakeInstructionPostOrder(); for (auto inst_it = insts.rbegin(); inst_it != insts.rend(); ++inst_it) { DetermineInstructionPrecision(*inst_it, /*skip_parameters=*/false); } computations_visited_in_backward_pass_.insert( fusion->fused_instructions_computation()); RevertIfFusionInternalBF16Changes(fusion); } void BFloat16Propagation::RevertIfFusionInternalBF16Changes( HloInstruction* fusion) { auto has_changes = [this](HloInstruction* inst) { auto it = changes_to_bf16_.find(inst); return it != changes_to_bf16_.end() && !it->second.empty(); }; auto root = fusion->fused_instructions_computation()->root_instruction(); tensorflow::gtl::FlatSet<const HloValue*> changed_root_buffers; auto root_changes_it = changes_to_bf16_.find(root); if (root_changes_it != changes_to_bf16_.end()) { for (const auto& entry : root_changes_it->second) { for (const HloValue* value : dataflow_->GetValueSet(root, entry.second).values()) { changed_root_buffers.insert(value); } } } auto aliases_changed_root_buffer = [this, &changed_root_buffers](const HloInstruction* inst) { bool aliasing = false; ShapeUtil::ForEachSubshape( inst->shape(), [&](const Shape& subshape, const ShapeIndex& index) { if (aliasing) { // Skip if aliasing is already found. return; } // Only F32 buffers are considered for changing to BF16 in this // pass. if (subshape.element_type() != F32) { return; } for (const HloValue* value : dataflow_->GetValueSet(inst, index).values()) { if (ContainsKey(changed_root_buffers, value)) { aliasing = true; break; } } }); return aliasing; }; for (auto inst : fusion->fused_instructions_computation()->MakeInstructionPostOrder()) { if (inst->opcode() == HloOpcode::kParameter) { continue; } if (aliases_changed_root_buffer(inst)) { continue; } if (inst->opcode() == HloOpcode::kFusion) { bool parameter_reverted = false; for (int64 i = 0; i < inst->operand_count(); ++i) { if (has_changes(inst->mutable_operand(i))) { // Changes on the operand have not been reverted. continue; } auto* fused_parameter = inst->fused_parameter(i); if (has_changes(fused_parameter)) { changes_to_bf16_.erase(fused_parameter); parameter_reverted = true; } } if (parameter_reverted) { RevertIfFusionInternalBF16Changes(inst); } } if (!has_changes(inst)) { continue; } bool revert_changes = true; for (auto operand : inst->operands()) { if (has_changes(operand)) { revert_changes = false; break; } } if (revert_changes) { changes_to_bf16_.erase(inst); } } } void BFloat16Propagation::DetermineWhileComputationsPrecision( HloInstruction* while_hlo) { CHECK_EQ(while_hlo->opcode(), HloOpcode::kWhile); // We are depending on the while node itself having already been analyzed for // whether it can output BF16 and this has been adjusted in the output shape, // and now we're looking to update the body and condition computations to // match the new output shape, as well as recursively process the whole while // node even if the output shape was not modified. HloComputation* body = while_hlo->while_body(); auto body_root = body->root_instruction(); HloComputation* condition = while_hlo->while_condition(); ShapeUtil::ForEachSubshape( body_root->shape(), [this, while_hlo, body_root]( const Shape& subshape, const ShapeIndex& index) { if (subshape.element_type() != F32) { return; } if (OutputTypeAfterChange(while_hlo, index) == BF16) { AddToOrRemoveFromBF16ChangeSet(body_root, index, BF16); VLOG(2) << "While body root " << body_root->ToString() << " at shape index " << index << " changed to BF16 precision for while " << while_hlo->ToString(); } }); auto body_insts = body->MakeInstructionPostOrder(); for (auto inst_it = body_insts.rbegin(); inst_it != body_insts.rend(); ++inst_it) { DetermineInstructionPrecision(*inst_it, /*skip_parameters=*/false); } computations_visited_in_backward_pass_.insert(body); auto condition_insts = condition->MakeInstructionPostOrder(); for (auto inst_it = condition_insts.rbegin(); inst_it != condition_insts.rend(); ++inst_it) { DetermineInstructionPrecision(*inst_it, /*skip_parameters=*/false); } computations_visited_in_backward_pass_.insert(condition); } bool BFloat16Propagation::AllUsersConsumeBF16(const HloInstruction& hlo, const ShapeIndex& index) const { // If the subshape isn't floating point then none of the users will be BF16. const Shape& subshape = ShapeUtil::GetSubshape(hlo.shape(), index); if (subshape.element_type() != BF16 && subshape.element_type() != F32) { return false; } auto& value_set = dataflow_->GetValueSet(&hlo, index); for (const HloValue* value : value_set.values()) { if (ContainsKey(values_that_must_be_kept_as_f32_, value)) { return false; } if (ValueTypeAfterChange(value) == BF16) { continue; } for (const HloUse& use : value->uses()) { if (!ContainsKey(instructions_visited_in_backward_pass_, use.instruction)) { // We don't know yet whether use.instruction will consume BF16 since it // hasn't been visited. Although we visit instructions in reverse // topological order, this is still possible because there may be // unvisited instruction that alias the same buffer. In this case, we // aggressively skip this use, and if this causes inconsistency (e.g., // one use is in BF16 but another use is in F32), it will be resolved at // the end of the BFloat16Propagation pass. continue; } // Any visited user that can accept BF16 has already been updated if // necessary, e.g., the output has been changed to BF16 if it propagates // precision, or a called computation's parameters have been changed to // BF16 for fusions or whiles. if (use.instruction->opcode() == HloOpcode::kFusion) { auto* fused_parameter = use.instruction->fused_parameter(use.operand_number); if (OutputTypeAfterChange(fused_parameter, use.operand_index) != BF16) { return false; } continue; } else if (use.instruction->opcode() == HloOpcode::kWhile) { auto* cond_parameter = use.instruction->while_condition()->parameter_instruction( use.operand_number); if (OutputTypeAfterChange(cond_parameter, use.operand_index) != BF16) { return false; } auto* body_parameter = use.instruction->while_body()->parameter_instruction( use.operand_number); if (OutputTypeAfterChange(body_parameter, use.operand_index) != BF16) { return false; } continue; } if (bfloat16_support_->EffectiveOperandPrecisionIsBF16( *use.instruction, use.operand_number)) { continue; } // If the op propagates precision and it outputs a BF16, then it's OK to // supply BF16 also as the input. In the backward pass, the users shapes // should have already been processed. if (bfloat16_support_->EffectiveOperandPrecisionIsOutputPrecision( *use.instruction, use.operand_number)) { if (use.instruction->opcode() == HloOpcode::kTuple || (use.instruction->opcode() == HloOpcode::kCrossReplicaSum && ShapeUtil::IsTuple(use.instruction->shape()))) { ShapeIndex use_output_index{use.operand_number}; for (int64 i : use.operand_index) { use_output_index.push_back(i); } if (OutputTypeAfterChange(use.instruction, use_output_index) == BF16) { continue; } } else if (use.instruction->opcode() == HloOpcode::kGetTupleElement) { ShapeIndex use_output_index; for (int64 i = 1; i < use.operand_index.size(); ++i) { use_output_index.push_back(use.operand_index[i]); } if (OutputTypeAfterChange(use.instruction, use_output_index) == BF16) { continue; } } else { if (OutputTypeAfterChange(use.instruction, use.operand_index) == BF16) { continue; } } } return false; } } return true; } void BFloat16Propagation::DetermineInstructionPrecision(HloInstruction* hlo, bool skip_parameters) { // We handle any fusion computation or while body/condition after the // instruction is handled, because we need to know the output shape of a // fusion or while before propagating inside its computations. bool postpone_processing_called_computations = false; auto cleaner = tensorflow::gtl::MakeCleanup( [this, hlo, &postpone_processing_called_computations] { if (!postpone_processing_called_computations) { if (hlo->opcode() == HloOpcode::kFusion) { DetermineFusionComputationPrecision(hlo); } else if (hlo->opcode() == HloOpcode::kWhile) { DetermineWhileComputationsPrecision(hlo); } } instructions_visited_in_backward_pass_.insert(hlo); }); if (hlo->opcode() == HloOpcode::kWhile && (caller_counts_[hlo->while_condition()] > 1 || caller_counts_[hlo->while_body()] > 1)) { postpone_processing_called_computations = true; return; } // Do not change precision for instructions related to entry and exit of a // computation, and control flow, because this pass might break the interfaces // or assumptions for them. if (hlo->opcode() == HloOpcode::kInfeed || // hlo->opcode() == HloOpcode::kOutfeed || // hlo->opcode() == HloOpcode::kSend || // hlo->opcode() == HloOpcode::kSendDone || // hlo->opcode() == HloOpcode::kRecv || // hlo->opcode() == HloOpcode::kRecvDone || // hlo->opcode() == HloOpcode::kCustomCall || // hlo->opcode() == HloOpcode::kCall || // hlo->opcode() == HloOpcode::kConditional || // (hlo->opcode() == HloOpcode::kParameter && skip_parameters)) { return; } // Prevent root instructions from having their output modified by recording // all F32 output values as needing to stay as F32. CHECK(hlo->parent() != nullptr); if (hlo == hlo->parent()->root_instruction()) { if (!hlo->parent()->IsFusionComputation()) { ShapeUtil::ForEachSubshape(hlo->shape(), [&](const Shape& /* subshape */, const ShapeIndex& index) { if (OutputTypeAfterChange(hlo, index) != F32) { return; } for (const auto* value : dataflow_->GetValueSet(hlo, index).values()) { // Since we use HloValues from the dataflow analysis, this can also // affect HLO instructions beyond the root, e.g., if the root is a // Tuple HLO, then its operands are also affected. values_that_must_be_kept_as_f32_.insert(value); } }); } return; } if (!ContainsKey(consider_using_bfloat16_, hlo)) { return; } if (!bfloat16_support_->SupportsBF16Output(*hlo)) { return; } ShapeUtil::ForEachSubshape( hlo->shape(), [hlo, this](const Shape& /* subshape */, const ShapeIndex& index) { if (OutputTypeAfterChange(hlo, index) == F32 && AllUsersConsumeBF16(*hlo, index)) { AddToOrRemoveFromBF16ChangeSet(hlo, index, BF16); VLOG(2) << "HloInstruction output at shape index " << index << " changed to BF16 precision: " << hlo->ToString(); } }); } bool BFloat16Propagation::InstructionIsCandidateForBF16Output( HloInstruction* hlo) { if (!bfloat16_support_->SupportsMixedPrecisions(*hlo) && hlo->opcode() != HloOpcode::kTuple && hlo->opcode() != HloOpcode::kGetTupleElement && hlo->opcode() != HloOpcode::kDomain && hlo->shape().element_type() != BF16) { for (int64 i = 0; i < hlo->operand_count(); ++i) { if (!bfloat16_support_->EffectiveOperandPrecisionIsOutputPrecision(*hlo, i) || !ContainsKey(consider_using_bfloat16_, hlo->operand(i))) { return false; } } } return true; } void BFloat16Propagation::AdjustCalledComputationParameters( HloInstruction* hlo) { auto adjust_computation = [this, hlo](HloComputation* computation, tensorflow::gtl::ArraySlice<HloInstruction*> operands) { // Adjust parameters. CHECK_EQ(operands.size(), computation->num_parameters()); for (int64 i = 0; i < operands.size(); ++i) { auto parameter = computation->parameter_instruction(i); ShapeUtil::ForEachSubshape( parameter->shape(), [this, i, hlo, &operands, parameter](const Shape& /* subshape */, const ShapeIndex& index) { if (!ShapeUtil::IsLeafIndex(parameter->shape(), index)) { return; } PrimitiveType operand_type = OutputTypeAfterChange(operands[i], index); if (OutputTypeAfterChange(parameter, index) == operand_type) { return; } AddToOrRemoveFromBF16ChangeSet(parameter, index, operand_type); VLOG(2) << "Called computation parameter " << parameter->ToString() << " at shape index " << index << " adjusted to " << (operand_type == BF16 ? "BF16" : "F32") << " to match operand in HLO " << hlo->ToString(); }); } }; switch (hlo->opcode()) { case HloOpcode::kFusion: adjust_computation(hlo->fused_instructions_computation(), hlo->operands()); break; case HloOpcode::kWhile: adjust_computation(hlo->while_condition(), hlo->operands()); adjust_computation(hlo->while_body(), hlo->operands()); break; default: break; } } void BFloat16Propagation::AdjustCalledComputationRoot(HloInstruction* hlo) { auto adjust_computation = [this, hlo](HloComputation* computation, HloInstruction* output) { // Adjust root. HloInstruction* root = computation->root_instruction(); ShapeUtil::ForEachSubshape(root->shape(), [this, hlo, root, output]( const Shape& /* subshape */, const ShapeIndex& index) { if (!ShapeUtil::IsLeafIndex(hlo->shape(), index)) { return; } const PrimitiveType output_type = OutputTypeAfterChange(output, index); if (OutputTypeAfterChange(root, index) == output_type) { return; } AddToOrRemoveFromBF16ChangeSet(root, index, output_type); // It's possible that output_type is F32, but the root instruction's // type is BF16; e.g., a fusion node's output was changed to BF16 // initially but then adjusted back to F32, and the fusion computation // is now being adjusted after the fusion node. if (output_type == F32) { for (const auto* value : dataflow_->GetValueSet(root, index).values()) { // We rely on the fact that this adjustment works in reverse // topological order so that called computation will be // processed later. Adding the value to // values_that_must_be_kept_as_f32_ will ensure the // correctness of the adjustment for HLOs that will be // processed later. values_that_must_be_kept_as_f32_.insert(value); } } VLOG(2) << "Called computation root " << root->ToString() << " at shape index " << index << " adjusted to " << (output_type == BF16 ? "BF16" : "F32") << " to match output shape of " << hlo->ToString(); }); }; switch (hlo->opcode()) { case HloOpcode::kFusion: adjust_computation(hlo->fused_instructions_computation(), hlo); break; case HloOpcode::kWhile: adjust_computation(hlo->while_body(), hlo); break; default: break; } } bool BFloat16Propagation::ResolveInconsistencyOfAliasingBuffersHelper( HloComputation* computation, tensorflow::gtl::FlatSet<const HloComputation*>* visited_computations) { bool parameter_changed = false; auto insts = computation->MakeInstructionPostOrder(); // Do the adjustment on each instruction in the computation in reverse // topological order. for (auto inst_it = insts.rbegin(); inst_it != insts.rend(); ++inst_it) { auto hlo = *inst_it; auto adjust_hlo_output = [this, hlo, &parameter_changed]( const Shape& /* subshape */, const ShapeIndex& index) { auto output_type = OutputTypeAfterChange(hlo, index); if (output_type != F32 && output_type != BF16) { return; } PrimitiveType type = BF16; for (const auto* value : dataflow_->GetValueSet(hlo, index).values()) { auto value_type = ValueTypeAfterChange(value); if (value_type == BF16) { continue; } CHECK_EQ(value_type, F32); type = F32; break; } // It's possible that a user has been changed from BF16 to F32 // during this final adjustment pass, so we need to check // AllUsersConsumeBF16() again. if (type == BF16 && !AllUsersConsumeBF16(*hlo, index)) { type = F32; } if (type == F32) { for (const auto* value : dataflow_->GetValueSet(hlo, index).values()) { // We rely on the fact that this adjustment works in reverse // topological order. Adding the value to // values_that_must_be_kept_as_f32_ will ensure the correctness // of the adjustment for HLOs that will be processed later. values_that_must_be_kept_as_f32_.insert(value); } } if (type != output_type) { AddToOrRemoveFromBF16ChangeSet(hlo, index, type); VLOG(2) << "HloInstruction output at shape index " << index << " adjusted to " << (type == BF16 ? "BF16" : "F32") << ": " << hlo->ToString(); if (hlo->opcode() == HloOpcode::kParameter) { parameter_changed = true; } } }; ShapeUtil::ForEachSubshape(hlo->shape(), adjust_hlo_output); AdjustCalledComputationRoot(hlo); if (hlo->opcode() == HloOpcode::kWhile) { // We need to run on the while body and condition repeatedly until a fixed // point is reached, i.e., the parameters do not change any more. We may // need more than one iteration because the while input and output alias // each other, so changing one input parameter requires changing the // corresponding output element and thus may transitively require changing // another input parameter. A fixed point will be reached because the // parameters can only be changed from BF16 to F32, not the other way // around. tensorflow::gtl::FlatSet<const HloComputation*> visited_in_while; while (ResolveInconsistencyOfAliasingBuffersHelper(hlo->while_condition(), &visited_in_while) || ResolveInconsistencyOfAliasingBuffersHelper(hlo->while_body(), &visited_in_while)) { visited_in_while.clear(); ShapeUtil::ForEachSubshape(hlo->shape(), adjust_hlo_output); AdjustCalledComputationRoot(hlo); } visited_computations->insert(visited_in_while.begin(), visited_in_while.end()); } } // Now adjust parameters of called computations. for (auto inst_it = insts.rbegin(); inst_it != insts.rend(); ++inst_it) { AdjustCalledComputationParameters(*inst_it); } return parameter_changed; } void BFloat16Propagation::ResolveInconsistencyOfAliasingBuffers( HloModule* module) { const auto& computations_topological_order = module->MakeComputationPostOrder(); tensorflow::gtl::FlatSet<const HloComputation*> resolved; for (auto comp_it = computations_topological_order.rbegin(); comp_it != computations_topological_order.rend(); ++comp_it) { if (ContainsKey(resolved, *comp_it)) { continue; } ResolveInconsistencyOfAliasingBuffersHelper(*comp_it, &resolved); } } Status BFloat16Propagation::ResolveInconsistentFusions(HloModule* module) { // We could have changed a fusion computation's root shape to have a different // precision than the fusion node's output, if the fusion root does not // define a buffer (e.g., a tuple). Now we add conversions after such fusion // roots to make them match the fusion output. If the fusion output is a // (possibly nested) tuple, we first create get-tuple-elements, then convert // the unmatching leaf nodes, and finally create a new tuple as the fusion // computation's root. If tuples and get-tuple-elements are created, we will // run tuple simplifier and dead code elimination at the end (dead code is not // allowed in fusion computation). E.g., // // (1) (2) (3) // a b a b a b // |\ | |\ | |\ | // \ add -> |add -> | add // \ | \ | convert | // tuple tuple \ | // / \ tuple // gte gte // | | // convert | // \ / // tuple // (1) a is F32 but tuple is BF16 // (2) after adding conversion // (3) after tuple simplifier and DCE. bool needs_tuple_simplifier = false; for (auto computation : module->MakeComputationPostOrder()) { auto insts = computation->MakeInstructionPostOrder(); for (auto inst_it = insts.rbegin(); inst_it != insts.rend(); ++inst_it) { auto hlo = *inst_it; if (hlo->opcode() != HloOpcode::kFusion) { continue; } auto fusion_computation = hlo->fused_instructions_computation(); auto fusion_root = fusion_computation->root_instruction(); if (ShapeUtil::Compatible(fusion_root->shape(), hlo->shape())) { continue; } ShapeTree<HloInstruction*> converted_outputs(hlo->shape()); // Iterate through nodes in the shape tree in pre-order and initialize // each non-root node with a corresponding get-tuple-element. For a leaf // node, if its shape does not match the fusion output, create a // conversion node to overwrite the node value. for (auto it = converted_outputs.begin(); it != converted_outputs.end(); ++it) { ShapeIndex output_index = it->first; HloInstruction*& output = it->second; const Shape subshape = ShapeUtil::GetSubshape(hlo->shape(), output_index); if (output_index.empty()) { output = fusion_root; } else { ShapeIndex parent_index = output_index; parent_index.pop_back(); output = fusion_computation->AddInstruction( HloInstruction::CreateGetTupleElement( subshape, converted_outputs.element(parent_index), output_index.back())); } if (!ShapeUtil::IsArray(subshape)) { continue; } if (!ShapeUtil::Compatible( subshape, ShapeUtil::GetSubshape(fusion_root->shape(), output_index))) { output = fusion_computation->AddInstruction( HloInstruction::CreateConvert(subshape, output)); } } // Iterate through nodes in the shape tree in reverse pre-order and create // a tuple instruction for each non-leaf node where the elements are the // values of its child nodes. for (auto it = converted_outputs.rbegin(); it != converted_outputs.rend(); ++it) { ShapeIndex output_index = it->first; HloInstruction*& output = it->second; const Shape& subshape = ShapeUtil::GetSubshape(hlo->shape(), output_index); if (!ShapeUtil::IsTuple(subshape)) { continue; } std::vector<HloInstruction*> elements( ShapeUtil::TupleElementCount(subshape)); ShapeIndex child_index = output_index; for (int64 i = 0; i < elements.size(); ++i) { child_index.push_back(i); elements[i] = converted_outputs.element(child_index); child_index.pop_back(); } output = fusion_computation->AddInstruction( HloInstruction::CreateTuple(elements)); } fusion_computation->set_root_instruction(converted_outputs.element({})); needs_tuple_simplifier |= ShapeUtil::IsTuple(hlo->shape()); } } if (needs_tuple_simplifier) { TupleSimplifier tuple_simplifier; TF_RETURN_IF_ERROR(tuple_simplifier.Run(module).status()); } return Status::OK(); } Status BFloat16Propagation::ResolveConvertedConstants(HloModule* module) { // We may have converted some constants from F32 to BF16, so adjust the // constant literals in such cases. We do this here instead of when the // constant node's is changed because 1) the HloInstruction interface does not // allow resetting the literal so we have to create a new kConstant // instruction to replace the old one, which invalidates dataflow analysis, // and 2) it's possible that a kConstant's output gets changed to BF16 at the // beginning but later on adjusted back to F32, so converting literals here // can avoid repeated conversions. // // TODO(b/73833576): Consider resetting literal in HloInstruction. for (auto computation : module->MakeComputationPostOrder()) { for (auto hlo : computation->MakeInstructionPostOrder()) { if (hlo->opcode() != HloOpcode::kConstant) { continue; } if (!ShapeUtil::Equal(hlo->literal().shape(), hlo->shape())) { TF_ASSIGN_OR_RETURN( auto converted_literal, hlo->literal().ConvertToShape(hlo->shape(), /*round_f32_to_bf16=*/true)); auto new_constant = computation->AddInstruction( HloInstruction::CreateConstant(std::move(converted_literal))); TF_RETURN_IF_ERROR(hlo->ReplaceAllUsesWith(new_constant)); } } } return Status::OK(); } Status BFloat16Propagation::SkipNoopConversions(HloModule* module) { for (auto computation : module->computations()) { for (auto hlo : computation->MakeInstructionPostOrder()) { if (hlo->opcode() != HloOpcode::kConvert) { continue; } auto source = hlo->mutable_operand(0); if (!ShapeUtil::Equal(source->shape(), hlo->shape())) { continue; } const bool is_root = hlo == computation->root_instruction(); TF_RETURN_IF_ERROR(hlo->ReplaceAllUsesWith(source)); if (is_root) { computation->set_root_instruction(source); } } } return Status::OK(); } // The algorithm first does a forward pass (parameters to root) to determine a // set of instructions to consider using bfloat16, then does a backward pass to // determine the precisions of those instructions according to the need of // their users. During the backward pass, the potential changes are stored in // changes_to_bf16_ which are subject to further adjustments then applied to the // HLOs. StatusOr<bool> BFloat16Propagation::Run(HloModule* module) { consider_using_bfloat16_.clear(); instructions_visited_in_backward_pass_.clear(); computations_visited_in_backward_pass_.clear(); values_that_must_be_kept_as_f32_.clear(); caller_counts_.clear(); changes_to_bf16_.clear(); changed_ = false; TF_ASSIGN_OR_RETURN(dataflow_, HloDataflowAnalysis::Run(*module)); const auto& computations_topological_order = module->MakeComputationPostOrder(); // The first step is a forward pass (parameters to root), where we determine // the potential candidate instructions to use bfloat16 in the outputs that // are not likely to cause overhead from extra explicit conversions. This is // done forwardly because we determine whether an HLO is a candidate partially // based on whether its operands are candidates. for (auto computation : computations_topological_order) { for (auto inst : computation->MakeInstructionPostOrder()) { if (InstructionIsCandidateForBF16Output(inst)) { consider_using_bfloat16_.insert(inst); } } } // The second step is a backward pass (root to parameters), where we modify // the precisions of the instructions identified in the first step when // feasible. This is done backwardly because we determine the precision of an // HLO's output based on how it is later used. // // The precision of an instruction is determined by its users, so we do the // propagation in reverse topological order. for (auto comp_it = computations_topological_order.rbegin(); comp_it != computations_topological_order.rend(); ++comp_it) { if ((*comp_it)->IsFusionComputation()) { // Fusion computations are handled when visiting the fusion instruction. continue; } auto insts = (*comp_it)->MakeInstructionPostOrder(); for (auto inst_it = insts.rbegin(); inst_it != insts.rend(); ++inst_it) { DetermineInstructionPrecision(*inst_it, /*skip_parameters=*/true); } } // It's possible that an instruction does not define a buffer, but the // defining instruction's shape has changed. So we need to adjust the output // shapes of instructions according to the HLO values they refer to. ResolveInconsistencyOfAliasingBuffers(module); // Apply the changes in changes_to_bf16_. for (auto& change : changes_to_bf16_) { for (const auto& entry : change.second) { auto subshape = entry.first; CHECK_EQ(subshape->element_type(), F32); subshape->set_element_type(BF16); changed_ = true; } } if (!changed_) { return false; } TF_RETURN_IF_ERROR(ResolveInconsistentFusions(module)); TF_RETURN_IF_ERROR(ResolveConvertedConstants(module)); // This pass could have turned an F32 -> BF16 conversion to a no-op (BF16 -> // BF16), so we skip them now. TF_RETURN_IF_ERROR(SkipNoopConversions(module)); { // We may have dead HLOs after ResolveInconsistentFusions, // ResolveConvertedConstants and SkipNoopConversions. HloDCE dce; TF_RETURN_IF_ERROR(dce.Run(module).status()); } return true; } PrimitiveType BFloat16Propagation::OutputTypeAfterChange( HloInstruction* hlo, const ShapeIndex& index) const { Shape* subshape = ShapeUtil::GetMutableSubshape(hlo->mutable_shape(), index); const PrimitiveType type_on_hlo = subshape->element_type(); if (type_on_hlo != F32) { return type_on_hlo; } auto it = changes_to_bf16_.find(hlo); if (it == changes_to_bf16_.end()) { return type_on_hlo; } return ContainsKey(it->second, subshape) ? BF16 : F32; } PrimitiveType BFloat16Propagation::ValueTypeAfterChange( const HloValue* value) const { auto hlo = value->defining_instruction(); const auto& position = value->defining_position(); return OutputTypeAfterChange(hlo, position.index); } void BFloat16Propagation::AddToOrRemoveFromBF16ChangeSet( HloInstruction* hlo, const ShapeIndex& index, PrimitiveType target_type) { if (target_type == BF16) { auto& entry = changes_to_bf16_[hlo]; entry.emplace(ShapeUtil::GetMutableSubshape(hlo->mutable_shape(), index), index); } else { CHECK_EQ(target_type, F32); auto it = changes_to_bf16_.find(hlo); if (it == changes_to_bf16_.end()) { return; } it->second.erase( ShapeUtil::GetMutableSubshape(hlo->mutable_shape(), index)); } } } // namespace xla
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { OSCBundle::OSCBundle() { } OSCBundle::OSCBundle (OSCTimeTag t) : timeTag (t) { } // Note: The class invariant of OSCBundle::Element is that // at least one of the pointers bundle and message is nullptr // and the other one always points to a valid object. OSCBundle::Element::Element (OSCMessage m) : message (new OSCMessage (m)), bundle (nullptr) { } OSCBundle::Element::Element (OSCBundle b) : message (nullptr), bundle (new OSCBundle (b)) { } //============================================================================== OSCBundle::Element::Element (const Element& other) { if (this != &other) { message = nullptr; bundle = nullptr; if (other.isMessage()) message.reset (new OSCMessage (other.getMessage())); else bundle.reset (new OSCBundle (other.getBundle())); } } //============================================================================== OSCBundle::Element::~Element() { bundle = nullptr; message = nullptr; } //============================================================================== bool OSCBundle::Element::isMessage() const noexcept { return message != nullptr; } bool OSCBundle::Element::isBundle() const noexcept { return bundle != nullptr; } //============================================================================== const OSCMessage& OSCBundle::Element::getMessage() const { if (message == nullptr) { // This element is not a bundle! You must check this first before accessing. jassertfalse; throw OSCInternalError ("Access error in OSC bundle element."); } return *message; } //============================================================================== const OSCBundle& OSCBundle::Element::getBundle() const { if (bundle == nullptr) { // This element is not a bundle! You must check this first before accessing. jassertfalse; throw OSCInternalError ("Access error in OSC bundle element."); } return *bundle; } //============================================================================== #if JUCE_UNIT_TESTS class OSCBundleTests : public UnitTest { public: OSCBundleTests() : UnitTest ("OSCBundle class", "OSC") {} void runTest() { beginTest ("Construction"); { OSCBundle bundle; expect (bundle.getTimeTag().isImmediately()); } beginTest ("Construction with time tag"); { Time in100Seconds = (Time (Time::currentTimeMillis()) + RelativeTime (100.0)); OSCBundle bundle (in100Seconds); expect (! bundle.getTimeTag().isImmediately()); expect (bundle.getTimeTag().toTime() == in100Seconds); } beginTest ("Usage when containing messages"); { OSCBundle testBundle = generateTestBundle(); expectBundleEqualsTestBundle (testBundle); } beginTest ("Usage when containing other bundles (recursively)"); { OSCBundle complexTestBundle; complexTestBundle.addElement (generateTestBundle()); complexTestBundle.addElement (OSCMessage ("/test/")); complexTestBundle.addElement (generateTestBundle()); expect (complexTestBundle.size() == 3); OSCBundle::Element* elements = complexTestBundle.begin(); expect (! elements[0].isMessage()); expect (elements[0].isBundle()); expect (elements[1].isMessage()); expect (! elements[1].isBundle()); expect (! elements[2].isMessage()); expect (elements[2].isBundle()); expectBundleEqualsTestBundle (elements[0].getBundle()); expect (elements[1].getMessage().size() == 0); expect (elements[1].getMessage().getAddressPattern().toString() == "/test"); expectBundleEqualsTestBundle (elements[2].getBundle()); } } private: int testInt = 127; float testFloat = 1.5; OSCBundle generateTestBundle() { OSCBundle bundle; OSCMessage msg1 ("/test/fader"); msg1.addInt32 (testInt); OSCMessage msg2 ("/test/foo"); msg2.addString ("bar"); msg2.addFloat32 (testFloat); bundle.addElement (msg1); bundle.addElement (msg2); return bundle; } void expectBundleEqualsTestBundle (const OSCBundle& bundle) { expect (bundle.size() == 2); expect (bundle[0].isMessage()); expect (! bundle[0].isBundle()); expect (bundle[1].isMessage()); expect (! bundle[1].isBundle()); int numElementsCounted = 0; for (auto& element : bundle) { expect (element.isMessage()); expect (! element.isBundle()); ++numElementsCounted; } expectEquals (numElementsCounted, 2); auto* e = bundle.begin(); expect (e[0].getMessage().size() == 1); expect (e[0].getMessage().begin()->getInt32() == testInt); expect (e[1].getMessage().size() == 2); expect (e[1].getMessage()[1].getFloat32() == testFloat); } }; static OSCBundleTests OSCBundleUnitTests; //============================================================================== class OSCBundleElementTests : public UnitTest { public: OSCBundleElementTests() : UnitTest ("OSCBundle::Element class", "OSC") {} void runTest() { beginTest ("Construction from OSCMessage"); { float testFloat = -0.125; OSCMessage msg ("/test"); msg.addFloat32 (testFloat); OSCBundle::Element element (msg); expect (element.isMessage()); expect (element.getMessage().size() == 1); expect (element.getMessage()[0].getType() == OSCTypes::float32); expect (element.getMessage()[0].getFloat32() == testFloat); } } }; static OSCBundleElementTests OSCBundleElementUnitTests; #endif // JUCE_UNIT_TESTS } // namespace juce
class Solution { public: bool XXX(TreeNode* root) { if(!root) return true; stack<TreeNode*> left, right; left.push(root->left); right.push(root->right); while(!left.empty() && !right.empty()) { TreeNode* l = left.top(), * r = right.top(); left.pop(); right.pop(); if(!l && !r) continue; if(!l || !r || l->val != r->val) return false; left.push(l->left); left.push(l->right); right.push(r->right); right.push(r->left); } return true; } };
/** * @file * @ingroup containers * * Container which stores and transparently interpolates measurements from * multiple sensors. * * @defgroup containers * Storage types for data used by other modules. */ #ifndef WAVE_CONTAINERS_MEASUREMENT_CONTAINER_HPP #define WAVE_CONTAINERS_MEASUREMENT_CONTAINER_HPP namespace wave { /** @addtogroup containers * @{ */ /** Internal implementation details - for developers only */ namespace internal { template <typename T> struct measurement_container; } // namespace internal /** Container which stores and transparently interpolates measurements. * * @tparam T is the stored measurement type. The Measurement class template * in wave/containers/measurement.hpp is designed to be used here. * * However, any class can be used that has the following public members: * - `time_point` (any sortable type) * - `sensor_id` (any sortable type) * - `value` (any type) * * A type is sortable if it can be compared by `std::less`. * * Additionally, the non-member function * ``` * interpolate(const T&, const T&, const TimeType&) * ``` * must be defined for type `T`. */ template <typename T> class MeasurementContainer { public: // Types /** Alias for the template parameter, giving the type of Measurement stored * in this container */ using MeasurementType = T; /** Alias for the measurement's time type */ using TimeType = decltype(MeasurementType::time_point); /** Alias for the measurement's value type * Note this does *not* correspond to a typical container's value_type. */ using ValueType = decltype(MeasurementType::value); /** Alias for the type of the sensor id */ using SensorIdType = decltype(MeasurementType::sensor_id); using iterator = typename internal::measurement_container<T>::composite_type::iterator; using const_iterator = typename internal::measurement_container< T>::composite_type::const_iterator; using sensor_iterator = typename internal::measurement_container<T>::sensor_type::iterator; using size_type = std::size_t; // Constructors /** Default construct an empty container */ MeasurementContainer(); /** Construct the container with the contents of the range [first, last) */ template <typename InputIt> MeasurementContainer(InputIt first, InputIt last); // Capacity /** Return true if the container has no elements. */ bool empty() const noexcept; /** Return the number of elements in the container. */ size_type size() const noexcept; // Modifiers /** Insert a Measurement if a measurement for the same time and sensor does * not already exist. * * @return a pair p. If and only if insertion occurred, p.second is true and * p.first points to the element inserted. */ std::pair<iterator, bool> insert(const MeasurementType &); /** For each element of the range [first, last), inserts a Measurement if a * measurement for the same time and sensor does not already exist. * * @param first, last iterators representing a valid range of Measurements, * but not iterators into this container */ template <typename InputIt> void insert(InputIt first, InputIt last); /** Insert a Measurement constructed from the arguments if a measurement for * the same time and sensor does not already exist. * * @return a pair p. If and only if insertion occurred, p.second is true and * p.first points to the element inserted. */ template <typename... Args> std::pair<iterator, bool> emplace(Args &&... args); /** Delete the element with the matching time and sensor id, if one exists. * * @return the number of elements deleted. */ size_type erase(const TimeType &t, const SensorIdType &s); /** Delete the element at `position` * * @param position a valid dereferenceable iterator of this container * @return An iterator pointing to the element following the deleted one, or * `end()` if it was the last. */ iterator erase(iterator position) noexcept; /** Delete the elements in the range [first, last) * * @param first, last a valid range of this container * @return `last` */ iterator erase(iterator first, iterator last) noexcept; /** Delete all elements */ void clear() noexcept; // Retrieval /** Get the value of a measurement with corresponding time and sensor id */ ValueType get(const TimeType &t, const SensorIdType &s) const; /** Get all measurements from the given sensor * * @return a pair of iterators representing the start and end of the range. * If the range is empty, both iterators will be equal. * * @note because these iterators use the underlying ordered index of * sensor_ids, they are not the same type as those from `begin()`, * `getTimeWindow()`, etc. */ std::pair<sensor_iterator, sensor_iterator> getAllFromSensor( const SensorIdType &s) const noexcept; /** Get all measurements between the given times. * * @param start, end an inclusive range of times, with start <= end * * @return a pair of iterators representing the start and end of the range. * If the range is empty, both iterators will be equal. */ std::pair<iterator, iterator> getTimeWindow(const TimeType &start, const TimeType &end) const noexcept; // Iterators iterator begin() noexcept; iterator end() noexcept; const_iterator begin() const noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; private: using composite_type = typename internal::measurement_container<T>::composite_type; // Helper to get the composite index composite_type &composite() noexcept; const composite_type &composite() const noexcept; // Internal multi_index_container typename internal::measurement_container<T>::type storage; }; /** @} group containers */ } // namespace wave #include "impl/measurement_container.hpp" #endif // WAVE_CONTAINERS_MEASUREMENT_CONTAINER_HPP
// Copyright (c) 2016-2018 The Bitcoin Core developers // Copyright (c) 2018 Matt Corallo // Unlike the rest of Bitcoin Core, this file is // distributed under the Affero General Public License (AGPL v3) #include <blockencodings.h> #include <consensus/consensus.h> #include <consensus/validation.h> #include <chainparams.h> #include <crypto/sha256.h> #include <crypto/siphash.h> #include <random.h> #include <streams.h> #include <txmempool.h> #include <validation.h> #include <util/system.h> #include <open_hash_set.h> #include <unordered_map> #include <chrono> #define to_millis_double(t) (std::chrono::duration_cast<std::chrono::duration<double, std::chrono::milliseconds::period> >(t).count()) CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, bool fUseWTXID, bool fDeterministic) : nonce(fDeterministic ? block.GetHash().GetUint64(0) : GetRand(std::numeric_limits<uint64_t>::max())), shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) { FillShortTxIDSelector(); //TODO: Use our mempool prior to block acceptance to predictively fill more than just the coinbase prefilledtxn[0] = {0, block.vtx[0]}; for (size_t i = 1; i < block.vtx.size(); i++) { const CTransaction& tx = *block.vtx[i]; shorttxids[i - 1] = GetShortID(fUseWTXID ? tx.GetWitnessHash() : tx.GetHash()); } } void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const { CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); stream.reserve(80 + 8); stream << header << nonce; CSHA256 hasher; hasher.Write((unsigned char*)&(*stream.begin()), stream.size()); uint256 shorttxidhash; hasher.Finalize(shorttxidhash.begin()); shorttxidk0 = shorttxidhash.GetUint64(0); shorttxidk1 = shorttxidhash.GetUint64(1); } uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const uint256& txhash) const { static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids"); return SipHashUint256(shorttxidk0, shorttxidk1, txhash) & 0xffffffffffffL; } namespace { struct ShortIdIndexPair { uint64_t shortid : 48; uint64_t index : 16; ShortIdIndexPair(uint64_t shortid_in=0, uint16_t index_in=0) : shortid(shortid_in), index(index_in) {} }; static_assert(sizeof(ShortIdIndexPair) == 8, ""); struct ShortIdIndexPairHasher { uint64_t operator()(const ShortIdIndexPair& elem) const { return elem.shortid; } }; struct ShortIdIndexPairEqual { bool operator()(const ShortIdIndexPair& a, const ShortIdIndexPair& b) const { return a.shortid == b.shortid; } }; struct ShortIdIndexPairIsNull { bool operator()(const ShortIdIndexPair& elem) const { return elem.shortid == 0 && elem.index == 0; } }; } // anonymous namespace ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>>& extra_txn) { const bool fBench = LogAcceptCategory(BCLog::BENCH); std::chrono::steady_clock::time_point start; if (fBench) start = std::chrono::steady_clock::now(); if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty())) return READ_STATUS_INVALID; if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > MAX_BLOCK_WEIGHT / MIN_SERIALIZABLE_TRANSACTION_WEIGHT) return READ_STATUS_INVALID; assert(header.IsNull() && txn_available.empty()); header = cmpctblock.header; txn_available.resize(cmpctblock.BlockTxCount()); int32_t lastprefilledindex = -1; for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) { if (cmpctblock.prefilledtxn[i].tx->IsNull()) return READ_STATUS_INVALID; lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; //index is a uint16_t, so can't overflow here if (lastprefilledindex > std::numeric_limits<uint16_t>::max()) return READ_STATUS_INVALID; if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) { // If we are inserting a tx at an index greater than our full list of shorttxids // plus the number of prefilled txn we've inserted, then we have txn for which we // have neither a prefilled txn or a shorttxid! return READ_STATUS_INVALID; } txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx; } prefilled_count = cmpctblock.prefilledtxn.size(); if (cmpctblock.shorttxids.empty()) { return READ_STATUS_OK; } // Calculate map of txids -> positions and check mempool to see what we have (or don't) std::chrono::steady_clock::time_point prefilled_filled; if (fBench) prefilled_filled = std::chrono::steady_clock::now(); // Because well-formed cmpctblock messages will have a (relatively) uniform distribution // of short IDs, any highly-uneven distribution of elements can be safely treated as a // READ_STATUS_FAILED. open_hash_set<ShortIdIndexPair, ShortIdIndexPairIsNull, ShortIdIndexPairHasher, ShortIdIndexPairEqual> shorttxids(cmpctblock.shorttxids.size()); uint16_t index_offset = 0; for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) { while (txn_available[i + index_offset]) index_offset++; auto i_res = shorttxids.insert(ShortIdIndexPair(cmpctblock.shorttxids[i], i + index_offset)); if (!i_res.second) { return READ_STATUS_FAILED; } } // TODO: in the shortid-collision case, we should instead request both transactions // which collided. Falling back to full-block-request here is overkill. if (shorttxids.size() != cmpctblock.shorttxids.size()) return READ_STATUS_FAILED; // Short ID collision std::vector<bool> have_txn(txn_available.size()); std::chrono::steady_clock::time_point shortids_mapped; if (fBench) shortids_mapped = std::chrono::steady_clock::now(); { LOCK(pool->cs); const std::vector<uint256>& vTxHashes = pool->vTxHashes; const std::vector<CTxMemPool::txiter>& vTxnUnordered = pool->vTxnUnordered; uint64_t shortid = vTxHashes.size() > 0 ? cmpctblock.GetShortID(vTxHashes[0]) : 0; for (size_t i = 0; i < vTxHashes.size(); i++) { uint64_t next_shortid = 0; __builtin_prefetch(vTxHashes.data() + ((i + 2) * sizeof(decltype(pool->vTxHashes)::value_type)), 0); if (i + 1 < vTxHashes.size()) { next_shortid = cmpctblock.GetShortID(vTxHashes[i + 1]); } const ShortIdIndexPair *p = shorttxids.find_fast(ShortIdIndexPair(shortid)); if (p) { if (!have_txn[p->index]) { txn_available[p->index] = vTxnUnordered[i]->GetSharedTx(); have_txn[p->index] = true; mempool_count++; } else { // If we find two mempool txn that match the short id, just request it. // This should be rare enough that the extra bandwidth doesn't matter, // but eating a round-trip due to FillBlock failure would be annoying if (txn_available[p->index]) { txn_available[p->index].reset(); mempool_count--; } } } shortid = next_shortid; // Though ideally we'd continue scanning for the two-txn-match-shortid case, // the performance win of an early exit here is too good to pass up and worth // the extra risk. if (mempool_count == shorttxids.size()) break; } } uint64_t shortid = extra_txn.size() > 0 ? cmpctblock.GetShortID(extra_txn[0].first) : 0; for (size_t i = 0; i < extra_txn.size(); i++) { uint64_t next_shortid = 0; if (i + 1 < extra_txn.size()) { next_shortid = cmpctblock.GetShortID(extra_txn[i + 1].first); } const ShortIdIndexPair *p = shorttxids.find_fast(ShortIdIndexPair(shortid)); if (p) { if (!have_txn[p->index]) { txn_available[p->index] = extra_txn[i].second; have_txn[p->index] = true; mempool_count++; extra_count++; } else { // If we find two mempool/extra txn that match the short id, just // request it. // This should be rare enough that the extra bandwidth doesn't matter, // but eating a round-trip due to FillBlock failure would be annoying // Note that we don't want duplication between extra_txn and mempool to // trigger this case, so we compare witness hashes first if (txn_available[p->index] && txn_available[p->index]->GetWitnessHash() != extra_txn[i].second->GetWitnessHash()) { txn_available[p->index].reset(); mempool_count--; extra_count--; } } } shortid = next_shortid; // Though ideally we'd continue scanning for the two-txn-match-shortid case, // the performance win of an early exit here is too good to pass up and worth // the extra risk. if (mempool_count == shorttxids.size()) break; } if (fBench) { std::chrono::steady_clock::time_point finished(std::chrono::steady_clock::now()); LogPrintf("PartiallyDownloadedBlock::InitData took %lf %lf %lf ms\n", to_millis_double(prefilled_filled - start), to_millis_double(shortids_mapped - prefilled_filled), to_millis_double(finished - shortids_mapped)); } LogPrint(BCLog::CMPCTBLOCK, "Initialized PartiallyDownloadedBlock for block %s using a cmpctblock of size %lu\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock, PROTOCOL_VERSION)); return READ_STATUS_OK; } bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const { assert(!header.IsNull()); assert(index < txn_available.size()); return txn_available[index] != nullptr; } ReadStatus PartiallyDownloadedBlock::FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing) { assert(!header.IsNull()); uint256 hash = header.GetHash(); block = header; block.vtx.resize(txn_available.size()); size_t tx_missing_offset = 0; for (size_t i = 0; i < txn_available.size(); i++) { if (!txn_available[i]) { if (vtx_missing.size() <= tx_missing_offset) return READ_STATUS_INVALID; block.vtx[i] = vtx_missing[tx_missing_offset++]; } else block.vtx[i] = std::move(txn_available[i]); } // Make sure we can't call FillBlock again. header.SetNull(); txn_available.clear(); if (vtx_missing.size() != tx_missing_offset) return READ_STATUS_INVALID; CValidationState state; if (!CheckBlock(block, state, Params().GetConsensus())) { // TODO: We really want to just check merkle tree manually here, // but that is expensive, and CheckBlock caches a block's // "checked-status" (in the CBlock?). CBlock should be able to // check its own merkle root and cache that check. if (state.GetReason() == ValidationInvalidReason::BLOCK_MUTATED) return READ_STATUS_FAILED; // Possible Short ID collision return READ_STATUS_CHECKBLOCK_FAILED; } LogPrint(BCLog::CMPCTBLOCK, "Successfully reconstructed block %s with %lu txn prefilled, %lu txn from mempool (incl at least %lu from extra pool) and %lu txn requested\n", hash.ToString(), prefilled_count, mempool_count, extra_count, vtx_missing.size()); if (vtx_missing.size() < 5) { for (const auto& tx : vtx_missing) { LogPrint(BCLog::CMPCTBLOCK, "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetHash().ToString()); } } return READ_STATUS_OK; } CBlockHeaderAndLengthShortTxIDs::CBlockHeaderAndLengthShortTxIDs(const CBlock& block, codec_version_t const cv, bool const fDeterministic) : CBlockHeaderAndShortTxIDs(block, true, fDeterministic), codec_version(cv), txlens(shorttxids.size()) { int32_t lastprefilledindex = -1; uint16_t index_offset = 0; auto prefilledit = prefilledtxn.cbegin(); for (size_t i = 0; i < block.vtx.size(); i++) { if (prefilledit != prefilledtxn.cend() && (uint32_t)(lastprefilledindex + prefilledit->index + 1) == i + index_offset) { lastprefilledindex += prefilledit->index + 1; prefilledit++; index_offset++; } else { const CTransactionRef& tx = block.vtx[i]; txlens[i - index_offset] = GetSerializeSize(CTxCompressor(*tx, codec_version), PROTOCOL_VERSION); } } } template<typename F> ReadStatus CBlockHeaderAndLengthShortTxIDs::FillIndexOffsetMap(F& callback) const { if (txlens.size() != shorttxids.size()) return READ_STATUS_INVALID; // The first version is much faster, but for a 0.5-1ms hit, the second // version is much smarter about avoiding crossing chunk boundaries. #if MAX_CHUNK_CODED_BLOCK_SIZE_FACTOR == 1 size_t current_index = 0; int32_t lastprefilledindex = -1; uint16_t index_offset = 0; auto prefilledit = prefilledtxn.cbegin(); for (size_t i = 0; i < txlens.size(); i++) { while (prefilledit != prefilledtxn.cend() && (uint32_t)(lastprefilledindex + prefilledit->index + 1) == i + index_offset) { lastprefilledindex += prefilledit->index + 1; prefilledit++; index_offset++; } callback(current_index, i + index_offset); current_index += txlens[i]; } return READ_STATUS_OK; #elif MAX_CHUNK_CODED_BLOCK_SIZE_FACTOR == 2 std::multimap<size_t, size_t> indexes_left; // size -> index int32_t lastprefilledindex = -1; uint16_t index_offset = 0; auto prefilledit = prefilledtxn.cbegin(); for (size_t i = 0; i < txlens.size(); i++) { while (prefilledit != prefilledtxn.cend() && (uint32_t)(lastprefilledindex + prefilledit->index + 1) == i + index_offset) { lastprefilledindex += prefilledit->index + 1; prefilledit++; index_offset++; } indexes_left.insert(std::make_pair(txlens[i], i + index_offset)); } size_t current_index = 0; while (!indexes_left.empty()) { std::multimap<size_t, size_t>::reverse_iterator lastit = indexes_left.rbegin(); callback(current_index, lastit->second); current_index += lastit->first; lastit++; // base() returns next (ie prev of reverse) element indexes_left.erase(lastit.base()); size_t size_left = FEC_CHUNK_SIZE - (current_index % FEC_CHUNK_SIZE); while (!indexes_left.empty() && size_left > indexes_left.begin()->first) { std::multimap<size_t, size_t>::iterator it = indexes_left.upper_bound(size_left); assert(it != indexes_left.begin()); it--; assert(it->first <= size_left); callback(current_index, it->second); current_index += it->first; size_left -= it->first; indexes_left.erase(it); } if (current_index > MAX_BLOCK_SERIALIZED_SIZE) return READ_STATUS_INVALID; } return READ_STATUS_OK; #else #error Need size factor of 1 or 2 #endif } #define DIV_CEIL(a, b) (((a) + (b) - 1) / (b)) struct FillIndexOffsetMapSerializer { VectorOutputStream& stream; const CBlock& block; codec_version_t codec_version; void operator()(size_t offset, size_t index) { if (stream.pos() < offset) stream.skip_bytes(offset - stream.pos()); assert(stream.pos() == offset); const CTransactionRef& tx = block.vtx[index]; stream << CTxCompressor(*tx, codec_version); } }; ChunkCodedBlock::ChunkCodedBlock(const CBlock& block, const CBlockHeaderAndLengthShortTxIDs& headerAndIDs) { codedBlock.reserve(MAX_BLOCK_SERIALIZED_SIZE * 1.2); VectorOutputStream stream(&codedBlock, SER_NETWORK, PROTOCOL_VERSION); { FillIndexOffsetMapSerializer ser{stream, block, headerAndIDs.codec_ver()}; auto const ret = headerAndIDs.FillIndexOffsetMap(ser); assert(ret == READ_STATUS_OK); } codedBlock.resize(DIV_CEIL(codedBlock.size() + 80, FEC_CHUNK_SIZE) * FEC_CHUNK_SIZE); // Append the block header at the end of the last chunk. We dont currently // use this in decode, but this should allow us to decode a block without // ever having fully received the header-and-short-ids. if (stream.pos() < codedBlock.size() - 80) stream.skip_bytes(codedBlock.size() - 80 - stream.pos()); assert(stream.pos() == codedBlock.size() - 80); stream << headerAndIDs.header; } static inline uint16_t get_txlens_index(const std::map<uint16_t, uint16_t>& txn_prefilled, uint16_t real_index) { if (txn_prefilled.empty()) return real_index; std::map<uint16_t, uint16_t>::const_iterator it = txn_prefilled.upper_bound(real_index); it--; return real_index - it->second; } struct FillIndexOffsetMapCallback { std::map<size_t, size_t>& index_offsets; void operator()(size_t offset, size_t index) { index_offsets[offset] = index; } }; ReadStatus PartiallyDownloadedChunkBlock::InitData(const CBlockHeaderAndLengthShortTxIDs& comprblock, const std::vector<std::pair<uint256, CTransactionRef>>& extra_txn) { const bool fBench = LogAcceptCategory(BCLog::BENCH); std::chrono::steady_clock::time_point start; if (fBench) start = std::chrono::steady_clock::now(); codec_version = comprblock.codec_version; if (comprblock.txlens.size() != comprblock.shorttxids.size()) return READ_STATUS_INVALID; ReadStatus status; // We limit number of mempool txn iterated over because it costs a lot of time, // and a few extra transactions missed is just fine. status = PartiallyDownloadedBlock::InitData(comprblock, extra_txn); if (status != READ_STATUS_OK) return status; std::chrono::steady_clock::time_point base_data_initd; if (fBench) base_data_initd = std::chrono::steady_clock::now(); *decoded_block = header; allTxnFromMempool = true; for (const std::shared_ptr<const CTransaction>& tx : txn_available) allTxnFromMempool &= tx ? true : false; if (allTxnFromMempool) return READ_STATUS_OK; FillIndexOffsetMapCallback fiomCallback{index_offsets}; status = comprblock.FillIndexOffsetMap(fiomCallback); if (status != READ_STATUS_OK) return status; std::chrono::steady_clock::time_point index_offset_mapped; if (fBench) index_offset_mapped = std::chrono::steady_clock::now(); int32_t prefilled_txn_offset = -1; for (size_t i = 0; i < comprblock.prefilledtxn.size(); i++) { prefilled_txn_offset += comprblock.prefilledtxn[i].index + 1; bool const inserted = txn_prefilled.insert(std::make_pair(prefilled_txn_offset, i + 1)).second; assert(inserted); } if (index_offsets.size()) { size_t codedBlockSize = DIV_CEIL( index_offsets.rbegin()->first + comprblock.txlens[get_txlens_index(txn_prefilled, index_offsets.rbegin()->second)] + 80, FEC_CHUNK_SIZE) * FEC_CHUNK_SIZE; chunksAvailable.resize(codedBlockSize / FEC_CHUNK_SIZE); remainingChunks = codedBlockSize / FEC_CHUNK_SIZE; codedBlock.resize(codedBlockSize); } fill_coding_index_offsets_it = index_offsets.begin(); if (fBench) { std::chrono::steady_clock::time_point finished(std::chrono::steady_clock::now()); LogPrintf("PartiallyDownloadedChunkBlock::InitData took %lf %lf %lf ms\n", to_millis_double(base_data_initd - start), to_millis_double(index_offset_mapped - base_data_initd), to_millis_double(finished - index_offset_mapped)); } return READ_STATUS_OK; } bool PartiallyDownloadedChunkBlock::SerializeTransaction(VectorOutputStream& stream, std::map<size_t, size_t>::iterator it) { if (stream.pos() < it->first) stream.skip_bytes(it->first - stream.pos()); assert(stream.pos() == it->first); // We're fine blindly serializing tx -> either it came from mempool and is fully valid, // or it was received over the wire, so it shouldn't be able to eat all our memory. const CTransactionRef& tx = PartiallyDownloadedBlock::txn_available[it->second]; /* We're serializing txns in order to form the chunk-coded block in advance * of actually receiving it from the UDP peer. Hence, we must compress txns * with the same codec that is going to be used by tx peer. The codec has * been advertised within the CBlockHeaderAndLengthShortTxIDs structure. */ stream << CTxCompressor(*tx, codec_version); it++; if (it == index_offsets.end()) return true; else return stream.pos() <= it->first; } ReadStatus PartiallyDownloadedChunkBlock::DoIterativeFill(size_t& firstChunkProcessed) { std::map<size_t, size_t>::iterator current_it = fill_coding_index_offsets_it; size_t current_index = current_it->first; VectorOutputStream stream(&codedBlock, SER_NETWORK, PROTOCOL_VERSION, current_index); firstChunkProcessed = current_index / FEC_CHUNK_SIZE; for (; fill_coding_index_offsets_it != index_offsets.end(); fill_coding_index_offsets_it++) { if (fill_coding_index_offsets_it->first / FEC_CHUNK_SIZE == current_index / FEC_CHUNK_SIZE) haveChunk &= IsTxAvailable(fill_coding_index_offsets_it->second); else break; } // First process the chunk we were most recently in if (haveChunk) { for (; current_it != fill_coding_index_offsets_it; current_it++) { if (!SerializeTransaction(stream, current_it)) return READ_STATUS_FAILED; // Could be a shorttxid collision } for (size_t i = current_index / FEC_CHUNK_SIZE; i < fill_coding_index_offsets_it->first / FEC_CHUNK_SIZE; i++) { if (i == chunksAvailable.size() - 1) { // Write the header to the last 80 bytes of the last chunk size_t header_pos = chunksAvailable.size() * FEC_CHUNK_SIZE - 80; if (stream.pos() < header_pos) stream.skip_bytes(header_pos - stream.pos()); assert(stream.pos() == header_pos); stream << header; } if (!chunksAvailable[i]) remainingChunks--; chunksAvailable[i] = true; } }//TODO else if (haveMostRecentlyCheckedTx && mostRecentlyCheckedTxFillsChunk(s)OnItsOwn //TODO: Handle chunk that spanned a border and filled up at least one chunk on its own // Note that the current FillIndexOffsetMap implementation will never use this haveChunk = true; // Next chunk gets a fresh start // If we're gonna try to process this chunk later... if (fill_coding_index_offsets_it != index_offsets.end() && IsTxAvailable(fill_coding_index_offsets_it->second)) { current_index = fill_coding_index_offsets_it->first; if (current_index % FEC_CHUNK_SIZE != 0) { // If we don't start on a chunk boundry, we assume the previous transaction // came into our chunk, as otherwise our packing algorithm is braindead assert(fill_coding_index_offsets_it != index_offsets.begin()); std::map<size_t, size_t>::iterator previt = fill_coding_index_offsets_it; previt--; if (IsTxAvailable(previt->second)) { if (stream.pos() <= previt->first) { // If previt was not already encoded... if (!SerializeTransaction(stream, previt)) return READ_STATUS_FAILED; // Could be a shorttxid collision } } else haveChunk = false; // I'm sorry, but its just not gonna work out - its not you, its me } } return READ_STATUS_OK; } bool PartiallyDownloadedChunkBlock::IsIterativeFillDone() const { return allTxnFromMempool || fill_coding_index_offsets_it == index_offsets.end(); } uint256& PartiallyDownloadedChunkBlock::GetBlockHash() const { assert(!header.IsNull()); if (block_hash.IsNull()) block_hash = header.GetHash(); return block_hash; } bool PartiallyDownloadedChunkBlock::IsHeaderNull() const { return header.IsNull(); } bool PartiallyDownloadedChunkBlock::IsBlockAvailable() const { assert(!header.IsNull()); return allTxnFromMempool || !remainingChunks; } bool PartiallyDownloadedChunkBlock::AreAllTxnsInMempool() const { assert(!header.IsNull()); return allTxnFromMempool; } bool PartiallyDownloadedChunkBlock::AreChunksAvailable() const { return !header.IsNull() && !allTxnFromMempool; } ReadStatus PartiallyDownloadedChunkBlock::FinalizeBlock() { const bool fBench = LogAcceptCategory(BCLog::BENCH); std::chrono::steady_clock::time_point start; if (fBench) start = std::chrono::steady_clock::now(); assert(!header.IsNull()); assert(IsBlockAvailable()); CBlock& block = *decoded_block; block.vtx.clear(); block.vtx.reserve(txn_available.size()); for (size_t i = 0; i < txn_available.size(); i++) { if (txn_available[i]) { block.vtx.emplace_back(std::move(txn_available[i])); } else { assert(!allTxnFromMempool); block.vtx.emplace_back(); } } txn_available.clear(); if (allTxnFromMempool) { block_finalized = true; return READ_STATUS_OK; } std::chrono::steady_clock::time_point mempool_filled; if (fBench) mempool_filled = std::chrono::steady_clock::now(); // TODO: This is really slow (like several ms) // We should migrate to keeping the partially-decoded block as a unique_ptr // and decode transactions as we go...this will not only save the deserialize // time we spend here, but by calling GetHash() at that time, save the // hashing time we'll spend later to check the hash of each transaction. VectorInputStream stream(&codedBlock, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_CACHE); for (auto it = index_offsets.cbegin(); it != index_offsets.cend(); it++) { if (block.vtx[it->second]) continue; try { if (it->first < stream.pos()) // Last transaction was longer than expected return READ_STATUS_FAILED; // Could be a shorttxid collision stream.seek(it->first); stream >> REF(CTxCompressor(block.vtx[it->second], codec_version)); } catch (const std::ios_base::failure& e) { return READ_STATUS_FAILED; // Could be a shorttxid collision } } if (fBench) { std::chrono::steady_clock::time_point finished(std::chrono::steady_clock::now()); LogPrintf("PartiallyDownloadedChunkBlock::FinalizeBlock took %lf %lf ms\n", to_millis_double(mempool_filled - start), to_millis_double(finished - mempool_filled)); } block_finalized = true; return READ_STATUS_OK; } size_t PartiallyDownloadedChunkBlock::GetChunkCount() const { assert(AreChunksAvailable()); return chunksAvailable.size(); } bool PartiallyDownloadedChunkBlock::IsChunkAvailable(size_t chunk) const { assert(chunk < GetChunkCount()); return chunksAvailable[chunk]; } unsigned char* PartiallyDownloadedChunkBlock::GetChunk(size_t chunk) { assert(chunk < GetChunkCount()); return &codedBlock[chunk * FEC_CHUNK_SIZE]; } void PartiallyDownloadedChunkBlock::MarkChunkAvailable(size_t chunk) { assert(chunk < GetChunkCount()); if (!chunksAvailable[chunk]) remainingChunks--; chunksAvailable[chunk] = true; }
// Copyright (c) 2018 The GAM Authors int Worker::ProcessLocalRead(WorkRequest* wr) { epicAssert(wr->addr); epicAssert(!(wr->flag & ASYNC)); epicAssert(wr->size < MAX_REQUEST_SIZE); if(!(wr->flag & FENCE)) { Fence* fence = fences_.at(wr->fd); fence->lock(); if(unlikely(IsMFenced(fence, wr))) { AddToFence(fence, wr); epicLog(LOG_DEBUG, "fenced (mfenced = %d, sfenced = %d): %d", fence->mfenced, fence->sfenced, wr->op); fence->unlock(); return FENCE_PENDING; } fence->unlock(); } if(likely(IsLocal(wr->addr))) { GAddr start = wr->addr; GAddr start_blk = TOBLOCK(start); GAddr end = GADD(start, wr->size); if(TOBLOCK(end-1) != start_blk) { epicLog(LOG_INFO, "read/write split to multiple blocks"); } for(GAddr i = start_blk; i < end;) { epicAssert(!(wr->flag & COPY) || ((wr->flag & COPY) && (wr->flag & ASYNC))); GAddr nextb = BADD(i, 1); void* laddr = ToLocal(i); directory.lock(laddr); GAddr gs = i > start ? i : start; void* ls = (void*)((ptr_t)wr->ptr + GMINUS(gs, start)); int len = nextb > end ? GMINUS(end, gs) : GMINUS(nextb, gs); memcpy(ls, ToLocal(gs), len); directory.unlock(laddr); i = nextb; } } else { Client* cli = GetClient(wr->addr); SubmitRequest(cli, wr, ADD_TO_PENDING | REQUEST_SEND); return REMOTE_REQUEST; } #ifdef MULTITHREAD if(wr->flag & TO_SERVE || wr->flag & FENCE) { #endif /* * notify the app thread directly * this can only happen when the request can be fulfilled locally * or we don't need to wait for reply from remote node */ if(Notify(wr)) { epicLog(LOG_WARNING, "cannot wake up the app thread"); } #ifdef MULTITHREAD } #endif return SUCCESS; } int Worker::ProcessLocalWrite(WorkRequest* wr) { epicAssert(wr->addr); epicAssert(wr->size < MAX_REQUEST_SIZE); epicAssert(wr->flag & ASYNC); Fence* fence = fences_.at(wr->fd); if(!(wr->flag & FENCE)) { fence->lock(); if(unlikely(IsFenced(fence, wr))) { epicLog(LOG_DEBUG, "fenced(mfenced = %d, sfenced = %d): %d", fence->mfenced, fence->sfenced, wr->op); AddToFence(fence, wr); fence->unlock(); return FENCE_PENDING; } fence->unlock(); } if((wr->flag & ASYNC) && !(wr->flag & TO_SERVE)) { //fences_[wr->fd].pending_writes++; fence->pending_writes++; epicLog(LOG_DEBUG, "Local: one more pending write"); } if(likely(IsLocal(wr->addr))) { GAddr start = wr->addr; GAddr start_blk = TOBLOCK(start); GAddr end = GADD(start, wr->size); if(TOBLOCK(end-1) != start_blk) { epicLog(LOG_INFO, "read/write split to multiple blocks"); } for(GAddr i = start_blk; i < end;) { epicAssert(!(wr->flag & COPY) || ((wr->flag & COPY) && (wr->flag & ASYNC))); GAddr nextb = BADD(i, 1); void* laddr = ToLocal(i); directory.lock(laddr); GAddr gs = i > start ? i : start; void* ls = (void*)((ptr_t)wr->ptr + GMINUS(gs, start)); int len = nextb > end ? GMINUS(end, gs) : GMINUS(nextb, gs); logWrite(gs, len, ls); memcpy(ToLocal(gs), len, ls); directory.unlock(laddr); i = nextb; } } else { Client* cli = GetClient(wr->addr); if(wr->flag & ASYNC) { if(!wr->IsACopy()) { wr = wr->Copy(); } } SubmitRequest(cli, wr, ADD_TO_PENDING | REQUEST_SEND); return REMOTE_REQUEST; } #ifdef MULTITHREAD if(wr->flag & ASYNC || wr->flag & TO_SERVE || wr->flag & FENCE) { #endif /* * notify the app thread directly * this can only happen when the request can be fulfilled locally * or we don't need to wait for reply from remote node */ if(Notify(wr)) { epicLog(LOG_WARNING, "cannot wake up the app thread"); } #ifdef MULTITHREAD } #endif return SUCCESS; } int Worker::ProcessLocalRLock(WorkRequest* wr) { epicAssert(wr->addr); epicAssert(!(wr->flag & ASYNC)); //epicAssert(!(wr->flag & FENCE)); if(!(wr->flag & FENCE)) { Fence* fence = fences_.at(wr->fd); //if(fence->mfenced || fence->sfenced) { fence->lock(); if(IsFenced(fence, wr)) { AddToFence(fence, wr); fence->unlock(); epicLog(LOG_DEBUG, "fenced (mfenced = %d, sfenced = %d): %d", fence->mfenced, fence->sfenced, wr->op); return FENCE_PENDING; } else if (fence->pending_writes) { //we only mark fenced when there are pending writes fence->mfenced = true; epicLog(LOG_DEBUG, "mfenced from RLOCK!"); AddToFence(fence, wr); fence->unlock(); return FENCE_PENDING; } fence->unlock(); } if(IsLocal(wr->addr)) { GAddr start = wr->addr; GAddr start_blk = TOBLOCK(start); void* laddr = ToLocal(start_blk); directory.lock(laddr); int ret = directory.RLock(ToLocal(wr->addr)); if(ret) { //fail to lock epicLog(LOG_INFO, "cannot lock addr %lx, will try later", wr->addr); if(wr->flag & TRY_LOCK) { wr->status = LOCK_FAILED; } else { //to_serve_local_requests[start_blk].push(wr); AddToServeLocalRequest(start_blk, wr); directory.unlock(laddr); return IN_TRANSITION; } } directory.unlock(laddr); } else { Client* cli = GetClient(wr->addr); SubmitRequest(cli, wr, ADD_TO_PENDING | REQUEST_SEND); return REMOTE_REQUEST; } #ifdef MULTITHREAD if(wr->flag & TO_SERVE || wr->flag & FENCE) { #endif /* * notify the app thread directly * this can only happen when the request can be fulfilled locally * or we don't need to wait for reply from remote node */ if(Notify(wr)) { epicLog(LOG_WARNING, "cannot wake up the app thread"); } #ifdef MULTITHREAD } #endif return SUCCESS; } int Worker::ProcessLocalWLock(WorkRequest* wr) { epicAssert(wr->addr); epicAssert(!(wr->flag & ASYNC)); //epicAssert(!(wr->flag & FENCE)); if(!(wr->flag & FENCE)) { Fence* fence = fences_.at(wr->fd); //if(fence->mfenced || fence->sfenced) { fence->lock(); if(IsFenced(fence, wr)) { //fence->pending_works.push(wr); AddToFence(fence, wr); fence->unlock(); epicLog(LOG_DEBUG, "fenced (mfenced = %d, sfenced = %d): %d", fence->mfenced, fence->sfenced, wr->op); return FENCE_PENDING; } else if (fence->pending_writes) { //we only mark fenced when there are pending writes fence->mfenced = true; epicLog(LOG_DEBUG, "mfenced from WLOCK!"); //fence->pending_works.push(wr); AddToFence(fence, wr); fence->unlock(); return FENCE_PENDING; } fence->unlock(); } if(IsLocal(wr->addr)) { GAddr start = wr->addr; GAddr start_blk = TOBLOCK(start); void* laddr = ToLocal(start_blk); directory.lock(laddr); int ret = directory.WLock(ToLocal(wr->addr)); if(ret) { //failed to lock epicLog(LOG_INFO, "cannot lock addr %lx, will try later", wr->addr); if(wr->flag & TRY_LOCK) { wr->status = LOCK_FAILED; } else { //to_serve_local_requests[start_blk].push(wr); AddToServeLocalRequest(start_blk, wr); directory.unlock(laddr); return IN_TRANSITION; } } directory.unlock(laddr); } else { Client* cli = GetClient(wr->addr); SubmitRequest(cli, wr, ADD_TO_PENDING | REQUEST_SEND); return REMOTE_REQUEST; } #ifdef MULTITHREAD if(wr->flag & TO_SERVE || wr->flag & FENCE) { #endif /* * notify the app thread directly * this can only happen when the request can be fulfilled locally * or we don't need to wait for reply from remote node */ if(Notify(wr)) { epicLog(LOG_WARNING, "cannot wake up the app thread"); } #ifdef MULTITHREAD } #endif return SUCCESS; } int Worker::ProcessLocalUnLock(WorkRequest* wr) { if(!(wr->flag & FENCE)) { Fence* fence = fences_.at(wr->fd); fence->lock(); if(IsFenced(fence, wr)) { AddToFence(fence, wr); fence->unlock(); epicLog(LOG_DEBUG, "fenced (mfenced = %d, sfenced = %d): %d", fence->mfenced, fence->sfenced, wr->op); return FENCE_PENDING; } else if (fence->pending_writes) { //we only mark fenced when there are pending writes fence->mfenced = true; epicLog(LOG_DEBUG, "mfenced from UNLOCK!"); AddToFence(fence, wr); fence->unlock(); return FENCE_PENDING; } fence->unlock(); } if(IsLocal(wr->addr)) { GAddr start_blk = TOBLOCK(wr->addr); void* laddr = ToLocal(start_blk); directory.lock(laddr); directory.UnLock(ToLocal(wr->addr)); directory.unlock(laddr); } else { Client* cli = GetClient(wr->addr); #ifdef ASYNC_UNLOCK SubmitRequest(cli, wr); //no need for reply #else SubmitRequest(cli, wr, ADD_TO_PENDING | REQUEST_SEND); //no need for reply #endif return REMOTE_REQUEST; } ProcessToServeRequest(wr); #ifdef MULTITHREAD if(wr->flag & TO_SERVE || wr->flag & FENCE) { #endif /* * notify the app thread directly * this can only happen when the request can be fulfilled locally * or we don't need to wait for reply from remote node */ if(Notify(wr)) { epicLog(LOG_WARNING, "cannot wake up the app thread"); } #ifdef MULTITHREAD } #endif return SUCCESS; }
# ifndef CPPAD_CORE_ATOMIC_TWO_FOR_SPARSE_JAC_HPP # define CPPAD_CORE_ATOMIC_TWO_FOR_SPARSE_JAC_HPP /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-18 Bradley M. Bell CppAD is distributed under the terms of the Eclipse Public License Version 2.0. This Source Code may also be made available under the following Secondary License when the conditions for such availability set forth in the Eclipse Public License, Version 2.0 are satisfied: GNU General Public License, Version 2.0 or later. ---------------------------------------------------------------------------- */ /* $begin atomic_two_for_sparse_jac$$ $spell sq mul.hpp afun Jacobian jac const CppAD std bool std $$ $section Atomic Forward Jacobian Sparsity Patterns$$ $head Syntax$$ $icode%ok% = %afun%.for_sparse_jac(%q%, %r%, %s%, %x%) %$$ $head Deprecated 2016-06-27$$ $icode%ok% = %afun%.for_sparse_jac(%q%, %r%, %s%) %$$ $head Purpose$$ This function is used by $cref ForSparseJac$$ to compute Jacobian sparsity patterns. For a fixed matrix $latex R \in \B{R}^{n \times q}$$, the Jacobian of $latex f( x + R * u)$$ with respect to $latex u \in \B{R}^q$$ is $latex \[ S(x) = f^{(1)} (x) * R \] $$ Given a $cref/sparsity pattern/glossary/Sparsity Pattern/$$ for $latex R$$, $code for_sparse_jac$$ computes a sparsity pattern for $latex S(x)$$. $head Implementation$$ If you are using $cref ForSparseJac$$, $cref ForSparseHes$$, or $cref RevSparseHes$$, one of the versions of this virtual function must be defined by the $cref/atomic_user/atomic_two_ctor/atomic_user/$$ class. $subhead q$$ The argument $icode q$$ has prototype $codei% size_t %q% %$$ It specifies the number of columns in $latex R \in \B{R}^{n \times q}$$ and the Jacobian $latex S(x) \in \B{R}^{m \times q}$$. $subhead r$$ This argument has prototype $codei% const %atomic_sparsity%& %r% %$$ and is a $cref/atomic_sparsity/atomic_two_option/atomic_sparsity/$$ pattern for $latex R \in \B{R}^{n \times q}$$. $subhead s$$ This argument has prototype $codei% %atomic_sparsity%& %s% %$$ The input values of its elements are not specified (must not matter). Upon return, $icode s$$ is a $cref/atomic_sparsity/atomic_two_option/atomic_sparsity/$$ pattern for $latex S(x) \in \B{R}^{m \times q}$$. $subhead x$$ $index deprecated$$ The argument has prototype $codei% const CppAD::vector<%Base%>& %x% %$$ and size is equal to the $icode n$$. This is the $cref Value$$ value corresponding to the parameters in the vector $cref/ax/atomic_two_afun/ax/$$ (when the atomic function was called). To be specific, if $codei% if( Parameter(%ax%[%i%]) == true ) %x%[%i%] = Value( %ax%[%i%] ); else %x%[%i%] = CppAD::numeric_limits<%Base%>::quiet_NaN(); %$$ The version of this function with out the $icode x$$ argument is deprecated; i.e., you should include the argument even if you do not use it. $head ok$$ The return value $icode ok$$ has prototype $codei% bool %ok% %$$ If it is $code true$$, the corresponding evaluation succeeded, otherwise it failed. $end ----------------------------------------------------------------------------- */ namespace CppAD { // BEGIN_CPPAD_NAMESPACE /*! \file atomic/two_for_sparse_jac.hpp Atomic forward Jacobian sparsity pattern. */ /*! Link, after case split, from for_jac_sweep to atomic_base. \param q is the column dimension for the Jacobian sparsity partterns. \param r is the Jacobian sparsity pattern for the argument vector x \param s is the Jacobian sparsity pattern for the result vector y \param x is the integer value for x arguments that are parameters. */ template <class Base> bool atomic_base<Base>::for_sparse_jac( size_t q , const vector< std::set<size_t> >& r , vector< std::set<size_t> >& s , const vector<Base>& x ) { return false; } template <class Base> bool atomic_base<Base>::for_sparse_jac( size_t q , const vector<bool>& r , vector<bool>& s , const vector<Base>& x ) { return false; } template <class Base> bool atomic_base<Base>::for_sparse_jac( size_t q , const vectorBool& r , vectorBool& s , const vector<Base>& x ) { return false; } // deprecated versions template <class Base> bool atomic_base<Base>::for_sparse_jac( size_t q , const vector< std::set<size_t> >& r , vector< std::set<size_t> >& s ) { return false; } template <class Base> bool atomic_base<Base>::for_sparse_jac( size_t q , const vector<bool>& r , vector<bool>& s ) { return false; } template <class Base> bool atomic_base<Base>::for_sparse_jac( size_t q , const vectorBool& r , vectorBool& s ) { return false; } /*! Link, before case split, from for_jac_sweep to atomic_base. \tparam InternalSparsity Is the type used for internal sparsity calculations; i.e., sparse_pack or sparse_list. \param x is parameter arguments to the function, other components are nan. \param x_index is the variable index, on the tape, for the arguments to this function. This size of x_index is n, the number of arguments to this function. \param y_index is the variable index, on the tape, for the results for this function. This size of y_index is m, the number of results for this function. \param var_sparsity On input, for j = 0, ... , n-1, the sparsity pattern with index x_index[j], is the sparsity for the j-th argument to this atomic function. On output, for i = 0, ... , m-1, the sparsity pattern with index y_index[i], is the sparsity for the i-th result for this atomic function. */ template <class Base> template <class InternalSparsity> bool atomic_base<Base>::for_sparse_jac( const vector<Base>& x , const local::pod_vector<size_t>& x_index , const local::pod_vector<size_t>& y_index , InternalSparsity& var_sparsity ) { // intial results are empty during forward mode size_t q = var_sparsity.end(); bool input_empty = true; bool zero_empty = true; bool transpose = false; size_t m = y_index.size(); bool ok = false; size_t thread = thread_alloc::thread_num(); allocate_work(thread); // std::string msg = ": atomic_base.for_sparse_jac: returned false"; if( sparsity_ == pack_sparsity_enum ) { vectorBool& pack_r ( work_[thread]->pack_r ); vectorBool& pack_s ( work_[thread]->pack_s ); local::get_internal_sparsity( transpose, x_index, var_sparsity, pack_r ); // pack_s.resize(m * q ); ok = for_sparse_jac(q, pack_r, pack_s, x); if( ! ok ) ok = for_sparse_jac(q, pack_r, pack_s); if( ! ok ) { msg = afun_name() + msg + " sparsity = pack_sparsity_enum"; CPPAD_ASSERT_KNOWN(false, msg.c_str()); } local::set_internal_sparsity(zero_empty, input_empty, transpose, y_index, var_sparsity, pack_s ); } else if( sparsity_ == bool_sparsity_enum ) { vector<bool>& bool_r ( work_[thread]->bool_r ); vector<bool>& bool_s ( work_[thread]->bool_s ); local::get_internal_sparsity( transpose, x_index, var_sparsity, bool_r ); bool_s.resize(m * q ); ok = for_sparse_jac(q, bool_r, bool_s, x); if( ! ok ) ok = for_sparse_jac(q, bool_r, bool_s); if( ! ok ) { msg = afun_name() + msg + " sparsity = bool_sparsity_enum"; CPPAD_ASSERT_KNOWN(false, msg.c_str()); } local::set_internal_sparsity(zero_empty, input_empty, transpose, y_index, var_sparsity, bool_s ); } else { CPPAD_ASSERT_UNKNOWN( sparsity_ == set_sparsity_enum ); vector< std::set<size_t> >& set_r ( work_[thread]->set_r ); vector< std::set<size_t> >& set_s ( work_[thread]->set_s ); local::get_internal_sparsity( transpose, x_index, var_sparsity, set_r ); // set_s.resize(m); ok = for_sparse_jac(q, set_r, set_s, x); if( ! ok ) ok = for_sparse_jac(q, set_r, set_s); if( ! ok ) { msg = afun_name() + msg + " sparsity = set_sparsity_enum"; CPPAD_ASSERT_KNOWN(false, msg.c_str()); } local::set_internal_sparsity(zero_empty, input_empty, transpose, y_index, var_sparsity, set_s ); } return ok; } } // END_CPPAD_NAMESPACE # endif
/* * libjingle * Copyright 2004--2005, Google Inc. * * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * 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. */ #if defined(_MSC_VER) && _MSC_VER < 1300 #pragma warning(disable:4786) #endif #include "talk/base/asynctcpsocket.h" #include "talk/base/helpers.h" #include "talk/base/logging.h" #include "talk/p2p/base/relayport.h" namespace cricket { static const uint32 kMessageConnectTimeout = 1; static const int kKeepAliveDelay = 10 * 60 * 1000; static const int kRetryTimeout = 50 * 1000; // ICE says 50 secs // How long to wait for a socket to connect to remote host in milliseconds // before trying another connection. static const int kSoftConnectTimeoutMs = 3 * 1000; // Handles a connection to one address/port/protocol combination for a // particular RelayEntry. class RelayConnection : public sigslot::has_slots<> { public: RelayConnection(const ProtocolAddress* protocol_address, talk_base::AsyncPacketSocket* socket, talk_base::Thread* thread); ~RelayConnection(); talk_base::AsyncPacketSocket* socket() const { return socket_; } const ProtocolAddress* protocol_address() { return protocol_address_; } talk_base::SocketAddress GetAddress() const { return protocol_address_->address; } ProtocolType GetProtocol() const { return protocol_address_->proto; } int SetSocketOption(talk_base::Socket::Option opt, int value); // Validates a response to a STUN allocate request. bool CheckResponse(StunMessage* msg); // Sends data to the relay server. int Send(const void* pv, size_t cb); // Sends a STUN allocate request message to the relay server. void SendAllocateRequest(RelayEntry* entry, int delay); // Return the latest error generated by the socket. int GetError() { return socket_->GetError(); } // Called on behalf of a StunRequest to write data to the socket. This is // already STUN intended for the server, so no wrapping is necessary. void OnSendPacket(const void* data, size_t size, StunRequest* req); private: talk_base::AsyncPacketSocket* socket_; const ProtocolAddress* protocol_address_; StunRequestManager *request_manager_; }; // Manages a number of connections to the relayserver, one for each // available protocol. We aim to use each connection for only a // specific destination address so that we can avoid wrapping every // packet in a STUN send / data indication. class RelayEntry : public talk_base::MessageHandler, public sigslot::has_slots<> { public: RelayEntry(RelayPort* port, const talk_base::SocketAddress& ext_addr, const talk_base::SocketAddress& local_addr); ~RelayEntry(); RelayPort* port() { return port_; } const talk_base::SocketAddress& address() const { return ext_addr_; } void set_address(const talk_base::SocketAddress& addr) { ext_addr_ = addr; } bool connected() const { return connected_; } bool locked() const { return locked_; } // Returns the last error on the socket of this entry. int GetError(); // Returns the most preferred connection of the given // ones. Connections are rated based on protocol in the order of: // UDP, TCP and SSLTCP, where UDP is the most preferred protocol static RelayConnection* GetBestConnection(RelayConnection* conn1, RelayConnection* conn2); // Sends the STUN requests to the server to initiate this connection. void Connect(); // Called when this entry becomes connected. The address given is the one // exposed to the outside world on the relay server. void OnConnect(const talk_base::SocketAddress& mapped_addr, RelayConnection* socket); // Sends a packet to the given destination address using the socket of this // entry. This will wrap the packet in STUN if necessary. int SendTo(const void* data, size_t size, const talk_base::SocketAddress& addr); // Schedules a keep-alive allocate request. void ScheduleKeepAlive(); void SetServerIndex(size_t sindex) { server_index_ = sindex; } // Sets this option on the socket of each connection. int SetSocketOption(talk_base::Socket::Option opt, int value); size_t ServerIndex() const { return server_index_; } // Try a different server address void HandleConnectFailure(talk_base::AsyncPacketSocket* socket); // Implementation of the MessageHandler Interface. virtual void OnMessage(talk_base::Message *pmsg); private: RelayPort* port_; talk_base::SocketAddress ext_addr_, local_addr_; size_t server_index_; bool connected_; bool locked_; RelayConnection* current_connection_; // Called when a TCP connection is established or fails void OnSocketConnect(talk_base::AsyncTCPSocket* socket); void OnSocketClose(talk_base::AsyncTCPSocket* socket, int error); // Called when a packet is received on this socket. void OnReadPacket( const char* data, size_t size, const talk_base::SocketAddress& remote_addr, talk_base::AsyncPacketSocket* socket); // Sends the given data on the socket to the server with no wrapping. This // returns the number of bytes written or -1 if an error occurred. int SendPacket(const void* data, size_t size); }; // Handles an allocate request for a particular RelayEntry. class AllocateRequest : public StunRequest { public: AllocateRequest(RelayEntry* entry, RelayConnection* connection); virtual ~AllocateRequest() {} virtual void Prepare(StunMessage* request); virtual int GetNextDelay(); virtual void OnResponse(StunMessage* response); virtual void OnErrorResponse(StunMessage* response); virtual void OnTimeout(); private: RelayEntry* entry_; RelayConnection* connection_; uint32 start_time_; }; const std::string RELAY_PORT_TYPE("relay"); RelayPort::RelayPort( talk_base::Thread* thread, talk_base::SocketFactory* factory, talk_base::Network* network, const talk_base::SocketAddress& local_addr, const std::string& username, const std::string& password, const std::string& magic_cookie) : Port(thread, RELAY_PORT_TYPE, factory, network), local_addr_(local_addr), ready_(false), magic_cookie_(magic_cookie), error_(0) { entries_.push_back( new RelayEntry(this, talk_base::SocketAddress(), local_addr_)); set_username_fragment(username); set_password(password); if (magic_cookie_.size() == 0) magic_cookie_.append(STUN_MAGIC_COOKIE_VALUE, 4); } RelayPort::~RelayPort() { for (size_t i = 0; i < entries_.size(); ++i) delete entries_[i]; thread_->Clear(this); } void RelayPort::AddServerAddress(const ProtocolAddress& addr) { // Since HTTP proxies usually only allow 443, // let's up the priority on PROTO_SSLTCP if (addr.proto == PROTO_SSLTCP && (proxy().type == talk_base::PROXY_HTTPS || proxy().type == talk_base::PROXY_UNKNOWN)) { server_addr_.push_front(addr); } else { server_addr_.push_back(addr); } } void RelayPort::AddExternalAddress(const ProtocolAddress& addr) { std::string proto_name = ProtoToString(addr.proto); for (std::vector<Candidate>::const_iterator it = candidates().begin(); it != candidates().end(); ++it) { if ((it->address() == addr.address) && (it->protocol() == proto_name)) { LOG(INFO) << "Redundant relay address: " << proto_name << " @ " << addr.address.ToString(); return; } } AddAddress(addr.address, proto_name, false); } void RelayPort::SetReady() { if (!ready_) { ready_ = true; SignalAddressReady(this); } } const ProtocolAddress * RelayPort::ServerAddress(size_t index) const { if (index < server_addr_.size()) return &server_addr_[index]; return NULL; } bool RelayPort::HasMagicCookie(const char* data, size_t size) { if (size < 24 + magic_cookie_.size()) { return false; } else { return 0 == std::memcmp(data + 24, magic_cookie_.c_str(), magic_cookie_.size()); } } void RelayPort::PrepareAddress() { // We initiate a connect on the first entry. If this completes, it will fill // in the server address as the address of this port. ASSERT(entries_.size() == 1); entries_[0]->Connect(); ready_ = false; } Connection* RelayPort::CreateConnection(const Candidate& address, CandidateOrigin origin) { // We only create conns to non-udp sockets if they are incoming on this port if ((address.protocol() != "udp") && (origin != ORIGIN_THIS_PORT)) { return 0; } // We don't support loopback on relays if (address.type() == type()) { return 0; } size_t index = 0; for (size_t i = 0; i < candidates().size(); ++i) { const Candidate& local = candidates()[i]; if (local.protocol() == address.protocol()) { index = i; break; } } Connection * conn = new ProxyConnection(this, index, address); AddConnection(conn); return conn; } int RelayPort::SendTo(const void* data, size_t size, const talk_base::SocketAddress& addr, bool payload) { // Try to find an entry for this specific address. Note that the first entry // created was not given an address initially, so it can be set to the first // address that comes along. RelayEntry* entry = 0; for (size_t i = 0; i < entries_.size(); ++i) { if (entries_[i]->address().IsAny() && payload) { entry = entries_[i]; entry->set_address(addr); break; } else if (entries_[i]->address() == addr) { entry = entries_[i]; break; } } // If we did not find one, then we make a new one. This will not be useable // until it becomes connected, however. if (!entry && payload) { entry = new RelayEntry(this, addr, local_addr_); if (!entries_.empty()) { entry->SetServerIndex(entries_[0]->ServerIndex()); } entry->Connect(); entries_.push_back(entry); } // If the entry is connected, then we can send on it (though wrapping may // still be necessary). Otherwise, we can't yet use this connection, so we // default to the first one. if (!entry || !entry->connected()) { ASSERT(!entries_.empty()); entry = entries_[0]; if (!entry->connected()) { error_ = EWOULDBLOCK; return SOCKET_ERROR; } } // Send the actual contents to the server using the usual mechanism. int sent = entry->SendTo(data, size, addr); if (sent <= 0) { ASSERT(sent < 0); error_ = entry->GetError(); return SOCKET_ERROR; } // The caller of the function is expecting the number of user data bytes, // rather than the size of the packet. return (int)size; } int RelayPort::SetOption(talk_base::Socket::Option opt, int value) { int result = 0; for (size_t i = 0; i < entries_.size(); ++i) { if (entries_[i]->SetSocketOption(opt, value) < 0) { result = -1; error_ = entries_[i]->GetError(); } } options_.push_back(OptionValue(opt, value)); return result; } int RelayPort::GetError() { return error_; } void RelayPort::OnReadPacket( const char* data, size_t size, const talk_base::SocketAddress& remote_addr) { if (Connection* conn = GetConnection(remote_addr)) { conn->OnReadPacket(data, size); } else { Port::OnReadPacket(data, size, remote_addr); } } RelayConnection::RelayConnection(const ProtocolAddress* protocol_address, talk_base::AsyncPacketSocket* socket, talk_base::Thread* thread) : socket_(socket), protocol_address_(protocol_address) { request_manager_ = new StunRequestManager(thread); request_manager_->SignalSendPacket.connect(this, &RelayConnection::OnSendPacket); } RelayConnection::~RelayConnection() { delete request_manager_; delete socket_; } int RelayConnection::SetSocketOption(talk_base::Socket::Option opt, int value) { if (socket_) { return socket_->SetOption(opt, value); } return 0; } bool RelayConnection::CheckResponse(StunMessage* msg) { return request_manager_->CheckResponse(msg); } void RelayConnection::OnSendPacket(const void* data, size_t size, StunRequest* req) { int sent = socket_->SendTo(data, size, GetAddress()); if (sent <= 0) { LOG(LS_VERBOSE) << "OnSendPacket: failed sending to " << GetAddress() << std::strerror(socket_->GetError()); ASSERT(sent < 0); } } int RelayConnection::Send(const void* pv, size_t cb) { return socket_->SendTo(pv, cb, GetAddress()); } void RelayConnection::SendAllocateRequest(RelayEntry* entry, int delay) { request_manager_->SendDelayed(new AllocateRequest(entry, this), delay); } RelayEntry::RelayEntry(RelayPort* port, const talk_base::SocketAddress& ext_addr, const talk_base::SocketAddress& local_addr) : port_(port), ext_addr_(ext_addr), local_addr_(local_addr), server_index_(0), connected_(false), locked_(false), current_connection_(NULL) { } RelayEntry::~RelayEntry() { // Remove all RelayConnections and dispose sockets. delete current_connection_; current_connection_ = NULL; } void RelayEntry::Connect() { // If we're already connected, return. if (connected_) return; // If we've exhausted all options, bail out. const ProtocolAddress* ra = port()->ServerAddress(server_index_); if (!ra) { LOG(LS_WARNING) << "No more relay addresses left to try"; return; } // Remove any previous connection. if (current_connection_) { port()->thread()->Dispose(current_connection_); current_connection_ = NULL; } // Try to set up our new socket. LOG(LS_INFO) << "Connecting to relay via " << ProtoToString(ra->proto) << " @ " << ra->address.ToString(); talk_base::AsyncPacketSocket* socket = port_->CreatePacketSocket(ra->proto); if (!socket) { LOG(LS_WARNING) << "Socket creation failed"; } else if (socket->Bind(local_addr_) < 0) { LOG(LS_WARNING) << "Socket bind failed with error " << socket->GetError(); delete socket; socket = NULL; } // If we failed to get a socket, move on to the next protocol. if (!socket) { port()->thread()->Post(this, kMessageConnectTimeout); return; } // Otherwise, create the new connection and configure any socket options. socket->SignalReadPacket.connect(this, &RelayEntry::OnReadPacket); current_connection_ = new RelayConnection(ra, socket, port()->thread()); for (size_t i = 0; i < port_->options().size(); ++i) { current_connection_->SetSocketOption(port_->options()[i].first, port_->options()[i].second); } // If we're trying UDP, start binding requests. // If we're trying TCP, initiate a connection with a fixed timeout. if ((ra->proto == PROTO_TCP) || (ra->proto == PROTO_SSLTCP)) { talk_base::AsyncTCPSocket* tcp = static_cast<talk_base::AsyncTCPSocket*>(socket); tcp->SignalClose.connect(this, &RelayEntry::OnSocketClose); tcp->SignalConnect.connect(this, &RelayEntry::OnSocketConnect); tcp->Connect(ra->address); port()->thread()->PostDelayed(kSoftConnectTimeoutMs, this, kMessageConnectTimeout); } else { current_connection_->SendAllocateRequest(this, 0); } } int RelayEntry::GetError() { if (current_connection_ != NULL) { return current_connection_->GetError(); } return 0; } RelayConnection* RelayEntry::GetBestConnection(RelayConnection* conn1, RelayConnection* conn2) { return conn1->GetProtocol() <= conn2->GetProtocol() ? conn1 : conn2; } void RelayEntry::OnConnect(const talk_base::SocketAddress& mapped_addr, RelayConnection* connection) { // We are connected, notify our parent. ProtocolType proto = PROTO_UDP; LOG(INFO) << "Relay allocate succeeded: " << ProtoToString(proto) << " @ " << mapped_addr.ToString(); connected_ = true; port_->AddExternalAddress(ProtocolAddress(mapped_addr, proto)); port_->SetReady(); } int RelayEntry::SendTo(const void* data, size_t size, const talk_base::SocketAddress& addr) { // If this connection is locked to the address given, then we can send the // packet with no wrapper. if (locked_ && (ext_addr_ == addr)) return SendPacket(data, size); // Otherwise, we must wrap the given data in a STUN SEND request so that we // can communicate the destination address to the server. // // Note that we do not use a StunRequest here. This is because there is // likely no reason to resend this packet. If it is late, we just drop it. // The next send to this address will try again. StunMessage request; request.SetType(STUN_SEND_REQUEST); request.SetTransactionID(talk_base::CreateRandomString(16)); StunByteStringAttribute* magic_cookie_attr = StunAttribute::CreateByteString(STUN_ATTR_MAGIC_COOKIE); magic_cookie_attr->CopyBytes(port_->magic_cookie().c_str(), (uint16)port_->magic_cookie().size()); request.AddAttribute(magic_cookie_attr); StunByteStringAttribute* username_attr = StunAttribute::CreateByteString(STUN_ATTR_USERNAME); username_attr->CopyBytes(port_->username_fragment().c_str(), (uint16)port_->username_fragment().size()); request.AddAttribute(username_attr); StunAddressAttribute* addr_attr = StunAttribute::CreateAddress(STUN_ATTR_DESTINATION_ADDRESS); addr_attr->SetFamily(1); addr_attr->SetIP(addr.ip()); addr_attr->SetPort(addr.port()); request.AddAttribute(addr_attr); // Attempt to lock if (ext_addr_ == addr) { StunUInt32Attribute* options_attr = StunAttribute::CreateUInt32(STUN_ATTR_OPTIONS); options_attr->SetValue(0x1); request.AddAttribute(options_attr); } StunByteStringAttribute* data_attr = StunAttribute::CreateByteString(STUN_ATTR_DATA); data_attr->CopyBytes(data, (uint16)size); request.AddAttribute(data_attr); // TODO: compute the HMAC. talk_base::ByteBuffer buf; request.Write(&buf); return SendPacket(buf.Data(), buf.Length()); } void RelayEntry::ScheduleKeepAlive() { if (current_connection_) { current_connection_->SendAllocateRequest(this, kKeepAliveDelay); } } int RelayEntry::SetSocketOption(talk_base::Socket::Option opt, int value) { // Set the option on all available sockets. int socket_error = 0; if (current_connection_) { socket_error = current_connection_->SetSocketOption(opt, value); } return socket_error; } void RelayEntry::HandleConnectFailure( talk_base::AsyncPacketSocket* socket) { // Make sure it's the current connection that has failed, it might // be an old socked that has not yet been disposed. if (!socket || socket == current_connection_->socket()) { if (current_connection_) port()->SignalConnectFailure(current_connection_->protocol_address()); // Try to connect to the next server address. server_index_ += 1; Connect(); } } void RelayEntry::OnMessage(talk_base::Message *pmsg) { ASSERT(pmsg->message_id == kMessageConnectTimeout); if (current_connection_) { const ProtocolAddress* ra = current_connection_->protocol_address(); LOG(LS_WARNING) << "Relay " << ra->proto << " connection to " << ra->address << " timed out"; // Currently we connect to each server address in sequence. If we // have more addresses to try, treat this is an error and move on to // the next address, otherwise give this connection more time and // await the real timeout. // // TODO: Connect to servers in pararel to speed up connect time // and to avoid giving up to early. port_->SignalSoftTimeout(ra); HandleConnectFailure(current_connection_->socket()); } else { HandleConnectFailure(NULL); } } void RelayEntry::OnSocketConnect(talk_base::AsyncTCPSocket* socket) { LOG(INFO) << "relay tcp connected to " << socket->GetRemoteAddress().ToString(); if (current_connection_ != NULL) { current_connection_->SendAllocateRequest(this, 0); } } void RelayEntry::OnSocketClose(talk_base::AsyncTCPSocket* socket, int error) { PLOG(LERROR, error) << "Relay connection failed: socket closed"; HandleConnectFailure(socket); } void RelayEntry::OnReadPacket(const char* data, size_t size, const talk_base::SocketAddress& remote_addr, talk_base::AsyncPacketSocket* socket) { // ASSERT(remote_addr == port_->server_addr()); // TODO: are we worried about this? if (current_connection_ == NULL || socket != current_connection_->socket()) { // This packet comes from an unknown address. LOG(WARNING) << "Dropping packet: unknown address"; return; } // If the magic cookie is not present, then this is an unwrapped packet sent // by the server, The actual remote address is the one we recorded. if (!port_->HasMagicCookie(data, size)) { if (locked_) { port_->OnReadPacket(data, size, ext_addr_); } else { LOG(WARNING) << "Dropping packet: entry not locked"; } return; } talk_base::ByteBuffer buf(data, size); StunMessage msg; if (!msg.Read(&buf)) { LOG(INFO) << "Incoming packet was not STUN"; return; } // The incoming packet should be a STUN ALLOCATE response, SEND response, or // DATA indication. if (current_connection_->CheckResponse(&msg)) { return; } else if (msg.type() == STUN_SEND_RESPONSE) { if (const StunUInt32Attribute* options_attr = msg.GetUInt32(STUN_ATTR_OPTIONS)) { if (options_attr->value() & 0x1) { locked_ = true; } } return; } else if (msg.type() != STUN_DATA_INDICATION) { LOG(INFO) << "Received BAD stun type from server: " << msg.type(); return; } // This must be a data indication. const StunAddressAttribute* addr_attr = msg.GetAddress(STUN_ATTR_SOURCE_ADDRESS2); if (!addr_attr) { LOG(INFO) << "Data indication has no source address"; return; } else if (addr_attr->family() != 1) { LOG(INFO) << "Source address has bad family"; return; } talk_base::SocketAddress remote_addr2(addr_attr->ip(), addr_attr->port()); const StunByteStringAttribute* data_attr = msg.GetByteString(STUN_ATTR_DATA); if (!data_attr) { LOG(INFO) << "Data indication has no data"; return; } // Process the actual data and remote address in the normal manner. port_->OnReadPacket(data_attr->bytes(), data_attr->length(), remote_addr2); } int RelayEntry::SendPacket(const void* data, size_t size) { int sent = 0; if (current_connection_) { // We are connected, no need to send packets anywere else than to // the current connection. sent = current_connection_->Send(data, size); } return sent; } AllocateRequest::AllocateRequest(RelayEntry* entry, RelayConnection* connection) : entry_(entry), connection_(connection) { start_time_ = talk_base::Time(); } void AllocateRequest::Prepare(StunMessage* request) { request->SetType(STUN_ALLOCATE_REQUEST); StunByteStringAttribute* magic_cookie_attr = StunAttribute::CreateByteString(STUN_ATTR_MAGIC_COOKIE); magic_cookie_attr->CopyBytes( entry_->port()->magic_cookie().c_str(), (uint16)entry_->port()->magic_cookie().size()); request->AddAttribute(magic_cookie_attr); StunByteStringAttribute* username_attr = StunAttribute::CreateByteString(STUN_ATTR_USERNAME); username_attr->CopyBytes( entry_->port()->username_fragment().c_str(), (uint16)entry_->port()->username_fragment().size()); request->AddAttribute(username_attr); } int AllocateRequest::GetNextDelay() { int delay = 100 * talk_base::_max(1 << count_, 2); count_ += 1; if (count_ == 5) timeout_ = true; return delay; } void AllocateRequest::OnResponse(StunMessage* response) { const StunAddressAttribute* addr_attr = response->GetAddress(STUN_ATTR_MAPPED_ADDRESS); if (!addr_attr) { LOG(INFO) << "Allocate response missing mapped address."; } else if (addr_attr->family() != 1) { LOG(INFO) << "Mapped address has bad family"; } else { talk_base::SocketAddress addr(addr_attr->ip(), addr_attr->port()); entry_->OnConnect(addr, connection_); } // We will do a keep-alive regardless of whether this request suceeds. // This should have almost no impact on network usage. entry_->ScheduleKeepAlive(); } void AllocateRequest::OnErrorResponse(StunMessage* response) { const StunErrorCodeAttribute* attr = response->GetErrorCode(); if (!attr) { LOG(INFO) << "Bad allocate response error code"; } else { LOG(INFO) << "Allocate error response:" << " code=" << static_cast<int>(attr->error_code()) << " reason='" << attr->reason() << "'"; } if (talk_base::TimeSince(start_time_) <= kRetryTimeout) entry_->ScheduleKeepAlive(); } void AllocateRequest::OnTimeout() { LOG(INFO) << "Allocate request timed out"; entry_->HandleConnectFailure(connection_->socket()); } } // namespace cricket
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2016 HPCC Systems®. 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 "couchbaseembed.hpp" #include "platform.h" #include "jexcept.hpp" #include "jlog.hpp" #include "hqlplugins.hpp" #include "deftype.hpp" #include "eclhelper.hpp" #include "eclrtl.hpp" #include "eclrtl_imp.hpp" #include <map> #include <mutex> #include <thread> static const char *g_moduleName = "couchbase"; static const char *g_moduleDescription = "Couchbase Embed Helper"; static const char *g_version = "Couchbase Embed Helper 1.0.0"; static const char *g_compatibleVersions[] = { g_version, nullptr }; static const NullFieldProcessor NULLFIELD(NULL); extern "C" COUCHBASEEMBED_PLUGIN_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb) { if (pb->size == sizeof(ECLPluginDefinitionBlockEx)) { ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb; pbx->compatibleVersions = g_compatibleVersions; } else if (pb->size != sizeof(ECLPluginDefinitionBlock)) return false; pb->magicVersion = PLUGIN_VERSION; pb->version = g_version; pb->moduleName = g_moduleName; pb->ECL = nullptr; pb->flags = PLUGIN_IMPLICIT_MODULE; pb->description = g_moduleDescription; return true; } namespace couchbaseembed { const time_t OBJECT_EXPIRE_TIMEOUT_SECONDS = 60 * 2; // Two minutes static std::once_flag connectionCacheInitFlag; //-------------------------------------------------------------------------- // Plugin Classes //-------------------------------------------------------------------------- void reportIfQueryFailure(Couchbase::Query * query) { auto status = query->meta().status(); if (status.errcode()) { if (status.isNetworkError()) failx("NetworkErr: %s", status.description()); else if (status.isDataError()) failx("DataErr: %s", status.description()); else if (status.isInputError()) failx("InputErr: %s", status.description()); else if (status.isTemporary()) failx("TempErr: %s", status.description()); else failx("Couchbase err: %s (%d)", status.description(), status.errcode()); } //consider parsing json result if (strstr(query->meta().body().to_string().c_str(), "\"status\": \"errors\"")) failx("Err: %s", query->meta().body().to_string().c_str()); } CouchbaseRowStream::CouchbaseRowStream(IEngineRowAllocator* resultAllocator, Couchbase::Query * cbaseQuery) : m_resultAllocator(resultAllocator) { m_currentRow = 0; m_shouldRead = true; //iterating over result rows and copying them to stringarray //is there a way to independently step through original result rows? for (auto cbrow : *cbaseQuery) m_Rows.append(cbrow.json().to_string().c_str()); reportIfQueryFailure(cbaseQuery); } CouchbaseRowStream::~CouchbaseRowStream() {} const void * CouchbaseRowStream::nextRow() { const void * result = nullptr; if (m_shouldRead && m_currentRow < m_Rows.length()) { auto json = m_Rows.item(m_currentRow++); Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json,ipt_caseInsensitive); if (contentTree) { CouchbaseRowBuilder cbRowBuilder(contentTree); RtlDynamicRowBuilder rowBuilder(m_resultAllocator); const RtlTypeInfo *typeInfo = m_resultAllocator->queryOutputMeta()->queryTypeInfo(); assertex(typeInfo); RtlFieldStrInfo dummyField("<row>", NULL, typeInfo); size32_t len = typeInfo->build(rowBuilder, 0, &dummyField, cbRowBuilder); return rowBuilder.finalizeRowClear(len); } else failx("Error processing result row"); } return result; } void CouchbaseRowStream::stop() { m_resultAllocator.clear(); m_shouldRead = false; } Couchbase::Query * CouchbaseConnection::query(Couchbase::QueryCommand * qcommand) { Couchbase::Status queryStatus; Couchbase::Query * pQuery = new Couchbase::Query(*m_pCouchbaseClient, *qcommand, queryStatus); // will be owned by method caller if (!queryStatus) failx("Couldn't issue query: %s", queryStatus.description()); if (!pQuery->status()) failx("Couldn't execute query, reason: %s\nBody is: ", pQuery->meta().body().data()); if (pQuery->meta().status().errcode() != LCB_SUCCESS )//rows.length() == 0) failx("Query execution error: %s", pQuery->meta().body().data()); return pQuery; } extern void UNSUPPORTED(const char *feature) { throw MakeStringException(-1, "UNSUPPORTED feature: %s not supported in %s", feature, g_version); } extern void failx(const char *message, ...) { va_list args; va_start(args,message); StringBuffer msg; msg.appendf("%s: ", g_moduleName).valist_appendf(message,args); va_end(args); rtlFail(0, msg.str()); } extern void fail(const char *message) { StringBuffer msg; msg.appendf("%s: ", g_moduleName).append(message); rtlFail(0, msg.str()); } void bindStringParam(unsigned len, const char *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd) { VStringBuffer cbPlaceholder("$%s", field->name); if (pQcmd) { size32_t utf8chars; char *utf8; rtlStrToUtf8X(utf8chars, utf8, len, value); auto status = pQcmd->named_param(cbPlaceholder.str(), utf8); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8); if (utf8) rtlFree(utf8); } else failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str()); } void bindBoolParam(bool value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd) { VStringBuffer cbPlaceholder("$%s", field->name); if (pQcmd) { StringBuffer serialized; TokenSerializer tokenSerializer; tokenSerializer.serialize(value, serialized); auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } else failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str()); } void bindDataParam(unsigned len, const void *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd) { VStringBuffer cbPlaceholder("$%s", field->name); if (pQcmd) { size32_t bytes; void *data; rtlStrToDataX(bytes, data, len, value); auto status = pQcmd->named_param(cbPlaceholder.str(), (char *)data); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), (char *)data); if (data) rtlFree(data); } else failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str()); } void bindIntParam(__int64 value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd) { VStringBuffer cbPlaceholder("$%s", field->name); if (pQcmd) { StringBuffer serialized; TokenSerializer tokenSerializer; tokenSerializer.serialize(value, serialized); auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } else failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str()); } void bindUIntParam(unsigned __int64 value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd) { VStringBuffer cbPlaceholder("$%s", field->name); if (pQcmd) { StringBuffer serialized; TokenSerializer tokenSerializer; tokenSerializer.serialize(value, serialized); auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } else failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str()); } void bindRealParam(double value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd) { VStringBuffer cbPlaceholder("$%s", field->name); if (pQcmd) { StringBuffer serialized; TokenSerializer tokenSerializer; tokenSerializer.serialize(value, serialized); auto status = pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } else failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str()); } void bindUnicodeParam(unsigned chars, const UChar *value, const RtlFieldInfo * field, Couchbase::QueryCommand * pQcmd) { VStringBuffer cbPlaceholder("$%s", field->name); if (pQcmd) { size32_t utf8chars; char *utf8; rtlUnicodeToUtf8X(utf8chars, utf8, chars, value); auto status = pQcmd->named_param(cbPlaceholder.str(), utf8); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8); } else failx("Internal error: detected invalid CouchbaseQueryCommand while attempting to bind to field: %s", cbPlaceholder.str()); } int CouchbaseRecordBinder::numFields() { int count = 0; const RtlFieldInfo * const *fields = typeInfo->queryFields(); assertex(fields); while (*fields++) count++; return count; } void CouchbaseRecordBinder::processRow(const byte *row) { thisParam = firstParam; typeInfo->process(row, row, &dummyField, *this); // Bind the variables for the current row } void CouchbaseRecordBinder::processString(unsigned len, const char *value, const RtlFieldInfo * field) { checkNextParam(field); bindStringParam(len, value, field, m_pQcmd); } void CouchbaseRecordBinder::processBool(bool value, const RtlFieldInfo * field) { bindBoolParam(value, field, m_pQcmd); } void CouchbaseRecordBinder::processData(unsigned len, const void *value, const RtlFieldInfo * field) { bindDataParam(len, value, field, m_pQcmd); } void CouchbaseRecordBinder::processInt(__int64 value, const RtlFieldInfo * field) { bindIntParam(value, field, m_pQcmd); } void CouchbaseRecordBinder::processUInt(unsigned __int64 value, const RtlFieldInfo * field) { bindUIntParam(value, field,m_pQcmd); } void CouchbaseRecordBinder::processReal(double value, const RtlFieldInfo * field) { bindRealParam(value, field, m_pQcmd); } void CouchbaseRecordBinder::processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field) { Decimal val; size32_t bytes; rtlDataAttr decText; val.setDecimal(digits, precision, value); val.getStringX(bytes, decText.refstr()); processUtf8(bytes, decText.getstr(), field); } void CouchbaseRecordBinder::processUnicode(unsigned chars, const UChar *value, const RtlFieldInfo * field) { bindUnicodeParam(chars, value, field, m_pQcmd); } void CouchbaseRecordBinder::processQString(unsigned len, const char *value, const RtlFieldInfo * field) { size32_t charCount; rtlDataAttr text; rtlQStrToStrX(charCount, text.refstr(), len, value); processUtf8(charCount, text.getstr(), field); } void CouchbaseRecordBinder::processUtf8(unsigned chars, const char *value, const RtlFieldInfo * field) { bindStringParam(strlen(value), value, field, m_pQcmd); } unsigned CouchbaseRecordBinder::checkNextParam(const RtlFieldInfo * field) { if (logctx.queryTraceLevel() > 4) logctx.CTXLOG("Binding %s to %d", field->name, thisParam); return thisParam++; } static class ConnectionCacheObj { private: typedef std::vector<CouchbaseConnection*> ConnectionList; typedef std::map<hash64_t, ConnectionList> ObjMap; public: ConnectionCacheObj(int _traceLevel) : traceLevel(_traceLevel) { } ~ConnectionCacheObj() { deleteAll(); } void deleteAll() { CriticalBlock block(cacheLock); // Delete all idle connection objects for (ObjMap::iterator keyIter = idleConnections.begin(); keyIter != idleConnections.end(); keyIter++) { for (ConnectionList::iterator connectionIter = keyIter->second.begin(); connectionIter != keyIter->second.end(); connectionIter++) { if (*connectionIter) { delete(*connectionIter); } } } idleConnections.clear(); // Delete all active connection objects for (ObjMap::iterator keyIter = activeConnections.begin(); keyIter != activeConnections.end(); keyIter++) { for (ConnectionList::iterator connectionIter = keyIter->second.begin(); connectionIter != keyIter->second.end(); connectionIter++) { if (*connectionIter) { delete(*connectionIter); } } } activeConnections.clear(); } void releaseActive(CouchbaseConnection* connectionPtr) { CriticalBlock block(cacheLock); // Find given connection in our active list and move it to our // idle list for (ObjMap::iterator keyIter = activeConnections.begin(); keyIter != activeConnections.end(); keyIter++) { for (ConnectionList::iterator connectionIter = keyIter->second.begin(); connectionIter != keyIter->second.end(); connectionIter++) { if (*connectionIter == connectionPtr) { connectionPtr->updateTimeTouched(); keyIter->second.erase(connectionIter); idleConnections[keyIter->first].push_back(connectionPtr); if (traceLevel > 4) { DBGLOG("Couchbase: Released connection object %p", connectionPtr); } return; } } } } void expire() { if (!idleConnections.empty()) { CriticalBlock block(cacheLock); time_t oldestAllowedTime = time(NULL) - OBJECT_EXPIRE_TIMEOUT_SECONDS; __int32 expireCount = 0; for (ObjMap::iterator keyIter = idleConnections.begin(); keyIter != idleConnections.end(); keyIter++) { ConnectionList::iterator connectionIter = keyIter->second.begin(); while (connectionIter != keyIter->second.end()) { if (*connectionIter) { if ((*connectionIter)->getTimeTouched() < oldestAllowedTime) { delete(*connectionIter); connectionIter = keyIter->second.erase(connectionIter); ++expireCount; } else { ++connectionIter; } } else { connectionIter = keyIter->second.erase(connectionIter); } } } if (traceLevel > 4 && expireCount > 0) { DBGLOG("Couchbase: Expired %d cached connection%s", expireCount, (expireCount == 1 ? "" : "s")); } } } CouchbaseConnection* getConnection(bool useSSL, const char * host, unsigned port, const char * bucketname, const char * password, const char * connOptions, unsigned int maxConnections, const char * user) { CouchbaseConnection* connectionObjPtr = nullptr; StringBuffer connectionString; CouchbaseConnection::makeConnectionString(useSSL, host, port, bucketname, connOptions, connectionString); // Use a hash of the connection string as the key to finding // any idle connection objects hash64_t key = rtlHash64VStr(connectionString.str(), 0); while (true) { { CriticalBlock block(cacheLock); ConnectionList& idleConnectionList = idleConnections[key]; if (!idleConnectionList.empty()) { // We have at least one idle connection; use that connectionObjPtr = idleConnectionList.back(); idleConnectionList.pop_back(); connectionObjPtr->updateTimeTouched(); // Push the connection object onto our active list activeConnections[key].push_back(connectionObjPtr); if (traceLevel > 4) { DBGLOG("Couchbase: Using cached connection object %p: %s", connectionObjPtr, connectionString.str()); } break; } else if (maxConnections == 0 || activeConnections[key].size() < maxConnections) { // No idle connections but we don't have to wait for // one; exit the loop and create a new connection break; } } // We can't exit the loop and allow a new connection to // be created because there are too many active // connections already; wait for a short while // and try again std::this_thread::sleep_for(std::chrono::microseconds(10)); } if (!connectionObjPtr) { // An idle connection for that particular combination of // options does not exist so we need to create one; // use a small loop to retry connections if necessary unsigned int connectAttempt = 0; unsigned int MAX_ATTEMPTS = 10; useconds_t SLEEP_TIME = 100 + (fastRand() % 200); // Add jitter to sleep time while (true) { connectionObjPtr = new CouchbaseConnection(connectionString, password, user); connectionObjPtr->connect(); if (connectionObjPtr->getConnectionStatus().success()) { { // Push new connection object onto our active list CriticalBlock block(cacheLock); connectionObjPtr->updateTimeTouched(); ConnectionList& activeConnectionList = activeConnections[key]; activeConnectionList.push_back(connectionObjPtr); } if (traceLevel > 4) { DBGLOG("Couchbase: Created and cached new connection object %p: %s", connectionObjPtr, connectionString.str()); } break; } else if (connectionObjPtr->getConnectionStatus().isTemporary()) { ++connectAttempt; if (connectAttempt < MAX_ATTEMPTS) { // According to libcouchbase-cxx, we need // to destroy the connection object if // there has been a failure of any kind delete(connectionObjPtr); connectionObjPtr = nullptr; std::this_thread::sleep_for(std::chrono::microseconds(SLEEP_TIME)); } else { // Capture the final failure reason and // destroy the connection object before // throwing an error std::string reason = connectionObjPtr->getConnectionStatus().description(); delete(connectionObjPtr); connectionObjPtr = nullptr; failx("Failed to connect to couchbase instance: %s Reason: '%s'", connectionString.str(), reason.c_str()); } } else { // Capture the final failure reason and // destroy the connection object before // throwing an error std::string reason = connectionObjPtr->getConnectionStatus().description(); delete(connectionObjPtr); connectionObjPtr = nullptr; failx("Failed to connect to couchbase instance: %s Reason: '%s'", connectionString.str(), reason.c_str()); } } } return connectionObjPtr; } private: ObjMap idleConnections; //!< std::map of created CouchbaseConnection object pointers ObjMap activeConnections; //!< std::map of created CouchbaseConnection object pointers CriticalSection cacheLock; //!< Mutex guarding modifications to connection pools int traceLevel; //!< The current logging level } *connectionCache; static class ConnectionCacheExpirerObj : public Thread { public: ConnectionCacheExpirerObj() : Thread("Couchbase::ConnectionCacheExpirer"), shouldRun(false) { } virtual void start() { if (!isAlive()) { shouldRun = true; Thread::start(); } } virtual void stop() { if (isAlive()) { shouldRun = false; join(); } } virtual int run() { // Periodically delete connections that have been idle too long while (shouldRun) { if (connectionCache) { connectionCache->expire(); } std::this_thread::sleep_for(std::chrono::microseconds(1000)); } return 0; } private: std::atomic_bool shouldRun; //!< If true, we should execute our thread's main event loop } *connectionCacheExpirer; static void setupConnectionCache(int traceLevel) { couchbaseembed::connectionCache = new couchbaseembed::ConnectionCacheObj(traceLevel); couchbaseembed::connectionCacheExpirer = new couchbaseembed::ConnectionCacheExpirerObj; couchbaseembed::connectionCacheExpirer->start(); } CouchbaseEmbedFunctionContext::CouchbaseEmbedFunctionContext(const IContextLogger &_logctx, const char *options, unsigned _flags) : logctx(_logctx), m_NextRow(), m_nextParam(0), m_numParams(0), m_scriptFlags(_flags) { m_pQuery = nullptr; m_pQcmd = nullptr; const char *server = "localhost"; const char *user = ""; const char *password = ""; const char *bucketname = "default"; unsigned port = 8091; bool useSSL = false; StringBuffer connectionOptions; unsigned int maxConnections = 0; StringArray inputOptions; inputOptions.appendList(options, ","); ForEachItemIn(idx, inputOptions) { const char *opt = inputOptions.item(idx); const char *val = strchr(opt, '='); if (val) { StringBuffer optName(val-opt, opt); val++; if (stricmp(optName, "server")==0) server = val; // Note that lifetime of val is adequate for this to be safe else if (stricmp(optName, "port")==0) port = atoi(val); else if (stricmp(optName, "user")==0) user = val; // This is not used but retained for backwards-compatibility else if (stricmp(optName, "password")==0) password = val; else if (stricmp(optName, "bucket")==0) bucketname = val; else if (stricmp(optName, "useSSL")==0) useSSL = clipStrToBool(val); else if (stricmp(optName, "max_connections")==0) maxConnections = atoi(val); //Connection String options /* operation_timeout=SECONDS: Specify the operation timeout in seconds. This is the time the client will wait for an operation to complete before timing it out. The default is 2.5 config_cache=PATH: Enables the client to make use of a file based configuration cache rather than connecting for the bootstrap operation. If the file does not exist, the client will first connect to the cluster and then cache the bootstrap information in the file. example "couchbases://127.0.0.1/default?certpath=../etc/x509-cert/SSLCA/clientdir/trust.pem" certpath=PATH: The path to the server's SSL certificate. This is typically required for SSL connectivity unless the certificate has already been added to the openssl installation on the system (only applicable with couchbases:// scheme) ssl=no_verify: Temporarily disable certificate verification for SSL (only applicable with couchbases:// scheme). This should only be used for quickly debugging SSL functionality. sasl_mech_force=MECHANISM: Force a specific SASL mechanism to be used when performing the initial connection. This should only need to be modified for debugging purposes. The currently supported mechanisms are PLAIN and CRAM-MD5 bootstrap_on=<both,http,cccp>: Specify the bootstrap protocol the client should use when attempting to connect to the cluster. Options are: cccp: Bootstrap using the Memcached protocol (supported on clusters 2.5 and greater); http: Bootstrap using the HTTP REST protocol (supported on any cluster version); and both: First attempt bootstrap over the Memcached protocol, and use the HTTP protocol if Memcached bootstrap fails. The default is both operation_timeout (Timeout) The operation timeout is the maximum amount of time the library will wait for an operation to receive a response before invoking its callback with a failure status. An operation might time-out if: - A server is taking too long to respond - An updated cluster configuration has not been promptly received When an operation times out, it will fail with the LCB_ETIMEDOUT error code. Connection String Example operation_timeout=2.5 config_total_timeout (Timeout) This is how long the client will wait to obtain the initial configuration. This affects the maximum amount of time that the call to lcb_wait() will take after having called lcb_connect(). If lcb_get_bootstrap_status is returning with LCB_ETIMEDOUT and you are running on a slow network, modifying this setting may increase the chances of success. See also config_node_timeout. Connection String Example config_total_timeout=5 config_node_timeout (Timeout) The per-node configuration timeout sets the amount of time to wait for each node within the bootstrap/configuration process. This interval is a subset of the config_total_timeout option mentioned above and is intended to ensure that the bootstrap process does not wait too long for a given node. Nodes that are physically offline may never respond, and it may take a long time until they are detected as being offline. See CCBC-261 and CCBC-313 for more reasons. Connection String Example config_node_timeout=2 views_timeout (Timeout) The I/O timeout for view operations. Connection String Example views_timeout=75 n1ql_timeout (Timeout). Since 2.5.3 The I/O timeout for N1QL queries. Connection String Example n1ql_timeout=75 durabilty_timeout (Timeout) The default timeout for lcb_durability_poll() This is the time the client will spend sending repeated probes to a given key’s vBucket masters and replicas before they are deemed not to have satisfied the durability requirements. Connection String Example durability_timeout=5 durabilty_interval (Timeout) This is the time the client will wait between repeated probes to a given server. Connection String Example durability_interval=0.0001 ipv6= (enum) Controls whether hostname lookups should prefer IPv4 or IPv6. Can be set to allow, disable (the default), or only. See Enumeration Type Documentation for more info. randomize_nodes (Boolean) This option controls whether the connection attempts for configuration retrievals should be done in the supplied order or whether they should be randomized. This setting is off by default. To affect the order of the initial connection, this option must be supplied in the connection string. For the initial connection, the default order is the list of hosts provided in the structure. For subsequent connections, this is the order of nodes as received by the server. Connection String Example randomize_nodes=1 config_cache (Path) The configuration cache allows bootstrapping from a cluster without using the initial bootstrap connection, considerably reducing latency. If the file passed does not exist, the normal bootstrap process is performed, and the file is written to with the current information. The leading directories for the file must exist. Otherwise, the file will never be created. Configuration cache is not supported for memcached buckets Connection String Example config_cache=/tmp/cb_config_cache config_cache_ro (Path). Since 2.4.8 This is identical to the config_cache option, except that it guarantees that the library will never overwrite or otherwise modify the path specified. Connection String Example config_cache_ro=1 detailed_errcodes (Boolean) Sets the behavior for reporting network errors. By default network errors are returned as LCB_NETWORK_ERROR. Return codes for compatibility reasons. More detailed error codes may be available by enabling this option that will return appropriate error codes with a category LCB_ERRTYPE_NETWORK. Using this option means your programming model is centered around the various LCB_EIF* macros (see <libcouchbase/error.h>) rather than individual codes. For users of higher level languages (wrapping the library), this may result in different exceptions being thrown, but may also help debug network issues. Connection String Example detailed_errcodes=1 http_poolsize (Integer) Set the maximum pool size for pooled HTTP (view or N1QL request) sockets. A setting of 0 disables pooling. Connection String Example http_poolsize=0 error_thresh_delay (Timeout) This option controls refreshing the configuration upon the receipt of errors. The client throttles how many requests for a new configuration it will send in a given interval—this is to avoid sending many successive requests in the event of a non-transient error condition. This setting controls the duration of this interval. The value can be adjusted upwards if operating in an environment where it is normal to receive many timeouts, such as in a resource-contented server or network. It can be adjusted downwards if timeouts are expected only in situations where the cluster has changed state. Connection String Example error_thresh_delay=7.5 bootstrap_on (String; see description) Controls how the client attempts to retrieve the configuration from the cluster. By default, the client attempts to connect to the data (memcached) port of each node listed and attempts to retrieve the configuration from there. If the retrieval fails, the client attempts the same process using the HTTP REST API port (8091) of each node. This setting can be used to have the client forcefully use a single mode. This might be helpful for quick initialization of memcached buckets, which can only send configurations over HTTP. It can also be used in the case of potential issues encountered with either mode. Possible values for this setting are: http, to force bootstrap over HTTP only cccp, to force bootstrap over memcached only both, which attempts both (as above). This option can only be set from within the connection string. bootstrap_on=http fetch_mutation_tokens (Boolean). Since 2.5.2 Whether the server should send an additional 16 bytes of metadata for each mutation response. This option is off by default but is required for Enhanced Durability. This option should be set either in the connection string, or immediately calling lcb_create(). For non-C applications, this must always be in the connection string. Connection String Example fetch_mutation_tokens=1 dur_mutation_tokens (Boolean). Since 2.5.2 Determines if Enhanced Durability is used automatically. It is enabled by default if fetch_synctokens is also enabled. Applications can take advantage of this new feature without modifying any code other than enabling these settings. If you are checking durability constraints across client instances, and fetch_synctokens is enabled, then this setting should be disabled. Otherwise, the client will fail to retrieve the lcb_SYNCTOKEN (see more about this in the Enhanced Durability section). Alternatively, you can supply the sync token directly in the command structure. dur_mutation_tokens=1 */ else if (stricmp(optName, "detailed_errcodes")==0 || stricmp(optName, "operation_timeout")==0 || stricmp(optName, "config_total_timeout")==0 || stricmp(optName, "config_node_timeout")==0 || stricmp(optName, "views_timeout")==0 || stricmp(optName, "durabilty_timeout")==0 || stricmp(optName, "durabilty_interval")==0 || stricmp(optName, "ipv6")==0 || stricmp(optName, "randomize_nodes")==0 || stricmp(optName, "config_cache_ro")==0 || stricmp(optName, "http_poolsize")==0 || stricmp(optName, "error_thresh_delay")==0 || stricmp(optName, "fetch_mutation_tokens")==0 || stricmp(optName, "dur_mutation_tokens")==0 || stricmp(optName, "http_poolsize")==0 || stricmp(optName, "config_cache")==0 || stricmp(optName, "certpath")==0 || stricmp(optName, "sasl_mech_force")==0 || stricmp(optName, "bootstrap_on")==0 || stricmp(optName, "console_log_level")==0) connectionOptions.appendf("%s%s=%s", connectionOptions.length() == 0 ? "?" : "&", optName.str(), val); else failx("Unknown option %s", optName.str()); } } std::call_once(connectionCacheInitFlag, setupConnectionCache, logctx.queryTraceLevel()); // Get a cached idle connection or create a new one m_oCBConnection = connectionCache->getConnection(useSSL, server, port, bucketname, password, connectionOptions.str(), maxConnections, user); } CouchbaseEmbedFunctionContext::~CouchbaseEmbedFunctionContext() { if (m_pQcmd) { delete m_pQcmd; m_pQcmd = nullptr; } if (m_pQuery) { delete m_pQuery; m_pQuery = nullptr; } if (m_oCBConnection) { // When the context is deleted we should return any connection // object back to idle status connectionCache->releaseActive(m_oCBConnection); m_oCBConnection = nullptr; } } IPropertyTree * CouchbaseEmbedFunctionContext::nextResultRowTree() { if (m_pQuery) { reportIfQueryFailure(m_pQuery); // Only the first callback query is processed auto json = m_pQuery->begin()->json().to_string(); Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json.c_str()); return contentTree.getLink(); } return nullptr; } IPropertyTreeIterator * CouchbaseEmbedFunctionContext::nextResultRowIterator() { if (m_pQuery) { reportIfQueryFailure(m_pQuery); // Only the first callback query is processed auto json = m_pQuery->begin()->json().to_string(); Owned<IPropertyTree> contentTree = createPTreeFromJSONString(json.c_str()); if (contentTree) return contentTree->getElements("./*"); failx("Could not fetch next result row."); } return nullptr; } const char * CouchbaseEmbedFunctionContext::nextResultScalar() { m_resultrow.setown(nextResultRowIterator()); if (m_resultrow) { m_resultrow->first(); if(m_resultrow->isValid() == true) { if (m_resultrow->query().hasChildren()) typeError("scalar", ""); return m_resultrow->query().queryProp(""); } else failx("Could not fetch next result column."); } else failx("Could not fetch next result row."); return nullptr; } bool CouchbaseEmbedFunctionContext::getBooleanResult() { bool mybool; auto scalar = nextResultScalar(); handleDeserializeOutcome(m_tokenDeserializer.deserialize(scalar, mybool), "bool", scalar); return mybool; } void CouchbaseEmbedFunctionContext::getDataResult(size32_t &len, void * &result) { auto value = nextResultScalar(); if (value && *value) { rtlStrToDataX(len, result, strlen(value), value); // This feels like it may not work to me - will preallocate rather larger than we want } else { rtlStrToDataX(len, result, NULLFIELD.resultChars, NULLFIELD.stringResult); } } double CouchbaseEmbedFunctionContext::getRealResult() { double mydouble = 0.0; auto value = nextResultScalar(); handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mydouble), "real", value); return mydouble; } __int64 CouchbaseEmbedFunctionContext::getSignedResult() { __int64 myint64 = 0; auto value = nextResultScalar(); handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myint64), "signed", value); return myint64; } unsigned __int64 CouchbaseEmbedFunctionContext::getUnsignedResult() { unsigned __int64 myuint64 = 0; auto value = nextResultScalar(); handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myuint64), "unsigned", value); return myuint64; } void CouchbaseEmbedFunctionContext::getStringResult(size32_t &chars, char * &result) { auto value = nextResultScalar(); if (value && *value) { unsigned numchars = rtlUtf8Length(strlen(value), value); rtlUtf8ToStrX(chars, result, numchars, value); } else { rtlStrToStrX(chars, result, NULLFIELD.resultChars, NULLFIELD.stringResult); } } void CouchbaseEmbedFunctionContext::getUTF8Result(size32_t &chars, char * &result) { getStringResult(chars, result); } void CouchbaseEmbedFunctionContext::getUnicodeResult(size32_t &chars, UChar * &result) { auto value = nextResultScalar(); if (value && *value) { unsigned numchars = rtlUtf8Length(strlen(value), value); rtlUtf8ToUnicodeX(chars, result, numchars, value); } else { rtlUnicodeToUnicodeX(chars, result, NULLFIELD.resultChars, NULLFIELD.unicodeResult); } } void CouchbaseEmbedFunctionContext::getDecimalResult(Decimal &value) { auto text = nextResultScalar(); if (text && *text) value.setString(rtlUtf8Length(strlen(text), text), text); else value.set(NULLFIELD.decimalResult); } IRowStream * CouchbaseEmbedFunctionContext::getDatasetResult(IEngineRowAllocator * _resultAllocator) { Owned<CouchbaseRowStream> cbaseRowStream; cbaseRowStream.setown(new CouchbaseRowStream(_resultAllocator, m_pQuery)); return cbaseRowStream.getLink(); } byte * CouchbaseEmbedFunctionContext::getRowResult(IEngineRowAllocator * _resultAllocator) { Owned<CouchbaseRowStream> cbaseRowStream; cbaseRowStream.setown(new CouchbaseRowStream(_resultAllocator, m_pQuery)); return (byte *)cbaseRowStream->nextRow(); } size32_t CouchbaseEmbedFunctionContext::getTransformResult(ARowBuilder & rowBuilder) { execute(); auto resultrow = nextResultRowTree(); if (!resultrow) fail("Failed to read row"); if (resultrow->getCount("./*") != 1) typeError("row", ""); CouchbaseRowBuilder couchbaseRowBuilder(resultrow); const RtlTypeInfo *typeInfo = rowBuilder.queryAllocator()->queryOutputMeta()->queryTypeInfo(); assertex(typeInfo); RtlFieldStrInfo dummyField("<row>", NULL, typeInfo); return typeInfo->build(rowBuilder, 0, &dummyField, couchbaseRowBuilder); } void CouchbaseEmbedFunctionContext::bindRowParam(const char *name, IOutputMetaData & metaVal, const byte *val) { CouchbaseRecordBinder binder(logctx, metaVal.queryTypeInfo(), m_pQcmd, m_nextParam); binder.processRow(val); m_nextParam += binder.numFields(); } void CouchbaseEmbedFunctionContext::bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val) { // We only support a single dataset parameter... // MORE - look into batch? if (m_oInputStream) { fail("At most one dataset parameter supported"); } m_oInputStream.setown(new CouchbaseDatasetBinder(logctx, LINK(val), metaVal.queryTypeInfo(), m_pQcmd, m_nextParam)); m_nextParam += m_oInputStream->numFields(); } void CouchbaseEmbedFunctionContext::bindBooleanParam(const char *name, bool val) { checkNextParam(name); StringBuffer serialized; m_tokenSerializer.serialize(val, serialized); VStringBuffer cbPlaceholder("$%s", name); auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } void CouchbaseEmbedFunctionContext::bindDataParam(const char *name, size32_t len, const void *val) { checkNextParam(name); VStringBuffer cbPlaceholder("$%s", name); size32_t bytes; void *data; rtlStrToDataX(bytes, data, len, val); auto status = m_pQcmd->named_param(cbPlaceholder.str(), (char *)data); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), (char *)data); if (data) rtlFree(data); } void CouchbaseEmbedFunctionContext::bindFloatParam(const char *name, float val) { checkNextParam(name); StringBuffer serialized; m_tokenSerializer.serialize(val, serialized); VStringBuffer cbPlaceholder("$%s", name); auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } void CouchbaseEmbedFunctionContext::bindRealParam(const char *name, double val) { checkNextParam(name); StringBuffer serialized; m_tokenSerializer.serialize(val, serialized); VStringBuffer cbPlaceholder("$%s", name); auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } void CouchbaseEmbedFunctionContext::bindSignedSizeParam(const char *name, int size, __int64 val) { bindSignedParam(name, val); } void CouchbaseEmbedFunctionContext::bindSignedParam(const char *name, __int64 val) { checkNextParam(name); StringBuffer serialized; m_tokenSerializer.serialize(val, serialized); VStringBuffer cbPlaceholder("$%s", name); auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } void CouchbaseEmbedFunctionContext::bindUnsignedSizeParam(const char *name, int size, unsigned __int64 val) { bindUnsignedParam(name, val); } void CouchbaseEmbedFunctionContext::bindUnsignedParam(const char *name, unsigned __int64 val) { checkNextParam(name); StringBuffer serialized; m_tokenSerializer.serialize(val, serialized); VStringBuffer cbPlaceholder("$%s", name); auto status = m_pQcmd->named_param(cbPlaceholder.str(), serialized.str()); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), serialized.str()); } void CouchbaseEmbedFunctionContext::bindStringParam(const char *name, size32_t len, const char *val) { checkNextParam(name); VStringBuffer cbPlaceholder("$%s", name); size32_t utf8chars; char *utf8; rtlStrToUtf8X(utf8chars, utf8, len, val); auto status = m_pQcmd->named_param(cbPlaceholder.str(), utf8); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8); if (utf8) rtlFree(utf8); } void CouchbaseEmbedFunctionContext::bindVStringParam(const char *name, const char *val) { checkNextParam(name); bindStringParam(name, strlen(val), val); } void CouchbaseEmbedFunctionContext::bindUTF8Param(const char *name, size32_t chars, const char *val) { checkNextParam(name); bindStringParam(name, strlen(val), val); } void CouchbaseEmbedFunctionContext::bindUnicodeParam(const char *name, size32_t chars, const UChar *val) { checkNextParam(name); VStringBuffer cbPlaceholder("$%s", name); size32_t utf8chars; char *utf8; rtlUnicodeToUtf8X(utf8chars, utf8, chars, val); auto status = m_pQcmd->named_param(cbPlaceholder.str(), utf8); if (!status.success()) failx("Could not bind Param: %s val: %s", cbPlaceholder.str(), utf8); } void CouchbaseEmbedFunctionContext::compileEmbeddedScript(size32_t chars, const char *script) { if (script && *script) { // Incoming script is not necessarily null terminated. Note that the chars refers to utf8 characters and not bytes. size32_t len = rtlUtf8Size(chars, script); if (len > 0) { StringAttr queryScript; queryScript.set(script, len); const char * terminatedScript = queryScript.get(); // Now null terminated if (m_pQcmd) delete m_pQcmd; m_pQcmd = new Couchbase::QueryCommand(terminatedScript); if ((m_scriptFlags & EFnoparams) == 0) m_numParams = countParameterPlaceholders(terminatedScript); else m_numParams = 0; } else failx("Empty N1QL query detected"); } else failx("Empty N1QL query detected"); } void CouchbaseEmbedFunctionContext::callFunction() { execute(); } void CouchbaseEmbedFunctionContext::execute() { if (m_oInputStream) m_oInputStream->executeAll(m_oCBConnection); else { if (m_pQuery) delete m_pQuery; m_pQuery = m_oCBConnection->query(m_pQcmd); reportIfQueryFailure(m_pQuery); } } unsigned CouchbaseEmbedFunctionContext::checkNextParam(const char *name) { if (m_nextParam == m_numParams) failx("Too many parameters supplied: No matching $<name> placeholder for parameter %s", name); return m_nextParam++; } bool CouchbaseRowBuilder::getBooleanResult(const RtlFieldInfo *field) { const char * value = nextField(field); if (!value || !*value) { NullFieldProcessor p(field); return p.boolResult; } bool mybool; couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mybool), "bool", value); return mybool; } void CouchbaseRowBuilder::getDataResult(const RtlFieldInfo *field, size32_t &len, void * &result) { const char * value = nextField(field); if (!value || !*value) { NullFieldProcessor p(field); rtlStrToDataX(len, result, p.resultChars, p.stringResult); return; } rtlStrToDataX(len, result, strlen(value), value); // This feels like it may not work to me - will preallocate rather larger than we want } double CouchbaseRowBuilder::getRealResult(const RtlFieldInfo *field) { const char * value = nextField(field); if (!value || !*value) { NullFieldProcessor p(field); return p.doubleResult; } double mydouble = 0.0; couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, mydouble), "real", value); return mydouble; } __int64 CouchbaseRowBuilder::getSignedResult(const RtlFieldInfo *field) { const char * value = nextField(field); if (!value || !*value) { NullFieldProcessor p(field); return p.uintResult; } __int64 myint64 = 0; couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myint64), "signed", value); return myint64; } unsigned __int64 CouchbaseRowBuilder::getUnsignedResult(const RtlFieldInfo *field) { const char * value = nextField(field); if (!value || !*value) { NullFieldProcessor p(field); return p.uintResult; } unsigned __int64 myuint64 = 0; couchbaseembed::handleDeserializeOutcome(m_tokenDeserializer.deserialize(value, myuint64), "unsigned", value); return myuint64; } void CouchbaseRowBuilder::getStringResult(const RtlFieldInfo *field, size32_t &chars, char * &result) { const char * value = nextField(field); if (!value || !*value) { NullFieldProcessor p(field); rtlStrToStrX(chars, result, p.resultChars, p.stringResult); return; } unsigned numchars = rtlUtf8Length(strlen(value), value); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think rtlUtf8ToStrX(chars, result, numchars, value); return; } void CouchbaseRowBuilder::getUTF8Result(const RtlFieldInfo *field, size32_t &chars, char * &result) { getStringResult(field, chars, result); return; } void CouchbaseRowBuilder::getUnicodeResult(const RtlFieldInfo *field, size32_t &chars, UChar * &result) { const char * value = nextField(field); if (!value || !*value) { NullFieldProcessor p(field); rtlUnicodeToUnicodeX(chars, result, p.resultChars, p.unicodeResult); return; } unsigned numchars = rtlUtf8Length(strlen(value), value); // MORE - is it a good assumption that it is utf8 ? Depends how the database is configured I think rtlUtf8ToUnicodeX(chars, result, numchars, value); return; } void CouchbaseRowBuilder::getDecimalResult(const RtlFieldInfo *field, Decimal &value) { const char * dvalue = nextField(field); if (!dvalue || !*dvalue) { NullFieldProcessor p(field); value.set(p.decimalResult); return; } size32_t chars; rtlDataAttr result; value.setString(strlen(dvalue), dvalue); RtlDecimalTypeInfo *dtype = (RtlDecimalTypeInfo *) field->type; value.setPrecision(dtype->getDecimalDigits(), dtype->getDecimalPrecision()); } void CouchbaseRowBuilder::processBeginSet(const RtlFieldInfo * field, bool &isAll) { isAll = false; // ALL not supported StringBuffer xpath; xpathOrName(xpath, field); if (!xpath.isEmpty()) { PathTracker newPathNode(xpath, CPNTSet); StringBuffer newXPath; constructNewXPath(newXPath, xpath.str()); newPathNode.childCount = m_oResultRow->getCount(newXPath); m_pathStack.push_back(newPathNode); } else { failx("processBeginSet: Field name or xpath missing"); } } bool CouchbaseRowBuilder::processNextSet(const RtlFieldInfo * field) { return m_pathStack.back().childrenProcessed < m_pathStack.back().childCount; } void CouchbaseRowBuilder::processBeginDataset(const RtlFieldInfo * field) { StringBuffer xpath; xpathOrName(xpath, field); if (!xpath.isEmpty()) { PathTracker newPathNode(xpath, CPNTDataset); StringBuffer newXPath; constructNewXPath(newXPath, xpath.str()); newPathNode.childCount = m_oResultRow->getCount(newXPath); m_pathStack.push_back(newPathNode); } else { failx("processBeginDataset: Field name or xpath missing"); } } void CouchbaseRowBuilder::processBeginRow(const RtlFieldInfo * field) { StringBuffer xpath; xpathOrName(xpath, field); if (!xpath.isEmpty()) { if (strncmp(xpath.str(), "<nested row>", 12) == 0) { // Row within child dataset if (m_pathStack.back().nodeType == CPNTDataset) { m_pathStack.back().currentChildIndex++; } else { failx("<nested row> received with no outer dataset designated"); } } else { m_pathStack.push_back(PathTracker(xpath, CPNTScalar)); } } else { failx("processBeginRow: Field name or xpath missing"); } } bool CouchbaseRowBuilder::processNextRow(const RtlFieldInfo * field) { return m_pathStack.back().childrenProcessed < m_pathStack.back().childCount; } void CouchbaseRowBuilder::processEndSet(const RtlFieldInfo * field) { StringBuffer xpath; xpathOrName(xpath, field); if (!xpath.isEmpty() && !m_pathStack.empty() && strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0) { m_pathStack.pop_back(); } } void CouchbaseRowBuilder::processEndDataset(const RtlFieldInfo * field) { StringBuffer xpath; xpathOrName(xpath, field); if (!xpath.isEmpty()) { if (!m_pathStack.empty() && strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0) { m_pathStack.pop_back(); } } else { failx("processEndDataset: Field name or xpath missing"); } } void CouchbaseRowBuilder::processEndRow(const RtlFieldInfo * field) { StringBuffer xpath; xpathOrName(xpath, field); if (!xpath.isEmpty()) { if (!m_pathStack.empty()) { if (m_pathStack.back().nodeType == CPNTDataset) { m_pathStack.back().childrenProcessed++; } else if (strcmp(xpath.str(), m_pathStack.back().nodeName.str()) == 0) { m_pathStack.pop_back(); } } } else { failx("processEndRow: Field name or xpath missing"); } } const char * CouchbaseRowBuilder::nextField(const RtlFieldInfo * field) { StringBuffer xpath; xpathOrName(xpath, field); if (xpath.isEmpty()) { failx("nextField: Field name or xpath missing"); } StringBuffer fullXPath; if (!m_pathStack.empty() && m_pathStack.back().nodeType == CPNTSet && strncmp(xpath.str(), "<set element>", 13) == 0) { m_pathStack.back().currentChildIndex++; constructNewXPath(fullXPath, NULL); m_pathStack.back().childrenProcessed++; } else { constructNewXPath(fullXPath, xpath.str()); } return m_oResultRow->queryProp(fullXPath.str()); } void CouchbaseRowBuilder::xpathOrName(StringBuffer & outXPath, const RtlFieldInfo * field) const { outXPath.clear(); if (field->xpath) { if (field->xpath[0] == xpathCompoundSeparatorChar) { outXPath.append(field->xpath + 1); } else { const char * sep = strchr(field->xpath, xpathCompoundSeparatorChar); if (!sep) { outXPath.append(field->xpath); } else { outXPath.append(field->xpath, 0, static_cast<size32_t>(sep - field->xpath)); } } } else { outXPath.append(field->name); } } void CouchbaseRowBuilder::constructNewXPath(StringBuffer& outXPath, const char * nextNode) const { bool nextNodeIsFromRoot = (nextNode && *nextNode == '/'); outXPath.clear(); if (!nextNodeIsFromRoot) { // Build up full parent xpath using our previous components for (std::vector<PathTracker>::const_iterator iter = m_pathStack.begin(); iter != m_pathStack.end(); iter++) { if (strncmp(iter->nodeName, "<row>", 5) != 0) { if (!outXPath.isEmpty()) { outXPath.append("/"); } outXPath.append(iter->nodeName); if (iter->nodeType == CPNTDataset || iter->nodeType == CPNTSet) { outXPath.appendf("[%d]", iter->currentChildIndex); } } } } if (nextNode && *nextNode) { if (!outXPath.isEmpty()) { outXPath.append("/"); } outXPath.append(nextNode); } } class CouchbaseEmbedContext : public CInterfaceOf<IEmbedContext> { public: virtual IEmbedFunctionContext * createFunctionContext(unsigned flags, const char *options) override { return createFunctionContextEx(nullptr, nullptr, flags, options); } virtual IEmbedFunctionContext * createFunctionContextEx(ICodeContext * ctx, const IThorActivityContext *activityCtx, unsigned flags, const char *options) override { if (flags & EFimport) { UNSUPPORTED("IMPORT"); return nullptr; } else return new CouchbaseEmbedFunctionContext(ctx ? ctx->queryContextLogger() : queryDummyContextLogger(), options, flags); } virtual IEmbedServiceContext * createServiceContext(const char *service, unsigned flags, const char *options) override { throwUnexpected(); return nullptr; } }; extern DECL_EXPORT IEmbedContext* getEmbedContext() { return new CouchbaseEmbedContext(); } extern DECL_EXPORT bool syntaxCheck(const char *script) { return true; // TO-DO } } // namespace MODULE_INIT(INIT_PRIORITY_STANDARD) { couchbaseembed::connectionCache = nullptr; couchbaseembed::connectionCacheExpirer = nullptr; return true; } MODULE_EXIT() { // Delete the background thread expiring items from the CouchbaseConnection // cache before deleting the connection cache if (couchbaseembed::connectionCacheExpirer) { couchbaseembed::connectionCacheExpirer->stop(); delete(couchbaseembed::connectionCacheExpirer); couchbaseembed::connectionCacheExpirer = nullptr; } if (couchbaseembed::connectionCache) { couchbaseembed::connectionCache->deleteAll(); delete(couchbaseembed::connectionCache); couchbaseembed::connectionCache = nullptr; } }
/* ----------------------------------------------------------------------------- This source file is part of OGRE-Next (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreVulkanHardwareBufferCommon.h" #include "OgreStringConverter.h" #include "OgreVulkanDevice.h" #include "OgreVulkanDiscardBufferManager.h" #include "OgreVulkanUtils.h" #include "Vao/OgreVulkanDynamicBuffer.h" #include "Vao/OgreVulkanStagingBuffer.h" #include "Vao/OgreVulkanVaoManager.h" namespace Ogre { namespace v1 { VulkanHardwareBufferCommon::VulkanHardwareBufferCommon( size_t sizeBytes, HardwareBuffer::Usage usage, uint16 alignment, VulkanDiscardBufferManager *discardBufferManager, VulkanDevice *device ) : mDevice( device ), mDiscardBuffer( 0 ), mVaoManager( discardBufferManager->getVaoManager() ), mStagingBuffer( 0 ) { memset( &mBuffer, 0, sizeof( mBuffer ) ); mBuffer.mSize = sizeBytes; mLastFrameUsed = mVaoManager->getFrameCount() - mVaoManager->getDynamicBufferMultiplier(); mLastFrameGpuWrote = mLastFrameUsed; VulkanVaoManager *vaoManager = static_cast<VulkanVaoManager *>( mVaoManager ); VulkanVaoManager::VboFlag vboFlag; if( usage & HardwareBuffer::HBU_WRITE_ONLY ) vboFlag = VulkanVaoManager::CPU_INACCESSIBLE; else vboFlag = VulkanVaoManager::CPU_WRITE_PERSISTENT; if( !( usage & HardwareBuffer::HBU_DISCARDABLE ) ) mBuffer = vaoManager->allocateRawBuffer( vboFlag, sizeBytes ); else mDiscardBuffer = discardBufferManager->createDiscardBuffer( sizeBytes, alignment ); } VulkanHardwareBufferCommon::~VulkanHardwareBufferCommon() { if( mDiscardBuffer ) { VulkanDiscardBufferManager *discardBufferManager = mDiscardBuffer->getOwner(); discardBufferManager->destroyDiscardBuffer( mDiscardBuffer ); mDiscardBuffer = 0; } else { VulkanVaoManager *vaoManager = static_cast<VulkanVaoManager *>( mVaoManager ); vaoManager->deallocateRawBuffer( mBuffer ); } } void VulkanHardwareBufferCommon::_notifyDeviceStalled() { mLastFrameUsed = mVaoManager->getFrameCount() - mVaoManager->getDynamicBufferMultiplier(); mLastFrameGpuWrote = mLastFrameUsed; } VkBuffer VulkanHardwareBufferCommon::getBufferName( size_t &outOffset ) { mLastFrameUsed = mVaoManager->getFrameCount(); if( !mDiscardBuffer ) { outOffset = mBuffer.mInternalBufferStart; return mBuffer.mVboName; } else return mDiscardBuffer->getBufferName( outOffset ); } VkBuffer VulkanHardwareBufferCommon::getBufferNameForGpuWrite( size_t &outOffset ) { assert( !mDiscardBuffer && "Discardable buffers can't be written from GPU!" ); mLastFrameUsed = mVaoManager->getFrameCount(); mLastFrameGpuWrote = mLastFrameUsed; outOffset = mBuffer.mInternalBufferStart; return mBuffer.mVboName; } void *VulkanHardwareBufferCommon::lockImpl( size_t offset, size_t length, HardwareBuffer::LockOptions options, bool isLocked ) { if( isLocked ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Invalid attempt to lock a buffer that has already been locked", "MetalHardwareBufferCommon::lock" ); } void *retPtr = 0; const uint32 currentFrame = mVaoManager->getFrameCount(); const uint32 bufferMultiplier = mVaoManager->getDynamicBufferMultiplier(); if( mDiscardBuffer ) { // If we're here, it was created with HBU_DISCARDABLE bit if( options == HardwareBuffer::HBL_READ_ONLY ) { LogManager::getSingleton().logMessage( "PERFORMANCE WARNING: reads from discardable " "buffers are uncached. May be slow." ); // We can't write from GPU to discardable memory. No need to check } else if( options == HardwareBuffer::HBL_NORMAL || options == HardwareBuffer::HBL_WRITE_ONLY ) { if( currentFrame - mLastFrameUsed < bufferMultiplier ) { LogManager::getSingleton().logMessage( "PERFORMANCE WARNING: locking with HBL_NORMAL or HBL_WRITE_ONLY for a " "buffer created with HBU_DISCARDABLE bit is slow/stalling. Consider " "locking w/ another locking option, or change the buffer's usage flag" ); mDevice->stall(); } } retPtr = mDiscardBuffer->map( options != HardwareBuffer::HBL_DISCARD ); retPtr = static_cast<void *>( static_cast<uint8 *>( retPtr ) + offset ); } else { if( mBuffer.mVboFlag != VulkanVaoManager::CPU_INACCESSIBLE ) { if( options == HardwareBuffer::HBL_READ_ONLY ) { if( currentFrame - mLastFrameGpuWrote < bufferMultiplier ) mDevice->stall(); } else if( options != HardwareBuffer::HBL_NO_OVERWRITE ) { if( currentFrame - mLastFrameUsed < bufferMultiplier ) { LogManager::getSingleton().logMessage( "PERFORMANCE WARNING: locking to a non-HBU_WRITE_ONLY or " "non-HBU_DISCARDABLE for other than reading is slow/stalling." ); mDevice->stall(); } } retPtr = mBuffer.map(); retPtr = static_cast<void *>( static_cast<uint8 *>( retPtr ) + offset ); } else { // If we're here, the buffer was created with HBU_WRITE_ONLY, but not discardable. // Write to a staging buffer to avoid blocking. We don't have to care about // reading access. OGRE_ASSERT_LOW( ( options != HardwareBuffer::HBL_NORMAL && options != HardwareBuffer::HBL_READ_ONLY ) && "Reading from a write-only buffer! Create " "the buffer without HBL_WRITE_ONLY bit (or use readData)" ); OGRE_ASSERT_LOW( !mStagingBuffer && "Invalid state, and mStagingBuffer will leak" ); mStagingBuffer = mVaoManager->getStagingBuffer( length, true ); retPtr = mStagingBuffer->map( length ); } } return retPtr; } void VulkanHardwareBufferCommon::unlockImpl( size_t lockStart, size_t lockSize ) { if( mDiscardBuffer ) { mDiscardBuffer->unmap(); } else if( mStagingBuffer ) { static_cast<VulkanStagingBuffer *>( mStagingBuffer ) ->_unmapToV1( this, lockStart, lockSize ); mStagingBuffer->removeReferenceCount(); mStagingBuffer = 0; } else { mBuffer.unmap(); } } void VulkanHardwareBufferCommon::readData( size_t offset, size_t length, void *pDest ) { assert( ( offset + length ) <= mBuffer.mSize ); void const *srcData = 0; StagingBuffer *stagingBuffer = 0; const uint32 currentFrame = mVaoManager->getFrameCount(); const uint32 bufferMultiplier = mVaoManager->getDynamicBufferMultiplier(); if( mDiscardBuffer ) { // We can't write from GPU to discardable memory. No need to check. srcData = mDiscardBuffer->map( true ); } else { if( mBuffer.mVboFlag != VulkanVaoManager::CPU_INACCESSIBLE ) { if( currentFrame - mLastFrameGpuWrote < bufferMultiplier ) mDevice->stall(); srcData = mBuffer.map(); } else { // Reading from HBL_WRITE_ONLY. stagingBuffer = mVaoManager->getStagingBuffer( length, false ); size_t stagingBufferOffset = static_cast<VulkanStagingBuffer *>( stagingBuffer ) ->_asyncDownloadV1( this, offset, length ); mDevice->stall(); srcData = stagingBuffer->_mapForRead( stagingBufferOffset, length ); offset = 0; } } srcData = static_cast<const void *>( static_cast<const uint8 *>( srcData ) + offset ); memcpy( pDest, srcData, length ); if( stagingBuffer ) stagingBuffer->removeReferenceCount(); } void VulkanHardwareBufferCommon::writeData( size_t offset, size_t length, const void *pSource, bool discardWholeBuffer ) { if( ( discardWholeBuffer && mDiscardBuffer ) || mBuffer.mVboFlag == VulkanVaoManager::CPU_INACCESSIBLE ) { // Fast path is through locking (it either discards or already uses a StagingBuffer). void *dstData = this->lockImpl( offset, length, HardwareBuffer::HBL_DISCARD, false ); memcpy( dstData, pSource, length ); this->unlockImpl( offset, length ); } else { // Use a StagingBuffer to avoid blocking StagingBuffer *stagingBuffer = mVaoManager->getStagingBuffer( length, true ); void *dstData = stagingBuffer->map( length ); memcpy( dstData, pSource, length ); static_cast<VulkanStagingBuffer *>( stagingBuffer )->_unmapToV1( this, offset, length ); stagingBuffer->removeReferenceCount(); } } void VulkanHardwareBufferCommon::copyData( VulkanHardwareBufferCommon *srcBuffer, size_t srcOffset, size_t dstOffset, size_t length, bool discardWholeBuffer ) { if( !this->mDiscardBuffer || mBuffer.mVboFlag == VulkanVaoManager::CPU_INACCESSIBLE ) { mDevice->mGraphicsQueue.getCopyEncoderV1Buffer( false ); size_t srcOffsetStart = 0; size_t dstOffsetStart = 0; VkBuffer srcBuf = srcBuffer->getBufferName( srcOffsetStart ); VkBuffer dstBuf = this->getBufferNameForGpuWrite( dstOffsetStart ); VkBufferCopy region; region.srcOffset = srcOffset + srcOffsetStart; region.dstOffset = dstOffset + dstOffsetStart; region.size = alignToNextMultiple<size_t>( length, 4u ); vkCmdCopyBuffer( mDevice->mGraphicsQueue.mCurrentCmdBuffer, srcBuf, dstBuf, 1u, &region ); if( this->mDiscardBuffer ) mDevice->stall(); } else { HardwareBuffer::LockOptions dstOption; if( discardWholeBuffer ) dstOption = HardwareBuffer::HBL_DISCARD; else dstOption = HardwareBuffer::HBL_WRITE_ONLY; const void *srcData = srcBuffer->lockImpl( srcOffset, length, HardwareBuffer::HBL_READ_ONLY, false ); void *dstData = this->lockImpl( dstOffset, length, dstOption, false ); memcpy( dstData, srcData, length ); this->unlockImpl( dstOffset, length ); srcBuffer->unlockImpl( srcOffset, length ); } } } // namespace v1 } // namespace Ogre
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "URIResult.h" namespace aria2 { URIResult::URIResult(const std::string& uri, error_code::Value result) : uri_(uri), result_(result) {} URIResult::~URIResult() {} } // namespace aria2
#include "pch.h" #include "FileTree.h" void FileTree::renderAssetsTree(const std::string& path) { long long id = PyUtils::getInstance()->getMathUtil().attr("md5Hash")(path, "long").cast<long long>(); auto file_name = PyUtils::getInstance()->getOs().attr("path").attr("basename")(path).cast<std::string>(); file_name = PyUtils::getInstance()->getStrUtil().attr("getFileName")(file_name).cast<std::string>(); float dir_icon_pos = ImGui::GetCursorPosX(); if (ImGui::TreeNode(path.c_str(), file_name.c_str())) { // tree begins // right click if (ImGui::IsItemClicked(1)) m_selected_menu_id = id; if (id == m_selected_menu_id) renderRightMouseMenuAssets(path, id); ImGui::SameLine(); ImGui::SetCursorPosX(dir_icon_pos); ImGui::Image(Resources::getFileFormatIcon("assets_file")); for (auto& asset : pe::Assets::getAssets()) { ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // texture if (asset.second->getType() == pe::Asset::Type::Texture) { long long id = PyUtils::getInstance()->getMathUtil().attr("md5Hash")(std::string(path).append(std::to_string(asset.first)), "long").cast<long long>(); if (m_selected_id == id) node_flags |= ImGuiTreeNodeFlags_Selected; ImGui::Image(Resources::getFileFormatIcon("asset_texture")); ImGui::SameLine(); ImGui::SetCursorPosX(ImGui::GetCursorPosX() - 20); ImGui::TreeNodeEx(std::string(asset.second->getName()).c_str(), node_flags); // click node if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) { ImageViwer::getInstance()->openImageViwer(pe::Assets::getAsset<pe::Texture>(asset.second->getId())->getPath()); } if (ImGui::IsItemClicked(0)) m_selected_id = id; if (ImGui::IsItemClicked(1)) m_selected_menu_id = id; if (id == m_selected_menu_id) renderRightMouseMenuTexture(asset.second->getId()); }// font else if (asset.second->getType() == pe::Asset::Type::Font) { long long id = PyUtils::getInstance()->getMathUtil().attr("md5Hash")(std::string(path).append(std::to_string(asset.first)), "long").cast<long long>(); if (m_selected_id == id) node_flags |= ImGuiTreeNodeFlags_Selected; ImGui::Image(Resources::getFileFormatIcon("asset_font")); ImGui::SameLine(); ImGui::SetCursorPosX(ImGui::GetCursorPosX() - 20); ImGui::TreeNodeEx(std::string(asset.second->getName()).c_str(), node_flags); // click node if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(0)) { FontViwer::getInstance()->openFontViwer(pe::Assets::getAsset<pe::Font>(asset.second->getId())->getPath()); } if (ImGui::IsItemClicked(0)) m_selected_id = id; if (ImGui::IsItemClicked(1)) m_selected_menu_id = id; if (id == m_selected_menu_id) renderRightMouseMenuFont(asset.second->getId()); } } ImGui::TreePop(); } else { // asset close if (ImGui::IsItemClicked(1)) m_selected_menu_id = id; if (id == m_selected_menu_id) renderRightMouseMenuAssets(path, id); ImGui::SameLine(); ImGui::SetCursorPosX(dir_icon_pos); ImGui::Image(Resources::getFileFormatIcon("assets_file")); } } void FileTree::renderRightMouseMenuAssets(const std::string& path, long long id) { if (ImGui::BeginPopupContextItem("right mouse menu")) { //ImGui::Image(Resources::getMenuIcon("open_in_explorer")); ImGui::SameLine(); if (ImGui::Selectable("Open in TextEditor")) { std::string title = PyUtils::getInstance()->getOs().attr("path").attr("basename")(path).cast<std::string>(); TextEditors::openTextEditor(title, path, id, TextEditor::LanguageDefinition::C()); } if (ImGui::Selectable("Reload")) { CLI::getInstance()->assetsFileUpdate(); } ImGui::Image(Resources::getMenuIcon("open_in_explorer")); ImGui::SameLine(); if (ImGui::Selectable("Open in Explorer")) { PyUtils::getInstance()->getOs().attr("system")(std::string("explorer \"").append( PyUtils::getInstance()->getOs().attr("path").attr("dirname")(path).cast<std::string>() ).append("\"")); } ImGui::EndPopup(); } } void FileTree::renderRightMouseMenuTexture(int texture_id) { if (ImGui::BeginPopupContextItem("right mouse menu")) { bool modified = false; if (ImGui::MenuItem("Open in Image Viwer")) { ImageViwer::getInstance()->openImageViwer(pe::Assets::getAsset<pe::Texture>(texture_id)->getPath()); } bool smooth = pe::Assets::getAsset<pe::Texture>(texture_id)->isSmooth(); if (ImGui::MenuItem("Smooth", NULL, &smooth)) { pe::Assets::getAsset<pe::Texture>(texture_id)->setSmooth(smooth); modified = true; ImGui::CloseCurrentPopup(); } bool repeated = pe::Assets::getAsset<pe::Texture>(texture_id)->isRepeated(); if (ImGui::MenuItem("Repeated", NULL, &repeated)) { pe::Assets::getAsset<pe::Texture>(texture_id)->setRepeated(repeated); modified = true; ImGui::CloseCurrentPopup(); } if (ImGui::BeginMenu("See Path")) { ImGui::Text(pe::Assets::getAsset<pe::Texture>(texture_id)->getPath().c_str()); ImGui::EndMenu(); } if (modified) CLI::getInstance()->updateTexture(pe::Assets::getAsset<pe::Texture>(texture_id)); ImGui::EndPopup(); } } void FileTree::renderRightMouseMenuFont(int font_id) { if (ImGui::BeginPopupContextItem("right mouse menu")) { if (ImGui::MenuItem("Open in Font Viwer")) { FontViwer::getInstance()->openFontViwer(pe::Assets::getAsset<pe::Font>(font_id)->getPath()); } if (ImGui::BeginMenu("See Path")) { ImGui::Text(pe::Assets::getAsset<pe::Font>(font_id)->getPath().c_str()); ImGui::EndMenu(); } ImGui::EndPopup(); } }
// Optimise #include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "/home/shahraaz/bin/debug.h" #else #define db(...) #endif using ll = long long; #define f first #define s second #define pb push_back #define all(v) v.begin(), v.end() const int NAX = 2e5 + 5, MOD = 1000000007; struct Solution { Solution() {} void solveCase() { int n, k, l; cin >> n >> k >> l; vector<int> d(n); for (auto &x : d) cin >> x; for (auto &x : d) if (x > l) { cout << "No\n"; return; } int pos = min(k, l - d[0]); int sign = -1; db("---------"); for (size_t i = 0; i < n; i++) { db(i, pos, d[i] + pos, l); if (d[i] + pos > l) { if (sign == 1) { cout << "No\n"; return; } pos = l - d[i]; } db(i, pos, d[i] + pos, l, "\n"); if (l - d[i] >= k) { sign = -1; pos = k; } if (sign == -1) { pos--; if (pos == -1) { sign = 1; pos = 1; } } else { pos++; if (pos == (k + 1)) { sign = -1; pos = k - 1; } } } cout << "Yes\n"; } }; int32_t main() { #ifndef LOCAL ios_base::sync_with_stdio(0); cin.tie(0); #endif int t = 1; cin >> t; Solution mySolver; for (int i = 1; i <= t; ++i) { mySolver.solveCase(); #ifdef LOCAL cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n"; TimeStart = chrono::steady_clock::now(); #endif } return 0; }
/* $Id$ * * Copyright : (c) 2015 Open Source Solutions Pty Ltd. All Rights Reserved * Project : report_generator * File : VisitorText * * Author : Denis Dowling * Created : 8/5/2009 * * Description : Render a report in Text */ #include "VisitorText.h" #include "Section.h" #include "Paragraph.h" #include "Table.h" #include "WordWrap.h" #include "BoxDrawingCharacters.h" #include "List.h" #include "Image.h" #include <boost/foreach.hpp> using namespace report_generator; VisitorText::VisitorText(bool use_colour) : sectionLevel(0), useColour(use_colour) { } std::string VisitorText::getText() const { return ss.str(); } void VisitorText::enterReport(Report & /*r*/) { } void VisitorText::exitReport(Report & /*r*/) { } void VisitorText::enterSection(Section & s) { sectionLevel++; ss << s.getHeading() << "\n"; std::string rule = getLineStr(B_DOUBLE_HORIZONTAL, s.getHeading().size()); ss << rule << "\n\n"; } void VisitorText::exitSection(Section & /*s*/) { sectionLevel--; } void VisitorText::enterParagraph(Paragraph &p) { // FIXME Where does the width come from std::vector<std::string> sv = wordWrap(p.getText(), 80); BOOST_FOREACH(const std::string &s, sv) ss << s << "\n"; } void VisitorText::exitParagraph(Paragraph & /*p*/) { ss << "\n"; } void VisitorText::enterTable(Table &t) { ss << t.renderAsASCII(useColour); } void VisitorText::exitTable(Table & /*t*/) { // Nothing to do } void VisitorText::enterList(List &l) { ss << l.renderAsASCII(); } void VisitorText::exitList(List & /*l*/) { // Nothing to do } void VisitorText::visitImage(Image &i) { ss << i.renderAsASCII(); }
#pragma once #include <Siv3D.hpp> #include "Constraint.hpp" namespace s3d::aoba { enum class LayerDirection { Top, Bottom, CenterY, Height, Left, Right, CenterX, Width }; struct Layer { private: Constraint m_top, m_bottom, m_centerY, m_height, m_left, m_right, m_centerX, m_width; public: Rect asRect() const { return asRectF().asRect(); } RectF asRectF() const { return RectF(m_left, m_top, m_width, m_height); } Vec2 center() const { return Vec2(m_centerX, m_centerY); } const Constraint& top() const { return m_top; } const Constraint& bottom() const { return m_bottom; } const Constraint& centerY() const { return m_centerY; } const Constraint& height() const { return m_height; } const Constraint& left() const { return m_left; } const Constraint& right() const { return m_right; } const Constraint& centerX() const { return m_centerX; } const Constraint& width() const { return m_width; } void updateConstraints(); void setConstraint(LayerDirection direction, double constant, double multiplier); void setConstraint(LayerDirection direction, const std::function<double()>& func, double constant, double multiplier); void setConstraint(LayerDirection direction, Layer& otherLayer, LayerDirection otherLayerDirection, double constant, double multiplier); void removeConstraint(LayerDirection direction); void removeAllConstraints(); private: Constraint& constraintReferenceTo(LayerDirection direction); }; }
/* Copyright 2013-2019 MultiMC Contributors * * 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 "settings/INIFile.h" #include <FileSystem.h> #include <QFile> #include <QTextStream> #include <QStringList> #include <QSaveFile> #include <QDebug> INIFile::INIFile() { } QString INIFile::unescape(QString orig) { QString out; QChar prev = 0; for(auto c: orig) { if(prev == '\\') { if(c == 'n') out += '\n'; else if(c == 't') out += '\t'; else if(c == '#') out += '#'; else out += c; prev = 0; } else { if(c == '\\') { prev = c; continue; } out += c; prev = 0; } } return out; } QString INIFile::escape(QString orig) { QString out; for(auto c: orig) { if(c == '\n') out += "\\n"; else if (c == '\t') out += "\\t"; else if(c == '\\') out += "\\\\"; else if(c == '#') out += "\\#"; else out += c; } return out; } bool INIFile::saveFile(QString fileName) { QByteArray outArray; for (Iterator iter = begin(); iter != end(); iter++) { QString value = iter.value().toString(); value = escape(value); outArray.append(iter.key().toUtf8()); outArray.append('='); outArray.append(value.toUtf8()); outArray.append('\n'); } try { FS::write(fileName, outArray); } catch (const Exception &e) { qCritical() << e.what(); return false; } return true; } bool INIFile::loadFile(QString fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) return false; bool success = loadFile(file.readAll()); file.close(); return success; } bool INIFile::loadFile(QByteArray file) { QTextStream in(file); in.setCodec("UTF-8"); QStringList lines = in.readAll().split('\n'); for (int i = 0; i < lines.count(); i++) { QString &lineRaw = lines[i]; // Ignore comments. int commentIndex = 0; QString line = lineRaw; // Search for comments until no more escaped # are available while((commentIndex = line.indexOf('#', commentIndex + 1)) != -1) { if(commentIndex > 0 && line.at(commentIndex - 1) == '\\') { continue; } line = line.left(lineRaw.indexOf('#')).trimmed(); } int eqPos = line.indexOf('='); if (eqPos == -1) continue; QString key = line.left(eqPos).trimmed(); QString valueStr = line.right(line.length() - eqPos - 1).trimmed(); valueStr = unescape(valueStr); QVariant value(valueStr); this->operator[](key) = value; } return true; } QVariant INIFile::get(QString key, QVariant def) const { if (!this->contains(key)) return def; else return this->operator[](key); } void INIFile::set(QString key, QVariant val) { this->operator[](key) = val; }
// Copyright (c) 2016, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder 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. #if !defined __GNUC__ || defined __MINGW32__ || defined __MINGW64__ || defined __ANDROID__ #define USE_UNWIND #else #define ELPP_FEATURE_CRASH_LOG 1 #endif #include "easylogging++/easylogging++.h" #include <stdexcept> #ifdef USE_UNWIND #define UNW_LOCAL_ONLY #include <libunwind.h> #include <cxxabi.h> #endif #ifndef STATICLIB #include <dlfcn.h> #endif #include <boost/algorithm/string.hpp> #include "common/stack_trace.h" #include "misc_log_ex.h" #undef INCOGNITO_DEFAULT_LOG_CATEGORY #define INCOGNITO_DEFAULT_LOG_CATEGORY "stacktrace" #define ST_LOG(x) CINFO(el::base::Writer,el::base::DispatchAction::FileOnlyLog,INCOGNITO_DEFAULT_LOG_CATEGORY) << x // from http://stackoverflow.com/questions/11665829/how-can-i-print-stack-trace-for-caught-exceptions-in-c-code-injection-in-c // The decl of __cxa_throw in /usr/include/.../cxxabi.h uses // 'std::type_info *', but GCC's built-in protype uses 'void *'. #ifdef __clang__ #define CXA_THROW_INFO_T std::type_info #else // !__clang__ #define CXA_THROW_INFO_T void #endif // !__clang__ #ifdef STATICLIB #define CXA_THROW __wrap___cxa_throw extern "C" __attribute__((noreturn)) void __real___cxa_throw(void *ex, CXA_THROW_INFO_T *info, void (*dest)(void*)); #else // !STATICLIB #define CXA_THROW __cxa_throw extern "C" typedef #ifdef __clang__ // only clang, not GCC, lets apply the attr in typedef __attribute__((noreturn)) #endif // __clang__ void (cxa_throw_t)(void *ex, CXA_THROW_INFO_T *info, void (*dest)(void*)); #endif // !STATICLIB extern "C" __attribute__((noreturn)) void CXA_THROW(void *ex, CXA_THROW_INFO_T *info, void (*dest)(void*)) { int status; char *dsym = abi::__cxa_demangle(((const std::type_info*)info)->name(), NULL, NULL, &status); tools::log_stack_trace((std::string("Exception: ")+((!status && dsym) ? dsym : (const char*)info)).c_str()); free(dsym); #ifndef STATICLIB #ifndef __clang__ // for GCC the attr can't be applied in typedef like for clang __attribute__((noreturn)) #endif // !__clang__ cxa_throw_t *__real___cxa_throw = (cxa_throw_t*)dlsym(RTLD_NEXT, "__cxa_throw"); #endif // !STATICLIB __real___cxa_throw(ex, info, dest); } namespace { std::string stack_trace_log; } namespace tools { void set_stack_trace_log(const std::string &log) { stack_trace_log = log; } void log_stack_trace(const char *msg) { #ifdef USE_UNWIND unw_context_t ctx; unw_cursor_t cur; unw_word_t ip, off; unsigned level; char sym[512], *dsym; int status; const char *log = stack_trace_log.empty() ? NULL : stack_trace_log.c_str(); #endif if (msg) ST_LOG(msg); ST_LOG("Unwound call stack:"); #ifdef USE_UNWIND if (unw_getcontext(&ctx) < 0) { ST_LOG("Failed to create unwind context"); return; } if (unw_init_local(&cur, &ctx) < 0) { ST_LOG("Failed to find the first unwind frame"); return; } for (level = 1; level < 999; ++level) { // 999 for safety int ret = unw_step(&cur); if (ret < 0) { ST_LOG("Failed to find the next frame"); return; } if (ret == 0) break; if (unw_get_reg(&cur, UNW_REG_IP, &ip) < 0) { ST_LOG(" " << std::setw(4) << level); continue; } if (unw_get_proc_name(&cur, sym, sizeof(sym), &off) < 0) { ST_LOG(" " << std::setw(4) << level << std::setbase(16) << std::setw(20) << "0x" << ip); continue; } dsym = abi::__cxa_demangle(sym, NULL, NULL, &status); ST_LOG(" " << std::setw(4) << level << std::setbase(16) << std::setw(20) << "0x" << ip << " " << (!status && dsym ? dsym : sym) << " + " << "0x" << off); free(dsym); } #else std::stringstream ss; ss << el::base::debug::StackTrace(); std::vector<std::string> lines; std::string s = ss.str(); boost::split(lines, s, boost::is_any_of("\n")); for (const auto &line: lines) ST_LOG(line); #endif } } // namespace tools
// @brief // Arduino Thunderbolt GPS types #include "gpstype.h" #ifndef NULL #define NULL (0) #endif /*************************** * Fix types * ***************************/ PosFix::PosFix() : type(RPT_NONE) {} VelFix::VelFix() : type(RPT_NONE) {} const LLA_Fix<Float32>* PosFix::getLLA_32() const { if (type == RPT_FIX_POS_LLA_32) return &lla_32; else return NULL; } const LLA_Fix<Float64>* PosFix::getLLA_64() const { if (type == RPT_FIX_POS_LLA_64) return &lla_64; else return NULL; } const XYZ_Fix<Float32>* PosFix::getXYZ_32() const { if (type == RPT_FIX_POS_XYZ_32) return &xyz_32; else return NULL; } const XYZ_Fix<Float64>* PosFix::getXYZ_64() const { if (type == RPT_FIX_POS_XYZ_64) return &xyz_64; else return NULL; } const XYZ_VFix *VelFix::getXYZ() const { if (type == RPT_FIX_VEL_XYZ) return &xyz; else return NULL; } const ENU_VFix *VelFix::getENU() const { if (type == RPT_FIX_VEL_ENU) return &enu; else return NULL; } /************************** * GPSVersion * ***************************/ GPSVersion::GPSVersion() { app.major_ver = 0; app.minor_ver = 0; core.minor_ver = 0; core.minor_ver = 0; } /*************************** * GPSStatus * ***************************/ GPSStatus::GPSStatus() : health(HLTH_UNKNOWN), n_satellites(0), almanac_incomplete(true), rtclock_unavailable(true), sbas_enabled(false), sbas_corrected(false) {} /************************** * GPSTime * ***************************/ GPSTime::GPSTime() : week_no(0), timing_flags(0), Second(0), Minute(0), Hour(0), Day(0), Month(0), Year(0) {}
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/plugin/poplar/driver/tools/custom_ops/ipu_inter_copy.h" #include "tensorflow/compiler/plugin/poplar/driver/tools/hlo_poplar_buffer_util.h" #include "tensorflow/compiler/plugin/poplar/kernels/custom_kernels_util.h" #include "tensorflow/compiler/plugin/poplar/kernels/ops.pb.h" namespace xla { namespace poplarplugin { HloIpuInterCopy::HloIpuInterCopy(absl::Span<HloInstruction* const> operands) : HloPoplarInstruction(GetHloPoplarInstructionShape(operands), operands, PoplarOp::IpuInterCopy) {} absl::flat_hash_set<int64> HloIpuInterCopy::AllocatingIndices() const { return {}; } bool HloIpuInterCopy::AllocatingOutput() const { return false; } absl::flat_hash_map<int64, int64> HloIpuInterCopy::LayoutDependencies() const { return {}; } HloPoplarUseDescriptions HloIpuInterCopy::GetUseDescriptions() const { return UseDescriptionsNoInputOutputAlias(); } HloPoplarBufferDescriptions HloIpuInterCopy::GetBufferDescriptions() const { return BufferDescriptionsAllocatesAllOutputs(this); } const FindConsumersExtensionResults HloIpuInterCopy::FindConsumers( FindConsumersExtensionParams params) const { return FindConsumersExtensionResults::DoNotFindConsumers(); } bool HloIpuInterCopy::IsPopOpsElementwise() const { return false; } std::unique_ptr<HloInstruction> HloIpuInterCopy::CloneWithNewOperandsImpl( const Shape& shape, absl::Span<HloInstruction* const> new_operands, HloCloneContext* context) const { return CreateIpuInterCopy(new_operands); } std::vector<std::string> HloIpuInterCopy::ExtraPoplarAttributesToStringImpl( const HloPrintOptions& options) const { return {}; } std::unique_ptr<HloInstruction> CreateIpuInterCopy( absl::Span<HloInstruction* const> operands) { return absl::make_unique<HloIpuInterCopy>(operands); } } // namespace poplarplugin } // namespace xla
/* * This file is part of the WebKit project. * * Copyright (C) 2009 Michelangelo De Simone <micdesim@gmail.com> * Copyright (C) 2010 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "BaseTextInputType.h" #include "HTMLInputElement.h" #include "HTMLNames.h" #include <JavaScriptCore/RegularExpression.h> namespace WebCore { using namespace HTMLNames; bool BaseTextInputType::isTextType() const { return true; } bool BaseTextInputType::patternMismatch(const String& value) const { const AtomicString& rawPattern = element().attributeWithoutSynchronization(patternAttr); if (rawPattern.isNull() || value.isEmpty() || !JSC::Yarr::RegularExpression(rawPattern).isValid()) return false; String pattern = "^(?:" + rawPattern + ")$"; int matchLength = 0; int valueLength = value.length(); int matchOffset = JSC::Yarr::RegularExpression(pattern).match(value, 0, &matchLength); return matchOffset || matchLength != valueLength; } bool BaseTextInputType::supportsPlaceholder() const { return true; } bool BaseTextInputType::supportsSelectionAPI() const { return true; } } // namespace WebCore
// CSVParser.cpp #include "CSVParser.hpp" #include <iostream> #include <fstream> #include <unistd.h> #include <bits/stdc++.h> #include <sstream> #include <numeric> // std::accumulate template struct ColumnData<int_data_type>; template <typename T> std::ostream &operator<<(std::ostream &os, const ColumnData<T> &cd) { os << "header: " << cd.header << "\nfirst_data_row_index: " << cd.first_data_row_index << "\nheader_row_index: " << cd.header_row_index << "\nheader_col_index: " << cd.header_col_index << "\nnum_rows: " << cd.num_rows << "\ndata_summary_actual: " << cd.data_summary_actual << "\ndata_summary_projected: " << cd.data_summary_projected << "\nnum_segments: " << cd.num_segments << "\ncur_segment: " << cd.cur_segment << "\nsegment_indices: [ "; for(auto index : cd.segment_indices) { std::cout << index << " "; } std::cout << "]" << std::flush; return os; } template std::ostream &operator<<(std::ostream &os, const ColumnData<int_data_type> &cd); template std::ostream &operator<<(std::ostream &os, const ColumnData<float_data_type> &cd); template <typename T> bool operator==(const ColumnData<T> &cd1, const ColumnData<T> &cd2){ return( cd1.header == cd2.header && cd1.first_data_row_index == cd2.first_data_row_index && cd1.header_row_index == cd2.header_row_index && cd1.header_col_index == cd2.header_col_index && cd1.num_rows == cd2.num_rows && cd1.data_summary_actual == cd2.data_summary_actual && cd1.data_summary_projected == cd2.data_summary_projected && cd1.num_segments == cd2.num_segments && cd1.cur_segment == cd2.cur_segment && cd1.segment_indices == cd2.segment_indices); } template bool operator==( const ColumnData<int_data_type> &cd1, const ColumnData<int_data_type> &cd2); template bool operator==( const ColumnData<float_data_type> &cd1, const ColumnData<float_data_type> &cd2); template <typename T> float_data_type calcAvg(const std::vector<ColumnData<T>> &cd_vec) { float_data_type sum {0}; int_data_type n {0}; for(auto const &cd : cd_vec) { sum += std::accumulate(cd.data_raw.begin(), cd.data_raw.end(), 0.0); n += cd.data_raw.size(); } return sum / n; } template float_data_type calcAvg(const std::vector<ColumnData<int_data_type>> &cd); template float_data_type calcAvg(const std::vector<ColumnData<float_data_type>> &cd); CSVParser makeCSVParser(const std::string &filename, const char delim) { return readData(CSVParser{filename, delim}); } CSVParser::CSVParser(const std::string& filename, const char delim) : _delim {delim}, _filename {filename} {} CSVParser readData(CSVParser csvp) { std::ifstream file {csvp._filename}; if(file.fail()) { throw std::runtime_error("Filename does not exist"); } std::string raw_line{}; std::vector<std::string> parsed_row{}; std::vector<std::vector<std::string>> rows{}; while(getline(file, raw_line)){ // Reference for the following code, dealing with delimiters inside quotes: // https://stackoverflow.com/questions/35639083/c-csv-line-with-commas-and-strings-within-double-quotes/35639947 const char *row_ptr = raw_line.c_str(); bool in_quotes {false}; const char *start = row_ptr; for(const char *cur_char = start; *cur_char; ++cur_char) { if(*cur_char == '"') { in_quotes = !in_quotes; } else if (*cur_char == csvp._delim && !in_quotes) { parsed_row.push_back(std::string(start, cur_char - start)); // add word to list start = cur_char + 1; // set start to beginning of next word } } parsed_row.push_back(std::string(start)); // push last word, trailing final delim csvp._rows.push_back(parsed_row); parsed_row.clear(); } return csvp; } // CSVParser::makeSegments() is used to create a vector of ColumnData structs // It is expected that the user calls this function to obtain the vector of ColumnData // structs, then iterates through each vector calling CSVParser::runAnalysisSegment. template <typename T> std::vector<ColumnData<T>> CSVParser::makeSegments( const std::string &target_header, const index_type header_row_index, const index_type first_data_row_index, const index_type num_segments) const { std::vector<ColumnData<T>> results; for(index_type cur_seg {0}; cur_seg < num_segments; ++cur_seg) { ColumnData<T> cur_cd{}; cur_cd.num_segments = num_segments; cur_cd.cur_segment = cur_seg; cur_cd.header = target_header; cur_cd.first_data_row_index = first_data_row_index; cur_cd.header_row_index = header_row_index; results.push_back(cur_cd); } // Work out indices for all segments std::vector<index_type> segment_indices{}; index_type num_rows = _rows.size() - first_data_row_index; for(index_type seg {0}; seg < num_segments; ++seg) { index_type first_index_of_seg = (seg * num_rows)/num_segments + first_data_row_index; segment_indices.push_back(first_index_of_seg); } // Find header_col_index index_type header_col_index; { auto header_col {_rows.at(header_row_index)}; auto header {std::find(header_col.begin(), header_col.end(), target_header)}; if(header == header_col.end()) { throw std::runtime_error("Target header not found"); } else { header_col_index = std::distance(header_col.begin(), header); } } // now set segment_indices and num_rows for all ColumnData objects in results for(auto &cur_cd : results) { cur_cd.segment_indices = segment_indices; cur_cd.num_rows = num_rows; cur_cd.header_col_index = header_col_index; preprocess(cur_cd); } return results; } template std::vector<ColumnData<int_data_type>> CSVParser::makeSegments( const std::string &target_header, const index_type header_row_index, const index_type first_data_row_index, const index_type num_segments) const; template std::vector<ColumnData<float_data_type>> CSVParser::makeSegments( const std::string &target_header, const index_type header_row_index, const index_type first_data_row_index, const index_type num_segments) const; // CSVParser::preprocess() ensures that target_header exists, records the column // target_header is found, and creates segment_indices template <typename T> void CSVParser::preprocess( ColumnData<T> &cd ) const { cd.header_col_index = 0; bool index_found {false}; for(auto word : _rows.at(cd.header_row_index)) { if(word == cd.header) { index_found = true; // indicates cd.header_col_index is set correctly break; } ++cd.header_col_index; } if(!index_found) { throw std::runtime_error("Target header not found"); } index_type end_index; if(cd.cur_segment == cd.num_segments - 1) { // last segment, so end_index = last row index end_index = _rows.size() - 1; } else { end_index = cd.segment_indices.at(cd.cur_segment + 1) - 1; } for(index_type cur_row {cd.segment_indices.at(cd.cur_segment)}; cur_row <= end_index; ++cur_row) { // storing each value into a string stream, because the >> operator // can convert into a variety of numeric types. T val; std::stringstream converter_hack {_rows.at(cur_row).at(cd.header_col_index)}; converter_hack >> val; cd.data_raw.push_back(val); } } template void CSVParser::preprocess( ColumnData<int_data_type> &cd) const; template void CSVParser::preprocess( ColumnData<float_data_type> &cd) const; template <typename T> void CSVParser::runAnalysisSegment( ColumnData<T> &cd ) const { for(const auto &val : cd.data_raw) { cd.data_summary_actual += val; } } template void CSVParser::runAnalysisSegment( ColumnData<int_data_type> &cd) const; template void CSVParser::runAnalysisSegment( ColumnData<float_data_type> &cd) const;