blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0d449d2d6cb108c915ae5de4f0411cf0a9e2d826
|
b22522fe8fc3777b51dba385f0cdb7a7d2911e96
|
/project/faceTrack/faceTrack/train_patch_model.cpp
|
a7ddb7679cd4e5ffdcf28fd1fa21664769387074
|
[] |
no_license
|
txaxx/opencv
|
5320cbe28b04dc9b6b4b0ed17daf2464ae46816d
|
23e2394ab204f7439c62cffbae1f997cca50bf3e
|
refs/heads/master
| 2020-05-16T01:54:16.331452
| 2019-05-09T02:36:42
| 2019-05-09T02:36:42
| 182,612,736
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,306
|
cpp
|
/*****************************************************************************
* Non-Rigid Face Tracking
******************************************************************************
* by Jason Saragih, 5th Dec 2012
* http://jsaragih.org/
******************************************************************************
* Ch6 of the book "Mastering OpenCV with Practical Computer Vision Projects"
* Copyright Packt Publishing 2012.
* http://www.packtpub.com/cool-projects-with-opencv/book
*****************************************************************************/
/*
train_patch_model: learn a patch_model object from training data
Jason Saragih (2012)
*/
#include "ft.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#define fl at<float>
//==============================================================================
float //scaling factor
calc_scale(const Mat &X, //scaling basis vector
const float width) //width of desired shape
{
int n = X.rows/2; float xmin = X.at<float>(0),xmax = X.at<float>(0);
for(int i = 0; i < n; i++){
xmin = min(xmin,X.at<float>(2*i));
xmax = max(xmax,X.at<float>(2*i));
}return width/(xmax-xmin);
}
//==============================================================================
int main()
{
int width = 100;
int psize = 11;
int ssize = 11;
bool mirror = false;
Size wsize(psize+ssize,psize+ssize);
//load data
ft_data data = load_ft<ft_data>("E:\\C++\\opencv\\project\\muct-landmarks\\annotations.yaml");
data.rm_incomplete_samples();
if(data.imnames.size() == 0){
cerr << "Data file does not contain any annotations."<< endl; return 0;
}
//load shape model
shape_model smodel = load_ft<shape_model>("E:\\C++\\opencv\\project\\muct-landmarks\\shape.yaml");
//generate reference shape
smodel.p = Scalar::all(0.0);
smodel.p.fl(0) = calc_scale(smodel.V.col(0),width);
vector<Point2f> r = smodel.calc_shape();
//train patch models
patch_models pmodel;
pmodel.train(data,r,Size(psize,psize),Size(ssize,ssize),mirror);
save_ft<patch_models>("E:\\C++\\opencv\\project\\muct-landmarks\\patch.yaml",pmodel);
return 0;
}
//==============================================================================
|
[
"1192622499@example.com"
] |
1192622499@example.com
|
7b4c996664d6d46e20e507f378fad934a6fdd936
|
c766bece263e5149d0dbab04ea20308bf1191ab8
|
/AdobeInDesignCCProductsSDK.2020/source/public/interfaces/graphics/IOffscreenPortData.h
|
a5b294db1b97428221b6134d175c60484a3de6b8
|
[] |
no_license
|
stevenstong/adobe-tools
|
37a36868619db90984d5303187305c9da1e024f7
|
c74d61d882363a91da4938fd525b97f83084cb2e
|
refs/heads/master
| 2022-04-08T17:31:35.516938
| 2020-03-18T20:57:40
| 2020-03-18T20:57:40
| 248,061,036
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,617
|
h
|
//========================================================================================
//
// $File: //depot/devtech/15.0/plugin/source/public/interfaces/graphics/IOffscreenPortData.h $
//
// Owner: Jack Kirstein
//
// $Author: pmbuilder $
//
// $DateTime: 2019/10/11 10:48:01 $
//
// $Revision: #2 $
//
// $Change: 1061132 $
//
// Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
// with the terms of the Adobe license agreement accompanying it. If you have received
// this file from a source other than Adobe, then your use, modification, or
// distribution of it requires the prior written permission of Adobe.
//
//
// Purpose of interface:
// This is the OffscreenPort specific interface attached to offscreen view ports.
// It is a shell over the AGM API for setting up offscreen ports.
// In order to use an offscreen port, you have to create an IPlatformBitmap and
// then load that into the port via SetTargetBitmap. This is analogous to setting
// the targetwindow on a window view port.
//
//========================================================================================
#pragma once
#ifndef __IOffscreenPortData__
#define __IOffscreenPortData__
#include "IPMUnknown.h"
#include "GraphicsID.h"
#include "HelperInterface.h"
#include "IDVOffscreenPortData.h"
class PMMatrix;
class IPlatformOffscreen;
/** IOffscreenPortData is an interface for creating and updating platform offscreens.
InDesign uses platform offscreen for two reasons: 1) to reduce screen flicker;
2) as a cache to avoid having to instantiate an item on a page in order to ask it to draw.
On Mac OS X, the screen flicker case is handled by the OS so we don't need platform
offscreens for that case. However, the optimizations that reason 2 provides forces us
to continue using offscreens.
This interface has methods to maintain 1 or more offscreens as used by the IOffscreenViewPortCache.
The IOffscreenViewPortCache maintains two IOffscreenPortData ptrs: 1 for the background and 1 for the foreground.
In the case of the layout window, the background offscreen is the contents of the window/document in an
unselected state. The foreground is used as a composite. That is, if an update event
occurs, we do the following:
1. Make sure the background offscreen is up to date. If nobody has called
ILayoutController->InvalidateContent(), then there is nothing to do in this step.
Typically, InvalidateContent() gets called by a document observer after a command has
been processed which changes a page item or the layout in some way.
2. Copy the area to update from the background to the foreground.
3. Draw the selection into the foreground.
4. Draw the foreground to the window.
With the introduction of Mac OS X, the foreground buffer is not needed. Rather, the OS provided
back buffer can serve the purpose of the foreground/composite buffer. Hence, we need two different
update methods in the IOffscreenPortData interface. One (the original UpdateTargetBitmap()) which
allocates a new platform offscreen if the bounds are larger than the current one, and another,
UpdateTargetBitmapIfDiffSize(), which allocates a new platform offscreen if the bounds are different.
History:
Prior to InDesign 3.0, there was 1 background and 1 foreground offscreen shared
among all layout windows. As a result, if you had multiple documents open, switching between
documents/windows caused a performance hit as we updated the contents of the bitmap. In addition,
the size of the offscreen was the size of the largest window. Also, the IOffscreenViewPortCache
interface lived on the Session boss since it was not associated with any window.
For InDesign 3.0, I wanted to provide an offscreen per layout window. Hence, I added
the IOffscreenViewPortCache to kLayoutWidgetBoss. As a result, we no longer need to have the
background offscreen be the size of the largest window. However, since the foreground offscreen
is simply a compositing buffer, I did not want to add a foreground offscreen per window. Therefore,
the IOffscreenViewPortCache::QueryForegroundViewPort() implementation on the layout boss will simply
query for the foreground viewport on the session boss. And, when it is time to update it due to
a window resize, then the original UpdateTargetBitmap() function will be called.
@see IOffscreenViewPortCache (now IDVOffscreenViewPortCache)
*/
typedef IDVOffscreenPortData IOffscreenPortData;
#endif
|
[
"steven.tong@hcl.com"
] |
steven.tong@hcl.com
|
b0efac308b2c16a35a0a38bab7c8398313f37cad
|
97195724f8a99189c9afbcb371eb0816da5f2ec7
|
/imu/Teensy/src/imu_device.cpp
|
9a8da954c4acfbaaf2f461e105f3079490da0b94
|
[
"MIT"
] |
permissive
|
mylightyeah/Yukari
|
a8bc1e98156212df323dc53db2ec9ce16c6103aa
|
da3e599477302c241b438ca44d6711fdd68b6ef8
|
refs/heads/master
| 2021-05-22T16:11:23.320608
| 2017-06-16T13:43:00
| 2017-06-16T13:43:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,437
|
cpp
|
#include "imu_device.h"
#include <I2Cdev.h>
#include <BMP085.h>
#include <MPU9150_9Axis_MotionApps41.h>
#include <TinyGPS++.h>
#include <helper_3dmath.h>
#include <MSP.h>
#include <Scheduler.h>
Scheduler g_scheduler;
MSP g_msp(MSP_SERIAL);
TinyGPSPlus g_gps;
BMP085 g_barometer;
float g_temperature;
float g_pressure;
float g_altitude;
int32_t g_baroLastMicros = 0;
MPU9150 g_imu;
uint16_t g_dmpFIFOPacketSize;
uint16_t g_dmpFIFOBufferSize;
uint8_t g_dmpFIFOBuffer[64];
volatile bool g_mpuInterrupt = false;
// DMP packets use 1g = 4096 (AFS_SEL=2)
const float ACCEL_COEFF = 9.81f / 4096.0f;
Quaternion g_quat;
VectorFloat g_gravity;
VectorInt16 g_accelCalib;
VectorInt16 g_accel;
VectorInt16 g_realAccel;
VectorInt16 g_worldAccel;
VectorFloat g_worldAccelMS2;
uint8_t g_worldAccelMS2Zero[3];
uint8_t g_accelSamples = 0;
VectorFloat g_worldAccelMS2LPFAccum;
VectorFloat g_worldAccelMS2LPF;
uint32_t g_lastIntegrationTimestep = 0;
VectorFloat g_velocity;
VectorFloat g_displacement;
void dmpDataReady()
{
g_mpuInterrupt = true;
}
void taskBlink()
{
static bool blinkState = false;
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
}
#ifdef SERIALPLOT
/*
* Prints debug data as CSV for serialplot.
*
* 1) Acceleration - x
* 2) Acceleration - y
* 3) Acceleration - z
* 4) Linear acceleration - x
* 5) Linear acceleration - y
* 6) Linear acceleration - z
* 7) World acceleration - x
* 8) World acceleration - y
* 9) World acceleration - z
* 10) Velocity - x
* 11) Velocity - y
* 12) Velocity - z
* 13) Displacement - x
* 14) Displacement - y
* 15) Displacement - z
*/
void taskDebugPrintCSV()
{
DEBUG_SERIAL.printf("%d,%d,%d,%d,%d,%d,", g_accel.x, g_accel.y, g_accel.z, g_realAccel.x,
g_realAccel.y, g_realAccel.z);
DEBUG_SERIAL.print(g_worldAccelMS2.x);
DEBUG_SERIAL.print(",");
DEBUG_SERIAL.print(g_worldAccelMS2.y);
DEBUG_SERIAL.print(",");
DEBUG_SERIAL.print(g_worldAccelMS2.z);
DEBUG_SERIAL.print(",");
DEBUG_SERIAL.print(g_velocity.x);
DEBUG_SERIAL.print(",");
DEBUG_SERIAL.print(g_velocity.y);
DEBUG_SERIAL.print(",");
DEBUG_SERIAL.print(g_velocity.z);
DEBUG_SERIAL.print(",");
DEBUG_SERIAL.print(g_displacement.x);
DEBUG_SERIAL.print(",");
DEBUG_SERIAL.print(g_displacement.y);
DEBUG_SERIAL.print(",");
DEBUG_SERIAL.print(g_displacement.z);
DEBUG_SERIAL.println();
}
#endif /* SERIALPLOT */
void taskDMP()
{
if (!g_mpuInterrupt && g_dmpFIFOBufferSize < g_dmpFIFOPacketSize)
return;
// reset interrupt flag and get INT_STATUS byte
g_mpuInterrupt = false;
uint8_t mpuIntStatus = g_imu.getIntStatus();
// get current FIFO count
g_dmpFIFOBufferSize = g_imu.getFIFOCount();
// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || g_dmpFIFOBufferSize == 1024)
{
// reset so we can continue cleanly
g_imu.resetFIFO();
#ifdef DEBUG
DEBUG_SERIAL.printf("FIFO overflow!\n");
#endif
}
// otherwise, check for DMP data ready interrupt (this should happen frequently)
else if (mpuIntStatus & 0x02)
{
// wait for correct available data length, should be a VERY short wait
while (g_dmpFIFOBufferSize < g_dmpFIFOPacketSize)
g_dmpFIFOBufferSize = g_imu.getFIFOCount();
// read a packet from FIFO
g_imu.getFIFOBytes(g_dmpFIFOBuffer, g_dmpFIFOPacketSize);
// track FIFO count here in case there is > 1 packet available
// (this lets us immediately read more without waiting for an interrupt)
g_dmpFIFOBufferSize -= g_dmpFIFOPacketSize;
g_imu.dmpGetQuaternion(&g_quat, g_dmpFIFOBuffer);
g_imu.dmpGetAccel(&g_accel, g_dmpFIFOBuffer);
g_accel.x -= g_accelCalib.x;
g_accel.y -= g_accelCalib.y;
g_accel.z -= g_accelCalib.z;
g_imu.dmpGetGravity(&g_gravity, &g_quat);
g_imu.dmpGetLinearAccel(&g_realAccel, &g_accel, &g_gravity);
g_imu.dmpGetLinearAccelInWorld(&g_worldAccel, &g_realAccel, &g_quat);
g_worldAccelMS2 =
VectorFloat(g_worldAccel.x, g_worldAccel.y, g_worldAccel.z - 5150) * ACCEL_COEFF;
for (uint8_t i = 0; i < 3; i++)
{
if (abs(g_worldAccelMS2[i]) < 0.2f)
g_worldAccelMS2Zero[i]++;
else
g_worldAccelMS2Zero[i] = 0;
if (g_worldAccelMS2Zero[i] >= 10)
g_worldAccelMS2[i] = 0.0f;
}
g_worldAccelMS2LPFAccum += g_worldAccelMS2 / 8.0f;
g_accelSamples++;
// Calculate velocity and displacement
uint32_t now = micros();
if (g_lastIntegrationTimestep != 0 && g_accelSamples == 8)
{
g_worldAccelMS2LPF = g_worldAccelMS2LPFAccum;
g_worldAccelMS2LPFAccum.toZero();
g_accelSamples = 0;
float deltaTime = (float)(now - g_lastIntegrationTimestep) * 1e-6;
g_velocity += g_worldAccelMS2LPF * deltaTime;
g_displacement += g_velocity * deltaTime;
}
taskDebugPrintCSV();
g_lastIntegrationTimestep = now;
}
}
void taskResetIMUIntegration()
{
if (digitalRead(10) == LOW)
{
g_velocity.toZero();
g_displacement.toZero();
#ifdef DEBUG
DEBUG_SERIAL.printf("IMU integration reset\n");
#endif
}
}
void taskBarometer()
{
g_baroLastMicros = micros();
g_barometer.setControl(BMP085_MODE_TEMPERATURE);
while (micros() - g_baroLastMicros < g_barometer.getMeasureDelayMicroseconds())
;
g_temperature = g_barometer.getTemperatureC();
g_barometer.setControl(BMP085_MODE_PRESSURE_3);
while (micros() - g_baroLastMicros < g_barometer.getMeasureDelayMicroseconds())
;
g_pressure = g_barometer.getPressure();
g_altitude = g_barometer.getAltitude(g_pressure);
}
#ifdef DEBUG
void taskPrintData()
{
// Device orientation as quaternion
DEBUG_SERIAL.printf("quat\t");
DEBUG_SERIAL.print(g_quat.w);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.print(g_quat.x);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.print(g_quat.y);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.println(g_quat.z);
// Linear acceleration
DEBUG_SERIAL.printf("a\t%d\t%d\t%d\n", g_accel.x, g_accel.y, g_accel.z);
// Linear acceleration without gravity
DEBUG_SERIAL.printf("aReal\t%d\t%d\t%d\n", g_realAccel.x, g_realAccel.y, g_realAccel.z);
// Linear acceleration without gravity and corrected for orientation
DEBUG_SERIAL.printf("aWorld\t%d\t%d\t%d\n", g_worldAccel.x, g_worldAccel.y, g_worldAccel.z);
// Linear acceleration without gravity and corrected for orientation in ms-2
DEBUG_SERIAL.print("aWorld (ms-2)\t");
DEBUG_SERIAL.print(g_worldAccelMS2.x);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.print(g_worldAccelMS2.y);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.println(g_worldAccelMS2.z);
// Linear acceleration without gravity and corrected for orientation in ms-2 with low pass filter
DEBUG_SERIAL.print("aWorld LPF (ms-2)\t");
DEBUG_SERIAL.print(g_worldAccelMS2LPF.x);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.print(g_worldAccelMS2LPF.y);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.println(g_worldAccelMS2LPF.z);
// Velocity
DEBUG_SERIAL.printf("velocity (ms-1)\t");
DEBUG_SERIAL.print(g_velocity.x);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.print(g_velocity.y);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.println(g_velocity.z);
// Displacement
DEBUG_SERIAL.printf("displacement (m)\t");
DEBUG_SERIAL.print(g_displacement.x);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.print(g_displacement.y);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.println(g_displacement.z);
// BMP180 data
DEBUG_SERIAL.printf("T/P/Alt\t");
DEBUG_SERIAL.print(g_temperature);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.print(g_pressure);
DEBUG_SERIAL.print("\t");
DEBUG_SERIAL.println(g_altitude);
}
#endif /* DEBUG */
void taskFeedGPS()
{
if (GPS_SERIAL.available())
g_gps.encode(GPS_SERIAL.read());
}
#if defined(DEBUG)
void taskDebugPrintGPS()
{
DEBUG_SERIAL.printf("GPS stats\n");
if (g_gps.satellites.isUpdated())
DEBUG_SERIAL.printf("Sats: %ld\n", g_gps.satellites.value());
if (g_gps.location.isUpdated())
{
DEBUG_SERIAL.printf("Lat: %c%d.%ld\n", g_gps.location.rawLat().negative ? '-' : '+',
g_gps.location.rawLat().deg, g_gps.location.rawLat().billionths);
DEBUG_SERIAL.printf("Lng: %c%d.%ld\n", g_gps.location.rawLng().negative ? '-' : '+',
g_gps.location.rawLng().deg, g_gps.location.rawLng().billionths);
DEBUG_SERIAL.printf("Age: %ld\n", g_gps.location.age());
}
if (g_gps.altitude.isUpdated())
DEBUG_SERIAL.printf("Alt: %ldcm\n", g_gps.altitude.value());
if (g_gps.course.isUpdated())
DEBUG_SERIAL.printf("Course: %ld(deg/100)\n", g_gps.course.value());
if (g_gps.speed.isUpdated())
DEBUG_SERIAL.printf("Speed: %ld(knot/100)\n", g_gps.speed.value());
}
#endif /* DEBUG */
void taskMSP()
{
g_msp.loop();
}
void imu_device_init()
{
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
#if defined(DEBUG) || defined(SERIALPLOT)
/* Init debug serial */
DEBUG_SERIAL.begin(DEBUG_BAUD);
while (!DEBUG_SERIAL)
delay(5);
DEBUG_SERIAL.printf("Serial up\n");
#endif /* DEBUG || SERIALPLOT */
/* Init MSP */
MSP_SERIAL.begin(MSP_BAUD);
g_msp.setOnMessage([](MSP::Direction dir, MSP::Command cmd, uint8_t *buff, uint8_t len) {
#ifdef DEBUG
DEBUG_SERIAL.printf("dir=");
DEBUG_SERIAL.println((uint8_t)dir, HEX);
DEBUG_SERIAL.printf("cmd=");
DEBUG_SERIAL.println((uint8_t)cmd, HEX);
DEBUG_SERIAL.printf("len=%d\n", len);
for (uint8_t i = 0; i < len; i++)
{
DEBUG_SERIAL.print(buff[i], HEX);
DEBUG_SERIAL.print(' ');
}
DEBUG_SERIAL.printf("\n");
#endif
switch (cmd)
{
case MSP::Command::Y_ORIENTATION:
{
uint8_t pkt[8];
pkt[0] = g_dmpFIFOBuffer[0];
pkt[1] = g_dmpFIFOBuffer[1];
pkt[2] = g_dmpFIFOBuffer[4];
pkt[3] = g_dmpFIFOBuffer[5];
pkt[4] = g_dmpFIFOBuffer[8];
pkt[5] = g_dmpFIFOBuffer[9];
pkt[6] = g_dmpFIFOBuffer[12];
pkt[7] = g_dmpFIFOBuffer[13];
g_msp.sendPacket(MSP::Command::Y_RAW_IMU, pkt, 8);
break;
}
case MSP::Command::Y_DISPLACEMENT:
{
/* TODO */
break;
}
case MSP::Command::Y_RESET_DISPLACEMENT:
{
/* TODO */
break;
}
default:
break;
}
});
#ifdef DEBUG
DEBUG_SERIAL.printf("MSP init\n");
#endif /* DEBUG */
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
/* Init i2c bus (Arduino) */
Wire.begin();
Wire.setClock(400000); // 400kHz I2C clock
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
/* Init i2c bus (Fast Wire) */
Fastwire::setup(400, true);
#endif /* I2CDEV_IMPLEMENTATION */
#ifdef DEBUG
DEBUG_SERIAL.printf("Wire init\n");
#endif /* DEBUG */
#ifndef DISABLE_GPS
GPS_SERIAL.begin(GPS_BAUD);
#endif /* GPS_SERIAL */
#ifdef DEBUG
DEBUG_SERIAL.printf("GPS init\n");
DEBUG_SERIAL.printf("TinyGPS++ version: %s\n", TinyGPSPlus::libraryVersion());
#endif /* DEBUG */
#ifndef DISABLE_IMU
/* Init IMU */
g_imu.initialize();
#ifdef DEBU2
DEBUG_SERIAL.printf("IMU init: %d\n", g_imu.testConnection());
#endif /* DEBUG */
for (uint8_t i = 0; i < 3; i++)
g_worldAccelMS2Zero[i] = 0;
pinMode(MPU_INTERRUPT_PIN, INPUT);
/* Init DMP */
uint8_t dmpStatus = g_imu.dmpInitialize();
if (dmpStatus == 0)
{
g_imu.setDMPEnabled(true);
attachInterrupt(digitalPinToInterrupt(MPU_INTERRUPT_PIN), dmpDataReady, RISING);
dmpStatus = g_imu.getIntStatus();
g_dmpFIFOPacketSize = g_imu.dmpGetFIFOPacketSize();
}
/* Calibration sample */
int64_t axa = 0;
int64_t aya = 0;
int64_t aza = 0;
const uint16_t numSamples = 5000;
int16_t dummy, ax, ay, az;
#ifdef DEBUG
DEBUG_SERIAL.printf("Accel. calibration start\n");
#endif /* DEBUG */
for (uint16_t i = 0; i < numSamples; i++)
{
g_imu.getMotion6(&ax, &ay, &az, &dummy, &dummy, &dummy);
axa += ax;
aya += ay;
aza += az;
delay(1);
}
g_accelCalib.x = axa / numSamples;
g_accelCalib.y = aya / numSamples;
g_accelCalib.z = aza / numSamples;
#ifdef DEBUG
DEBUG_SERIAL.printf("Accel. calibration done: %d, %d, %d\n", g_accelCalib.x, g_accelCalib.y,
g_accelCalib.z);
#endif /* DEBUG */
#endif /* DISABLE_IMU */
#ifndef DISABLE_BARO
/* Init barometer */
g_barometer.initialize();
#ifdef DEBUG
DEBUG_SERIAL.printf("Barometer init: %d\n", g_barometer.testConnection());
#endif /* DEBUG */
#endif /* DISABLE_BARO */
/* Init scheduler */
g_scheduler.addTask(&taskBlink, Scheduler::HzToUsInterval(5.0f));
g_scheduler.addTask(&taskMSP, 0);
g_scheduler.addTask(&taskResetIMUIntegration, Scheduler::HzToUsInterval(10.0f));
#ifdef SERIALPLOT
/* g_scheduler.addTask(&taskDebugPrintCSV, Scheduler::HzToUsInterval(10.0f)); */
#endif /* SERIALPLOT */
#ifndef DISABLE_GPS
g_scheduler.addTask(&taskFeedGPS, 0);
#endif /* DISABLE_GPS */
#ifndef DISABLE_IMU
if (dmpStatus == 0)
g_scheduler.addTask(&taskDMP, 0);
#endif /* DISABLE_IMU */
#ifndef DISABLE_BARO
g_scheduler.addTask(&taskBarometer, Scheduler::HzToUsInterval(10.0f));
#endif /* DISABLE_BARO */
#ifdef DEBUG
g_scheduler.addTask(&taskPrintData, Scheduler::HzToUsInterval(10.0f));
#ifndef DISABLE_GPS
g_scheduler.addTask(&taskDebugPrintGPS, Scheduler::HzToUsInterval(1.0f));
#endif /* DISABLE_GPS */
g_scheduler.print(DEBUG_SERIAL);
#endif /* DEBUG */
digitalWrite(LED_PIN, LOW);
#ifdef DEBUG
DEBUG_SERIAL.printf("Ready\n");
#endif /* DEBUG */
}
void imu_device_loop()
{
g_scheduler.loop();
}
|
[
"dan@dan-nixon.com"
] |
dan@dan-nixon.com
|
118c0ed9d54842ff8f8213d557903c8a0a33854c
|
9ad40d7fff54f5e4f36ae974e33712a9beb7378e
|
/codeforces/2.cpp
|
9631d9797331d284c1a3fd5a2c852d013531bc13
|
[] |
no_license
|
vikram-shaw/cpp
|
7fcac406b003dd717abe43fc5f15ea253b486b1d
|
8d4367dedef4e48aed649c8174cee74d38be09ea
|
refs/heads/master
| 2023-01-31T19:13:04.363704
| 2020-12-20T05:50:24
| 2020-12-20T05:50:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 885
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
bool com(pair<int,int>& p1, pair<int,int>& p2)
{
if(p1.first >= p2.first && p1.second >=p2.second)
return true;
return false;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
vector<pair<int,int>> path(n);
for(int i=0;i<n;i++)
cin>>path[i].first>>path[i].second;
sort(path.begin(),path.end());
pair<int,int> s{0,0};
bool f = false;
int i;
for(i=1;i<n;i++)
{
if(path[i].first < path[i-1].first || path[i].second < path[i-1].second)
break;
}
if(i==n)
{
cout<<"YES\n";
for(int i=0;i<n;i++)
{
while(s.first < path[i].first || s.second < path[i].second)
{
if(s.first < path[i].first){
s.first++;
cout<<"R";
}
else if(s.second < path[i].second){
s.second++;
cout<<"U";
}
}
}
cout<<"\n";
}
else
cout<<"NO\n";
}
}
|
[
"vikram.shaw.3382@gmail.com"
] |
vikram.shaw.3382@gmail.com
|
6fe60d39bf4547f42863d16dfbf7ca7049749d7b
|
ea2ef79d13c8c8c70f96ba6683bf0f321e9942c1
|
/include/graphics/Scene.h
|
c81617ee928d3fac81fbae6a558df2d9eb7d98d1
|
[
"MIT"
] |
permissive
|
stnma7e/scim
|
32145a3d51aadb2013f2ab452fb1c83af563ca13
|
a82f0e97018a4a2abf0a225f75ebc7e8ef6f1e0d
|
refs/heads/master
| 2021-01-10T20:17:34.222501
| 2014-02-01T19:08:54
| 2014-02-01T19:08:54
| 7,210,907
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 954
|
h
|
#ifndef SCENE_H_
#define SCENE_H_
#include "IMesh.h"
#include <glm/glm.hpp>
#include <vector>
#include <stdio.h>
#include <iostream>
namespace scim
{
struct SceneNode
{
U32 index;
glm::mat4* wmat;
glm::mat4* lmat;
U32 parentNode;
IMesh* mesh;
};
class Scene
{
std::vector<glm::mat4> m_wmat; // world transform matrix list
std::vector<glm::mat4> m_lmat; // local transform matrix list
std::vector<const IMesh*> m_meshes;
std::vector<U32> m_parents;
public:
enum SceneConstant
{
ROOT_NODE = 0
};
static void PrintMatrix(const glm::mat4& matToPrint)
{
for (int j = 0; j < 4; ++j)
{
printf("row %d: ", j);
for (int k = 0; k < 4; ++k)
{
std::cout << matToPrint[k][j] << ", "; // row major order
}
printf("\n");
}
printf("\n");
}
Scene();
void UpdateNodes();
void RenderNodes();
SceneNode CreateNode(U32 parentNode, IMesh* mesh);
const SceneNode GetNode(U32 nodeIndex);
};
}
#endif
|
[
"svdelmerico@gmail.com"
] |
svdelmerico@gmail.com
|
93f1486bead20e1ad41423cd758008134fe59ae8
|
fee42f7dd84c0799a2dea25d08e52f99b2b88b22
|
/ContestUri2018/poesia.cc
|
a8212fe1210194705491efaa0414d44d19fbed83
|
[] |
no_license
|
eassisv/online-judge
|
0d997bb592f2af772454fe1d2125518cc841bfa2
|
33c5bcf818e3635e71c7fafafb82753bff34601b
|
refs/heads/master
| 2020-03-27T03:12:22.721276
| 2018-11-29T01:22:15
| 2018-11-29T01:22:15
| 145,845,940
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 815
|
cc
|
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
const int MAX = 2e3+1;
vector<int> divs, ns, rs(MAX);
int main(void) {
int N, ans;
cin >> N;
for(int i = 2, j = N, d = 0; j > 1;){
if(j % i) { d = 0; ++i; continue; }
if(!d) { d = 1; divs.pb(i); }
else { int x = i * divs.back(); divs.pb(x); }
j /= i;
}
sort(divs.begin(), divs.end());
for(int i = 0; i < N; i++) {
int x;
scanf("%d", &x);
ns.pb(x);
}
ans = -1;
for(auto i : divs) {
int x = N / i;
for(auto j : ns){
rs[j % i] += 1;
}
ans = i;
for(int j = 0; j < i; j++) {
if(rs[j] != x) ans = -1;
rs[j] = 0;
}
if(ans != -1) break;
}
cout << ans << '\n';
}
|
[
"eassis.vieira@gmail.com"
] |
eassis.vieira@gmail.com
|
88a2761c16aa3a2578fe59343015078e6cb66dda
|
24169ed433d6fb46ee6c00d49a31ee834f517dce
|
/GFlowSim/src/dataobjects/graphobjects/kineticenergydata.cpp
|
ddd79fb3082496106556e8f29df5c5d8299fec32
|
[] |
no_license
|
nrupprecht/GFlow
|
0ae566e33305c31c1fead7834a0b89f611abb715
|
445bf3cbdbcdc68aa51b5737f60d96634009a731
|
refs/heads/master
| 2021-11-22T22:07:31.721612
| 2020-04-22T18:51:21
| 2020-04-22T18:51:21
| 60,136,842
| 2
| 2
| null | 2020-02-10T23:10:33
| 2016-06-01T01:49:26
|
C++
|
UTF-8
|
C++
| false
| false
| 1,508
|
cpp
|
#include "kineticenergydata.hpp"
namespace GFlowSimulation {
// Constructor
KineticEnergyData::KineticEnergyData(GFlow *gflow, bool ave) : GraphObject(gflow, "KE", "time", "kinetic energy"), useAve(ave) {};
void KineticEnergyData::post_step() {
// Only record if enough time has gone by
if (!DataObject::_check()) return;
// Get data.
RealType ke = calculate_kinetic(simData, false);
// Store data. These functions work correctly with multiprocessor runs.
if (useAve) gatherAverageData(gflow->getElapsedTime(), ke, simData->size_owned());
else gatherData(gflow->getElapsedTime(), ke);
}
RealType KineticEnergyData::calculate_kinetic(shared_ptr<SimData> simData, bool average) {
RealType ke = 0;
auto v = simData->V();
auto im = simData->Im();
int sim_dimensions = simData->getSimDimensions();
int count = 0;
for (int n=0; n<simData->size_owned(); ++n) {
RealType vsqr = sqr(v(n), sim_dimensions);
if (im[n]>0 && !isnan(vsqr)) {
RealType m = 1./im(n);
ke += m*vsqr;
++count;
}
}
ke *= 0.5;
// Return the total kinetic energy
return average ? ke/static_cast<RealType>(count) : ke;
}
RealType KineticEnergyData::calculate_temperature(shared_ptr<SimData> simData) {
// Get the kinetic energy.
RealType ke = KineticEnergyData::calculate_kinetic(simData, true);
// Calculate temperature.
return 2./simData->getSimDimensions() * ke / simData->getGFlow()->getKB();
}
}
|
[
"nathaniel.rupprecht@gmail.com"
] |
nathaniel.rupprecht@gmail.com
|
ab6cf205c80f1278abb9878f5413de2cb172a5a2
|
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
|
/boost/mpl/transform.hpp
|
d1f94e6638ff71a7c071a7fdff5b74d040c2cd41
|
[] |
no_license
|
huahang/thirdparty
|
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
|
07a5d64111a55dda631b7e8d34878ca5e5de05ab
|
refs/heads/master
| 2021-01-15T14:29:26.968553
| 2014-02-06T07:35:22
| 2014-02-06T07:35:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 59
|
hpp
|
#include "thirdparty/boost_1_55_0/boost/mpl/transform.hpp"
|
[
"liuhuahang@xiaomi.com"
] |
liuhuahang@xiaomi.com
|
09dfc8eff23ce47bf507215f1537179e074e6110
|
40efd1998af596082f5a006f0e2c5bc12d8e7ebc
|
/CppSQLite3U.cpp
|
2e9a0595c05677fa3105c6fb7013be9b36e7d9e2
|
[
"MIT"
] |
permissive
|
cmf41013/CppSQLite3U
|
968a4386081b2c58cbac422ec80cc88d20444338
|
18d86b8c5619dcb71eb8dcebf62273a65547a2db
|
refs/heads/master
| 2021-05-28T05:30:05.364827
| 2014-11-20T09:45:43
| 2014-11-20T09:45:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20,099
|
cpp
|
////////////////////////////////////////////////////////////////////////////////
// CppSQLite3U is a C++ unicode wrapper around the SQLite3 embedded database library.
//
// Copyright (c) 2006 Tyushkov Nikolay. All Rights Reserved. http://softvoile.com
//
//
// Based on beautiful wrapper written by Rob Groves
// (https://secure.codeproject.com/database/CppSQLite.asp).
// Very good wrapper, but without unicode support unfortunately.
// So, I have reconstructed it for unicode.
//
// CppSQLite3 wrapper:
// Copyright (c) 2004 Rob Groves. All Rights Reserved. rob.groves@btinternet.com
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement, is hereby granted, provided that the above copyright notice,
// this paragraph and the following two paragraphs appear in all copies,
// modifications, and distributions.
//
// IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
// PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
// ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// If you want to get some documentation look at
// https://secure.codeproject.com/database/CppSQLite.asp
// Note, not all features from CppSQLite3 were implemented in CppSQLite3U
//
// V1.0 11/06/2006 - Initial Public Version
//
// Noteses :
// I have tested this wrapper only in unicode version, so I have no idea
// about its work in ANSI configuration, I think it doesn't work without modification;)
//
// Home page : http://softvoile.com/development/CppSQLite3U/
// Please send all bug report and comment to mail2@softvoile.com
//
//
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "CppSQLite3U.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CppSQLite3Exception
CppSQLite3Exception::CppSQLite3Exception(const int nErrCode,
LPTSTR szErrMess,
bool bDeleteMsg/*=true*/) :
mnErrCode(nErrCode)
{
int bufSize = szErrMess ? _tcslen(szErrMess) + 50 : 50;
mpszErrMess = new TCHAR[ bufSize ];
_stprintf_s(mpszErrMess, bufSize, _T("%s[%d]: %s"),
errorCodeAsString(nErrCode),
nErrCode,
szErrMess ? szErrMess : _T(""));
// _stprintf(mpszErrMess, _T("%s[%d]: %s"),
// errorCodeAsString(nErrCode),
// nErrCode,
// szErrMess ? szErrMess : _T(""));
if (bDeleteMsg && szErrMess) {
_sqlite3_free((char*)szErrMess);
}
}
CppSQLite3Exception::CppSQLite3Exception(const CppSQLite3Exception& e) :
mnErrCode(e.mnErrCode)
{
mpszErrMess = 0;
if (e.mpszErrMess) {
int bufSize = _tcslen(e.mpszErrMess) + 10;
mpszErrMess = new TCHAR[bufSize];
_stprintf_s(mpszErrMess, bufSize, _T("%s"), e.mpszErrMess);
// _stprintf(mpszErrMess, _T("%s"), e.mpszErrMess);
}
}
LPCTSTR CppSQLite3Exception::errorCodeAsString(int nErrCode)
{
switch (nErrCode) {
case SQLITE_OK: return _T("SQLITE_OK");
case SQLITE_ERROR: return _T("SQLITE_ERROR");
case SQLITE_INTERNAL: return _T("SQLITE_INTERNAL");
case SQLITE_PERM: return _T("SQLITE_PERM");
case SQLITE_ABORT: return _T("SQLITE_ABORT");
case SQLITE_BUSY: return _T("SQLITE_BUSY");
case SQLITE_LOCKED: return _T("SQLITE_LOCKED");
case SQLITE_NOMEM: return _T("SQLITE_NOMEM");
case SQLITE_READONLY: return _T("SQLITE_READONLY");
case SQLITE_INTERRUPT: return _T("SQLITE_INTERRUPT");
case SQLITE_IOERR: return _T("SQLITE_IOERR");
case SQLITE_CORRUPT: return _T("SQLITE_CORRUPT");
case SQLITE_NOTFOUND: return _T("SQLITE_NOTFOUND");
case SQLITE_FULL: return _T("SQLITE_FULL");
case SQLITE_CANTOPEN: return _T("SQLITE_CANTOPEN");
case SQLITE_PROTOCOL: return _T("SQLITE_PROTOCOL");
case SQLITE_EMPTY: return _T("SQLITE_EMPTY");
case SQLITE_SCHEMA: return _T("SQLITE_SCHEMA");
case SQLITE_TOOBIG: return _T("SQLITE_TOOBIG");
case SQLITE_CONSTRAINT: return _T("SQLITE_CONSTRAINT");
case SQLITE_MISMATCH: return _T("SQLITE_MISMATCH");
case SQLITE_MISUSE: return _T("SQLITE_MISUSE");
case SQLITE_NOLFS: return _T("SQLITE_NOLFS");
case SQLITE_AUTH: return _T("SQLITE_AUTH");
case SQLITE_FORMAT: return _T("SQLITE_FORMAT");
case SQLITE_RANGE: return _T("SQLITE_RANGE");
case SQLITE_ROW: return _T("SQLITE_ROW");
case SQLITE_DONE: return _T("SQLITE_DONE");
case CPPSQLITE_ERROR: return _T("CPPSQLITE_ERROR");
default: return _T("UNKNOWN_ERROR");
}
}
CppSQLite3Exception::~CppSQLite3Exception()
{
if (mpszErrMess) {
delete [] mpszErrMess;
mpszErrMess = 0;
}
}
/////////////////////////////////////////////////////////////////////////////
// CppSQLite3DB
CppSQLite3DB::CppSQLite3DB()
{
mpDB = 0;
mnBusyTimeoutMs = 60000; // 60 seconds
}
CppSQLite3DB::CppSQLite3DB(const CppSQLite3DB& db)
{
mpDB = db.mpDB;
mnBusyTimeoutMs = 60000; // 60 seconds
}
CppSQLite3DB::~CppSQLite3DB()
{
close();
}
////////////////////////////////////////////////////////////////////////////////
CppSQLite3DB& CppSQLite3DB::operator=(const CppSQLite3DB& db)
{
mpDB = db.mpDB;
mnBusyTimeoutMs = 60000; // 60 seconds
return *this;
}
void CppSQLite3DB::open(LPCTSTR szFile)
{
int nRet;
#if defined(_UNICODE) || defined(UNICODE)
nRet = sqlite3_open16(szFile, &mpDB); // not tested under window 98
#else // For Ansi Version
//*************- Added by Begemot szFile must be in unicode- 23/03/06 11:04 - ****
OSVERSIONINFOEX osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx ((OSVERSIONINFO *) &osvi);
if ( osvi.dwMajorVersion == 5)
{
WCHAR pMultiByteStr[MAX_PATH+1];
MultiByteToWideChar( CP_ACP, 0, szFile,
_tcslen(szFile)+1, pMultiByteStr,
sizeof(pMultiByteStr)/sizeof(pMultiByteStr[0]) );
nRet = sqlite3_open16(pMultiByteStr, &mpDB);
}
else
nRet = sqlite3_open(szFile,&mpDB);
#endif
//*************************
if (nRet != SQLITE_OK) {
LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
setBusyTimeout(mnBusyTimeoutMs);
}
void CppSQLite3DB::close()
{
if (mpDB) {
int nRet = _sqlite3_close(mpDB);
if (nRet != SQLITE_OK) {
LPCTSTR szError = (LPCTSTR)_sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
mpDB = 0;
}
}
CppSQLite3Statement CppSQLite3DB::compileStatement(LPCTSTR szSQL)
{
checkDB();
sqlite3_stmt* pVM = compile(szSQL);
return CppSQLite3Statement(mpDB, pVM);
}
bool CppSQLite3DB::tableExists(LPCTSTR szTable)
{
TCHAR szSQL[128];
_stprintf_s(szSQL, 127, _T("select count(*) from sqlite_master where type='table' and name='%s'"), szTable);
int nRet = execScalar(szSQL);
return (nRet > 0);
}
int CppSQLite3DB::execDML(LPCTSTR szSQL)
{
int nRet;
sqlite3_stmt* pVM;
checkDB();
do {
pVM = compile(szSQL);
nRet = _sqlite3_step(pVM);
if (nRet == SQLITE_ERROR) {
LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
nRet = _sqlite3_finalize(pVM);
} while (nRet == SQLITE_SCHEMA);
}
CppSQLite3Query CppSQLite3DB::execQuery(LPCTSTR szSQL)
{
checkDB();
int nRet;
sqlite3_stmt* pVM;
do {
pVM = compile(szSQL);
nRet = _sqlite3_step(pVM);
if (nRet == SQLITE_DONE) { // no rows
return CppSQLite3Query(mpDB, pVM, true/*eof*/);
} else if (nRet == SQLITE_ROW) { // at least 1 row
return CppSQLite3Query(mpDB, pVM, false/*eof*/);
}
nRet = _sqlite3_finalize(pVM);
} while (nRet == SQLITE_SCHEMA); // Edit By Begemot 08/16/06 12:44:35 - read SQLite FAQ
LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
int CppSQLite3DB::execScalar(LPCTSTR szSQL)
{
CppSQLite3Query q = execQuery(szSQL);
if (q.eof() || q.numFields() < 1 || q.fieldValue(0) == NULL)
throw CppSQLite3Exception(CPPSQLITE_ERROR, _T("Invalid scalar query"), DONT_DELETE_MSG);
return _tstoi(q.fieldValue(0));
}
// Added By Begemot, exact as execScalar but return CString 08/06/06 16:30:37
CString CppSQLite3DB::execScalarStr(LPCTSTR szSQL)
{
CppSQLite3Query q = execQuery(szSQL);
if (q.eof() || q.numFields() < 1)
throw CppSQLite3Exception(CPPSQLITE_ERROR, _T("Invalid scalar query"), DONT_DELETE_MSG);
return (CString)q.getStringField(0);
}
sqlite_int64 CppSQLite3DB::lastRowId()
{
return sqlite3_last_insert_rowid(mpDB);
}
void CppSQLite3DB::setBusyTimeout(int nMillisecs)
{
mnBusyTimeoutMs = nMillisecs;
sqlite3_busy_timeout(mpDB, mnBusyTimeoutMs);
}
void CppSQLite3DB::checkDB()
{
if (!mpDB)
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Database not open"), DONT_DELETE_MSG);
}
sqlite3_stmt* CppSQLite3DB::compile(LPCTSTR szSQL)
{
checkDB();
sqlite3_stmt* pVM;
int nRet = _sqlite3_prepare(mpDB, szSQL, -1, &pVM, NULL);
if (nRet != SQLITE_OK) {
pVM = NULL;
LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
return pVM;
}
//////////////////////// CppSQLite3Statement ///////////////////////////////////////////
CppSQLite3Statement::CppSQLite3Statement()
{
mpDB = 0;
mpVM = 0;
}
CppSQLite3Statement::CppSQLite3Statement(const CppSQLite3Statement& rStatement)
{
mpDB = rStatement.mpDB;
mpVM = rStatement.mpVM;
// Only one object can own VM
const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
}
CppSQLite3Statement::CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM)
{
mpDB = pDB;
mpVM = pVM;
}
CppSQLite3Statement::~CppSQLite3Statement()
{
try {
finalize();
}
catch (...) {}
}
CppSQLite3Statement& CppSQLite3Statement::operator=(const CppSQLite3Statement& rStatement)
{
mpDB = rStatement.mpDB;
mpVM = rStatement.mpVM;
// Only one object can own VM
const_cast<CppSQLite3Statement&>(rStatement).mpVM = 0;
return *this;
}
int CppSQLite3Statement::execDML()
{
checkDB();
checkVM();
int nRet = sqlite3_step(mpVM);
if (nRet == SQLITE_DONE) {
int nRowsChanged = sqlite3_changes(mpDB);
nRet = sqlite3_reset(mpVM);
if (nRet != SQLITE_OK) {
LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
return nRowsChanged;
} else {
nRet = sqlite3_reset(mpVM);
LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
}
void CppSQLite3Statement::bind(int nParam, LPCTSTR szValue)
{
checkVM();
int nRes = _sqlite3_bind_text(mpVM, nParam, szValue, -1, SQLITE_TRANSIENT);
if (nRes != SQLITE_OK)
throw CppSQLite3Exception(nRes,_T("Error binding string param"), DONT_DELETE_MSG);
}
void CppSQLite3Statement::bind(int nParam, const int nValue)
{
checkVM();
int nRes = sqlite3_bind_int(mpVM, nParam, nValue);
if (nRes != SQLITE_OK)
throw CppSQLite3Exception(nRes,_T("Error binding int param"), DONT_DELETE_MSG);
}
void CppSQLite3Statement::bind(int nParam, const double dValue)
{
checkVM();
int nRes = sqlite3_bind_double(mpVM, nParam, dValue);
if (nRes != SQLITE_OK)
throw CppSQLite3Exception(nRes, _T("Error binding double param"), DONT_DELETE_MSG);
}
void CppSQLite3Statement::bind(int nParam, const unsigned char* blobValue, int nLen)
{
checkVM();
int nRes = sqlite3_bind_blob(mpVM, nParam, (const void*)blobValue, nLen, SQLITE_TRANSIENT);
if (nRes != SQLITE_OK)
throw CppSQLite3Exception(nRes,_T("Error binding blob param"), DONT_DELETE_MSG);
}
void CppSQLite3Statement::bindNull(int nParam)
{
checkVM();
int nRes = sqlite3_bind_null(mpVM, nParam);
if (nRes != SQLITE_OK)
throw CppSQLite3Exception(nRes,_T("Error binding NULL param"), DONT_DELETE_MSG);
}
int CppSQLite3Statement::bindParameterIndex(LPCTSTR szParam)
{
checkVM();
CStringA s(szParam);
int nParam = _sqlite3_bind_parameter_index(mpVM, s);
int nn = sqlite3_bind_parameter_count(mpVM);
const char* sz1 = sqlite3_bind_parameter_name(mpVM, 1);
const char* sz2 = sqlite3_bind_parameter_name(mpVM, 2);
if (!nParam) {
TCHAR buf[128];
_stprintf_s(buf, 128, _T("Parameter '%s' is not valid for this statement"), szParam);
throw CppSQLite3Exception(CPPSQLITE_ERROR, buf, DONT_DELETE_MSG);
}
return nParam;
}
void CppSQLite3Statement::bind(LPCTSTR szParam, LPCTSTR szValue)
{
int nParam = bindParameterIndex(szParam);
bind(nParam, szValue);
}
void CppSQLite3Statement::bind(LPCTSTR szParam, int const nValue)
{
int nParam = bindParameterIndex(szParam);
bind(nParam, nValue);
}
void CppSQLite3Statement::bind(LPCTSTR szParam, double const dwValue)
{
int nParam = bindParameterIndex(szParam);
bind(nParam, dwValue);
}
void CppSQLite3Statement::bind(LPCTSTR szParam, unsigned char const* blobValue, int nLen)
{
int nParam = bindParameterIndex(szParam);
bind(nParam, blobValue, nLen);
}
void CppSQLite3Statement::bindNull(LPCTSTR szParam)
{
int nParam = bindParameterIndex(szParam);
bindNull(nParam);
}
void CppSQLite3Statement::reset()
{
if (mpVM) {
int nRet = sqlite3_reset(mpVM);
if (nRet != SQLITE_OK) {
LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
}
}
void CppSQLite3Statement::finalize()
{
if (mpVM) {
int nRet = sqlite3_finalize(mpVM);
mpVM = 0;
if (nRet != SQLITE_OK) {
LPCTSTR szError = (LPCTSTR) _sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
}
}
void CppSQLite3Statement::checkDB()
{
if (mpDB == 0)
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Database not open"), DONT_DELETE_MSG);
}
void CppSQLite3Statement::checkVM()
{
if (mpVM == 0)
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Null Virtual Machine pointer"), DONT_DELETE_MSG);
}
///////////////////// CppSQLite3Query //////////////////////////////////////////////////
CppSQLite3Query::CppSQLite3Query()
{
mpVM = 0;
mbEof = true;
mnCols = 0;
mbOwnVM = false;
}
CppSQLite3Query::CppSQLite3Query(const CppSQLite3Query& rQuery)
{
mpVM = rQuery.mpVM;
// Only one object can own the VM
const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
mbEof = rQuery.mbEof;
mnCols = rQuery.mnCols;
mbOwnVM = rQuery.mbOwnVM;
}
CppSQLite3Query::CppSQLite3Query(sqlite3* pDB, sqlite3_stmt* pVM,
bool bEof, bool bOwnVM/*=true*/)
{
mpDB = pDB;
mpVM = pVM;
mbEof = bEof;
mnCols = _sqlite3_column_count(mpVM);
mbOwnVM = bOwnVM;
}
CppSQLite3Query::~CppSQLite3Query()
{
try {
finalize();
}
catch (...) {}
}
CppSQLite3Query& CppSQLite3Query::operator=(const CppSQLite3Query& rQuery)
{
try {
finalize();
}
catch (...) {}
mpVM = rQuery.mpVM;
// Only one object can own the VM
const_cast<CppSQLite3Query&>(rQuery).mpVM = 0;
mbEof = rQuery.mbEof;
mnCols = rQuery.mnCols;
mbOwnVM = rQuery.mbOwnVM;
return *this;
}
int CppSQLite3Query::numFields()
{
checkVM();
return mnCols;
}
LPCTSTR CppSQLite3Query::fieldValue(int nField)
{
checkVM();
if (nField < 0 || nField > mnCols - 1)
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG);
return (LPCTSTR)_sqlite3_column_text(mpVM, nField);
}
LPCTSTR CppSQLite3Query::fieldValue(LPCTSTR szField)
{
int nField = fieldIndex(szField);
return (LPCTSTR)_sqlite3_column_text(mpVM, nField);
}
int CppSQLite3Query::getIntField(int nField, int nNullValue/*=0*/)
{
if (fieldDataType(nField) == SQLITE_NULL) {
return nNullValue;
} else {
return _sqlite3_column_int(mpVM, nField);
}
}
int CppSQLite3Query::getIntField(LPCTSTR szField, int nNullValue/*=0*/)
{
int nField = fieldIndex(szField);
return getIntField(nField, nNullValue);
}
double CppSQLite3Query::getFloatField(int nField, double fNullValue/*=0.0*/)
{
if (fieldDataType(nField) == SQLITE_NULL) {
return fNullValue;
} else {
return _sqlite3_column_double(mpVM, nField);
}
}
double CppSQLite3Query::getFloatField(LPCTSTR szField, double fNullValue/*=0.0*/)
{
int nField = fieldIndex(szField);
return getFloatField(nField, fNullValue);
}
LPCTSTR CppSQLite3Query::getStringField(int nField, LPCTSTR szNullValue/*=""*/)
{
if (fieldDataType(nField) == SQLITE_NULL) {
return szNullValue;
} else {
return (LPCTSTR)_sqlite3_column_text(mpVM, nField);
}
}
LPCTSTR CppSQLite3Query::getStringField(LPCTSTR szField, LPCTSTR szNullValue/*=""*/)
{
int nField = fieldIndex(szField);
return getStringField(nField, szNullValue);
}
const unsigned char* CppSQLite3Query::getBlobField(int nField, int& nLen)
{
checkVM();
if (nField < 0 || nField > mnCols - 1)
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG);
nLen = _sqlite3_column_bytes(mpVM, nField);
return (const unsigned char*)sqlite3_column_blob(mpVM, nField);
}
const unsigned char* CppSQLite3Query::getBlobField(LPCTSTR szField, int& nLen)
{
int nField = fieldIndex(szField);
return getBlobField(nField, nLen);
}
bool CppSQLite3Query::fieldIsNull(int nField)
{
return (fieldDataType(nField) == SQLITE_NULL);
}
bool CppSQLite3Query::fieldIsNull(LPCTSTR szField)
{
int nField = fieldIndex(szField);
return (fieldDataType(nField) == SQLITE_NULL);
}
int CppSQLite3Query::fieldIndex(LPCTSTR szField)
{
checkVM();
if (szField) {
for (int nField = 0; nField < mnCols; nField++) {
LPCTSTR szTemp = (LPCTSTR)_sqlite3_column_name(mpVM, nField);
if (_tcscmp(szField, szTemp) == 0) {
return nField;
}
}
}
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field name requested"), DONT_DELETE_MSG);
}
LPCTSTR CppSQLite3Query::fieldName(int nCol)
{
checkVM();
if (nCol < 0 || nCol > mnCols - 1) {
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG);
}
return (LPCTSTR)_sqlite3_column_name(mpVM, nCol);
}
LPCTSTR CppSQLite3Query::fieldDeclType(int nCol)
{
checkVM();
if (nCol < 0 || nCol > mnCols - 1) {
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG);
}
return (LPCTSTR)_sqlite3_column_decltype(mpVM, nCol);
}
int CppSQLite3Query::fieldDataType(int nCol)
{
checkVM();
if (nCol < 0 || nCol > mnCols - 1) {
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Invalid field index requested"), DONT_DELETE_MSG);
}
return _sqlite3_column_type(mpVM, nCol);
}
bool CppSQLite3Query::eof()
{
checkVM();
return mbEof;
}
void CppSQLite3Query::nextRow()
{
checkVM();
int nRet = _sqlite3_step(mpVM);
if (nRet == SQLITE_DONE) {
// no rows
mbEof = true;
} else if (nRet == SQLITE_ROW) {
// more rows, nothing to do
} else {
nRet = _sqlite3_finalize(mpVM);
mpVM = 0;
LPCTSTR szError = (LPCTSTR)_sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
}
void CppSQLite3Query::finalize()
{
if (mpVM && mbOwnVM) {
int nRet = _sqlite3_finalize(mpVM);
mpVM = 0;
if (nRet != SQLITE_OK) {
LPCTSTR szError = (LPCTSTR)_sqlite3_errmsg(mpDB);
throw CppSQLite3Exception(nRet, (LPTSTR)szError, DONT_DELETE_MSG);
}
}
}
void CppSQLite3Query::checkVM()
{
if (mpVM == 0) {
throw CppSQLite3Exception(CPPSQLITE_ERROR,_T("Null Virtual Machine pointer"), DONT_DELETE_MSG);
}
}
////////////////////////////////////////////////////////////////////////////////
//**************************
//*************- Added By Begemot - 28/02/06 20:25 - ****
CString DoubleQuotes(CString in)
{
in.Replace(_T("\'"),_T("\'\'"));
return in;
}
|
[
"slava.konashkov@gmail.com"
] |
slava.konashkov@gmail.com
|
aa686bb8bc1b77a1d341f72ab1b544dd58b0547c
|
60798997f9ff3a60b8787386dbed1ad06c1c9ccc
|
/DesignPatterns/Structural/Composite/floppydisk.cpp
|
192d2092f00675c638331e84d52d77c7be50f25d
|
[] |
no_license
|
e5MaxSpace/DesignPatterns
|
be7e478c0fca1626c764287af17fd4457c99a975
|
c44a2b6781a571937f85634b57f6feb60a744f89
|
refs/heads/master
| 2016-09-06T18:08:11.377009
| 2013-09-16T12:16:41
| 2013-09-16T12:16:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 320
|
cpp
|
#include "floppydisk.h"
FloppyDisk::FloppyDisk(const std::string &name)
: Equipment(name)
{
}
FloppyDisk::~FloppyDisk()
{
}
int FloppyDisk::Power() const
{
return 180;
}
Currency FloppyDisk::NetPrice() const
{
return 500.0;
}
Currency FloppyDisk::DiscountPrice() const
{
return NetPrice() * 0.85;
}
|
[
"e5Max@qq.com"
] |
e5Max@qq.com
|
3d990c1341cce745c8cd816c66e6e52a1a6126af
|
e9ed8f198134984a9342e50d96a454a0ed1e094a
|
/AR-VR/tanya007_Tanya_2024ec1197_2/gettingStarted/primesinrange.cpp
|
5973ff067ac49bf3d32c2080e55fb573c937d87b
|
[] |
no_license
|
divyaagarwal24/coderspree
|
20978b6dabefd84cac1343fffa79741bd6372046
|
7aafdab534bbab8dd1073007d83517470aae3492
|
refs/heads/main
| 2023-08-26T12:15:52.236087
| 2021-11-10T11:48:55
| 2021-11-10T11:48:55
| 412,049,822
| 0
| 1
| null | 2021-09-30T12:09:47
| 2021-09-30T12:09:47
| null |
UTF-8
|
C++
| false
| false
| 313
|
cpp
|
#include<iostream>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
for(int num=a;num<=b;num++){
int i;
for(i=2;i<num;i++){
if(num%i==0){
break;
}
}
if(i==num){
cout<<num<<endl;
}
}
return 0;
}
|
[
"30565750+tushar5526@users.noreply.github.com"
] |
30565750+tushar5526@users.noreply.github.com
|
1668062d6f35ef93535d12b81c7d09dce335a2ce
|
80bee850d1197772d61e05d8febc014e9980d7c0
|
/Addons/ExileReborn-Reborn_Zombies/@ExileServer/addons/Enigma_Exile_Custom/config.cpp
|
b599d7884fd7f9af5d528ef2cf49ffaf7d43298c
|
[
"MIT"
] |
permissive
|
x-cessive/Exile
|
0443bb201bda31201fadc9c0ac80823fb2d7a25d
|
c5d1f679879a183549e1c87d078d462cbba32c25
|
refs/heads/master
| 2021-11-29T08:40:00.286597
| 2021-11-14T17:36:51
| 2021-11-14T17:36:51
| 82,304,207
| 10
| 8
| null | 2017-04-11T14:44:21
| 2017-02-17T14:20:22
|
SQF
|
UTF-8
|
C++
| false
| false
| 359
|
cpp
|
class CfgPatches
{
class Enigma_Exile_Custom {
units[] = {};
weapons[] = {};
requiredVersion = 0.1;
author[]= {"Happydayz_EngimaTeam"};
};
};
class CfgFunctions
{
class EnigmaTeam
{
class main
{
file = "\Enigma_Exile_Custom\init";
class init
{
preInit = 1;
};
class postinit
{
postInit = 1;
};
};
};
};
|
[
"mrsage@xcsv.tv"
] |
mrsage@xcsv.tv
|
ecedf5a152a68f5ec4f7cabfe1fa482708e8bcb4
|
60276f056f1fc509593d4e05c383ba59148ad5e3
|
/DemoProj/Huffman/stdafx.cpp
|
96e356bbac808cb9db13c6d419381e0de5d5b75e
|
[] |
no_license
|
feiilin/DemoCodes
|
8b63b6afb3c0afe001be00848fd9409b3510aa51
|
d1b142da92318a66a7aab1f7cebdf54b1fe24b67
|
refs/heads/master
| 2022-11-30T17:08:40.234741
| 2020-08-18T07:05:22
| 2020-08-18T07:05:22
| 286,668,819
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 260
|
cpp
|
// stdafx.cpp : 只包括标准包含文件的源文件
// Huffman.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
|
[
"2273110249@qq.com"
] |
2273110249@qq.com
|
a120c473245e832ef76ab896c1f66b26bfb39e58
|
26ad4cc35496d364b31396e43a863aee08ef2636
|
/SDK/SoT_Proposal_Merchant_Rank07_CargoRun_03_classes.hpp
|
002c3f2d67d747c02e3e6b1c78b449cd49bd9fa1
|
[] |
no_license
|
cw100/SoT-SDK
|
ddb9b19ce6ae623299b2b02dee51c29581537ba1
|
3e6f12384c8e21ed83ef56f00030ca0506d297fb
|
refs/heads/master
| 2020-05-05T12:09:55.938323
| 2019-03-20T14:11:57
| 2019-03-20T14:11:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 817
|
hpp
|
#pragma once
// Sea of Thieves (1.4) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_Proposal_Merchant_Rank07_CargoRun_03_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Proposal_Merchant_Rank07_CargoRun_03.Proposal_Merchant_Rank07_CargoRun_03_C
// 0x0000 (0x0138 - 0x0138)
class UProposal_Merchant_Rank07_CargoRun_03_C : public UVoyageProposalDesc
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("BlueprintGeneratedClass Proposal_Merchant_Rank07_CargoRun_03.Proposal_Merchant_Rank07_CargoRun_03_C"));
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"igromanru@yahoo.de"
] |
igromanru@yahoo.de
|
756dfeb3fab0239288a99914424c3d4bbe3ffa62
|
cd484c21d9d412d81ee3039072365fbb32947fce
|
/WBoard/Source/tools/WBGraphicsCache.h
|
c267da4ccda46f5f770a130514051547cb0f5d34
|
[] |
no_license
|
drivestudy/WBoard
|
8c97fc4f01f58540718cd2c082562f9eab5761de
|
18959203a234944fb402b444462db76c6dd5b3c6
|
refs/heads/main
| 2023-08-01T01:41:04.303780
| 2021-09-09T04:56:46
| 2021-09-09T04:56:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,474
|
h
|
#ifndef WBGRAPHICSCACHE_H
#define WBGRAPHICSCACHE_H
#include <QColor>
#include <QGraphicsSceneMouseEvent>
#include "domain/WBItem.h"
#include "core/WB.h"
typedef enum
{
eMaskShape_Circle,
eMaskShap_Rectangle
}eMaskShape;
class WBGraphicsCache : public QGraphicsRectItem, public WBItem
{
public:
static WBGraphicsCache* instance(WBGraphicsScene *scene);
~WBGraphicsCache();
enum { Type = WBGraphicsItemType::cacheItemType };
virtual int type() const{ return Type;}
virtual WBItem* deepCopy() const;
virtual void copyItemParameters(WBItem *copy) const;
QColor maskColor();
void setMaskColor(QColor color);
eMaskShape maskshape();
void setMaskShape(eMaskShape shape);
int shapeWidth();
void setShapeWidth(int width);
protected:
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
private:
static QMap<WBGraphicsScene*, WBGraphicsCache*> sInstances;
QColor mMaskColor;
eMaskShape mMaskShape;
int mShapeWidth;
bool mDrawMask;
QPointF mShapePos;
int mOldShapeWidth;
QPointF mOldShapePos;
WBGraphicsScene* mScene;
WBGraphicsCache(WBGraphicsScene *scene);
void init();
QRectF updateRect(QPointF currentPoint);
};
#endif // WBGRAPHICSCACHE_H
|
[
"574226409@qq.com"
] |
574226409@qq.com
|
95d8241b798c687382be3f0c81556fcd4f16eb99
|
cb6a6b91b6f260e233663985a6e24bdd21559c91
|
/chapter16/c16e5.cc
|
7b20dea79c6a70359d25577c3e689641f8b536f2
|
[] |
no_license
|
drcxd/CppPrimerExercise
|
bf2ef28cfe9b1f5722116d550e7456fb395369c0
|
1b5b85d573144fc1019632c1e95cdcac01979d77
|
refs/heads/master
| 2021-01-23T09:10:06.782754
| 2018-02-09T02:01:19
| 2018-02-09T02:01:19
| 102,560,940
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 590
|
cc
|
#include <iostream>
#include <array>
// built-in array version
// template <unsigned N, typename T>
// void print(const T (&arr)[N]) {
// for (auto &it : arr) {
// std::cout << it << std::endl;
// }
// }
// stl array version
template <unsigned long N, typename T>
void print(const std::array<T, N> &arr) {
for (auto &it : arr) {
std::cout << it << std::endl;
}
}
int main() {
// std::string arr[5] = {"one", "two", "three", "four", "five"};
std::array<std::string, 5> arr = {"one", "two", "three", "four", "five"};
print(arr);
return 0;
}
|
[
"drcxd@sina.com"
] |
drcxd@sina.com
|
c94356bef61c119527a1d10644cfa7cfa23881c5
|
d52d5fdbcd848334c6b7799cad7b3dfd2f1f33e4
|
/third_party/folly/folly/test/ChronoTest.cpp
|
0e7ac92ee49b7aee8b4642b76964d27f578cdc02
|
[
"Apache-2.0"
] |
permissive
|
zhiliaoniu/toolhub
|
4109c2a488b3679e291ae83cdac92b52c72bc592
|
39a3810ac67604e8fa621c69f7ca6df1b35576de
|
refs/heads/master
| 2022-12-10T23:17:26.541731
| 2020-07-18T03:33:48
| 2020-07-18T03:33:48
| 125,298,974
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,146
|
cpp
|
/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/Chrono.h>
#include <folly/portability/GTest.h>
using namespace std::chrono;
using namespace folly::chrono;
namespace {
class ChronoTest : public testing::Test {};
} // namespace
TEST_F(ChronoTest, ceil_duration) {
EXPECT_EQ(seconds(7), ceil<seconds>(seconds(7)));
EXPECT_EQ(seconds(7), ceil<seconds>(milliseconds(7000)));
EXPECT_EQ(seconds(7), ceil<seconds>(milliseconds(6200)));
}
TEST_F(ChronoTest, ceil_time_point) {
auto const point = steady_clock::time_point{};
EXPECT_EQ(point + seconds(7), ceil<seconds>(point + seconds(7)));
EXPECT_EQ(point + seconds(7), ceil<seconds>(point + milliseconds(7000)));
EXPECT_EQ(point + seconds(7), ceil<seconds>(point + milliseconds(6200)));
}
TEST_F(ChronoTest, floor_duration) {
EXPECT_EQ(seconds(7), floor<seconds>(seconds(7)));
EXPECT_EQ(seconds(7), floor<seconds>(milliseconds(7000)));
EXPECT_EQ(seconds(7), floor<seconds>(milliseconds(7800)));
}
TEST_F(ChronoTest, floor_time_point) {
auto const point = steady_clock::time_point{};
EXPECT_EQ(point + seconds(7), floor<seconds>(point + seconds(7)));
EXPECT_EQ(point + seconds(7), floor<seconds>(point + milliseconds(7000)));
EXPECT_EQ(point + seconds(7), floor<seconds>(point + milliseconds(7800)));
}
TEST_F(ChronoTest, round_duration) {
EXPECT_EQ(seconds(7), round<seconds>(seconds(7)));
EXPECT_EQ(seconds(6), round<seconds>(milliseconds(6200)));
EXPECT_EQ(seconds(6), round<seconds>(milliseconds(6500)));
EXPECT_EQ(seconds(7), round<seconds>(milliseconds(6800)));
EXPECT_EQ(seconds(7), round<seconds>(milliseconds(7000)));
EXPECT_EQ(seconds(7), round<seconds>(milliseconds(7200)));
EXPECT_EQ(seconds(8), round<seconds>(milliseconds(7500)));
EXPECT_EQ(seconds(8), round<seconds>(milliseconds(7800)));
}
TEST_F(ChronoTest, round_time_point) {
auto const point = steady_clock::time_point{};
EXPECT_EQ(point + seconds(7), round<seconds>(point + seconds(7)));
EXPECT_EQ(point + seconds(6), round<seconds>(point + milliseconds(6200)));
EXPECT_EQ(point + seconds(6), round<seconds>(point + milliseconds(6500)));
EXPECT_EQ(point + seconds(7), round<seconds>(point + milliseconds(6800)));
EXPECT_EQ(point + seconds(7), round<seconds>(point + milliseconds(7000)));
EXPECT_EQ(point + seconds(7), round<seconds>(point + milliseconds(7200)));
EXPECT_EQ(point + seconds(8), round<seconds>(point + milliseconds(7500)));
EXPECT_EQ(point + seconds(8), round<seconds>(point + milliseconds(7800)));
}
|
[
"yangshengzhi1@bigo.sg"
] |
yangshengzhi1@bigo.sg
|
4da7e1f0758c1104525dc6ac848d7aa50586f3df
|
bfc0a74a378d3692d5b033c21c29cf223d2668da
|
/unittests/libtests/faults/TestFaultCohesiveKinSrcsCases.hh
|
2d50d2c0cf9ca9b8b598e087bf3d83de1c9de730
|
[
"MIT"
] |
permissive
|
rishabhdutta/pylith
|
b2ed9cd8039de33e337c5bc989e6d76d85fd4df1
|
cb07c51b1942f7c6d60ceca595193c59a0faf3a5
|
refs/heads/master
| 2020-12-29T01:53:49.828328
| 2016-07-15T20:34:58
| 2016-07-15T20:34:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,478
|
hh
|
// -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2016 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
/**
* @file unittests/libtests/faults/TestFaultCohesiveKinSrcsCases.hh
*
* @brief C++ unit testing for FaultCohesiveKin with multiple earthquake ruptures.
*/
#if !defined(pylith_faults_testfaultcohesivekinsrcscases_hh)
#define pylith_faults_testfaultcohesivekinsrcscases_hh
#include "TestFaultCohesiveKinSrcs.hh" // ISA TestFaultCohesiveKinSrcs
/// Namespace for pylith package
namespace pylith {
namespace faults {
class TestFaultCohesiveKinSrcsTri3;
class TestFaultCohesiveKinSrcsQuad4;
class TestFaultCohesiveKinSrcsTet4;
class TestFaultCohesiveKinSrcsHex8;
} // bc
} // pylith
// ----------------------------------------------------------------------
/// C++ unit testing for FaultCohesiveKinSrcs for mesh with 2-D triangular cells.
class pylith::faults::TestFaultCohesiveKinSrcsTri3 : public TestFaultCohesiveKinSrcs
{ // class TestFaultCohesiveKinSrcsTri3
// CPPUNIT TEST SUITE /////////////////////////////////////////////////
CPPUNIT_TEST_SUITE( TestFaultCohesiveKinSrcsTri3 );
CPPUNIT_TEST( testInitialize );
CPPUNIT_TEST( testIntegrateResidual );
CPPUNIT_TEST( testIntegrateJacobian );
CPPUNIT_TEST( testIntegrateJacobianLumped );
CPPUNIT_TEST( testCalcTractionsChange );
CPPUNIT_TEST_SUITE_END();
// PUBLIC METHODS /////////////////////////////////////////////////////
public :
/// Setup testing data.
void setUp(void);
}; // class TestFaultCohesiveKinSrcsTri3
// ----------------------------------------------------------------------
/// C++ unit testing for FaultCohesiveKin for mesh with 2-D quadrilateral cells.
class pylith::faults::TestFaultCohesiveKinSrcsQuad4 : public TestFaultCohesiveKinSrcs
{ // class TestFaultCohesiveKinSrcsQuad4
// CPPUNIT TEST SUITE /////////////////////////////////////////////////
CPPUNIT_TEST_SUITE( TestFaultCohesiveKinSrcsQuad4 );
CPPUNIT_TEST( testInitialize );
CPPUNIT_TEST( testIntegrateResidual );
CPPUNIT_TEST( testIntegrateJacobian );
CPPUNIT_TEST( testIntegrateJacobianLumped );
CPPUNIT_TEST( testCalcTractionsChange );
CPPUNIT_TEST_SUITE_END();
// PUBLIC METHODS /////////////////////////////////////////////////////
public :
/// Setup testing data.
void setUp(void);
}; // class TestFaultCohesiveKinSrcsQuad4
// ----------------------------------------------------------------------
/// C++ unit testing for FaultCohesiveKin for mesh with 3-D tetrahedral cells.
class pylith::faults::TestFaultCohesiveKinSrcsTet4 : public TestFaultCohesiveKinSrcs
{ // class TestFaultCohesiveKinSrcsTet4
// CPPUNIT TEST SUITE /////////////////////////////////////////////////
CPPUNIT_TEST_SUITE( TestFaultCohesiveKinSrcsTet4 );
CPPUNIT_TEST( testInitialize );
CPPUNIT_TEST( testIntegrateResidual );
CPPUNIT_TEST( testIntegrateJacobian );
CPPUNIT_TEST( testIntegrateJacobianLumped );
CPPUNIT_TEST( testCalcTractionsChange );
CPPUNIT_TEST_SUITE_END();
// PUBLIC METHODS /////////////////////////////////////////////////////
public :
/// Setup testing data.
void setUp(void);
}; // class TestFaultCohesiveKinSrcsTet4
// ----------------------------------------------------------------------
/// C++ unit testing for FaultCohesiveKin for mesh with 3-D hex cells.
class pylith::faults::TestFaultCohesiveKinSrcsHex8 : public TestFaultCohesiveKinSrcs
{ // class TestFaultCohesiveKinSrcsHex8
// CPPUNIT TEST SUITE /////////////////////////////////////////////////
CPPUNIT_TEST_SUITE( TestFaultCohesiveKinSrcsHex8 );
CPPUNIT_TEST( testInitialize );
CPPUNIT_TEST( testIntegrateResidual );
CPPUNIT_TEST( testIntegrateJacobian );
CPPUNIT_TEST( testIntegrateJacobianLumped );
CPPUNIT_TEST( testCalcTractionsChange );
CPPUNIT_TEST_SUITE_END();
// PUBLIC METHODS /////////////////////////////////////////////////////
public :
/// Setup testing data.
void setUp(void);
}; // class TestFaultCohesiveKinSrcsHex8
#endif // pylith_faults_testfaultcohesivesrcscases_hh
// End of file
|
[
"baagaard@usgs.gov"
] |
baagaard@usgs.gov
|
d9383c6124ba75f5460fb2432f541924204971c7
|
8774e1860d88aeadcd1709e543f262b9f7983f31
|
/src/qt/test/uritests.h
|
6943eeb2c400be9216b1820af02d060a08439468
|
[
"MIT"
] |
permissive
|
npq7721/raven-dark
|
cb1d0f5da007ff5a46f6b1d8410101ce827a7f5f
|
abc2c956f5eb5b01eb4703918f50ba325b676661
|
refs/heads/master
| 2020-08-04T17:04:11.847541
| 2019-07-19T19:32:55
| 2019-07-19T19:32:55
| 212,213,490
| 0
| 0
|
MIT
| 2019-10-01T22:47:40
| 2019-10-01T22:47:40
| null |
UTF-8
|
C++
| false
| false
| 436
|
h
|
// 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.
#ifndef RAVENDARK_QT_TEST_URITESTS_H
#define RAVENDARK_QT_TEST_URITESTS_H
#include <QObject>
#include <QTest>
class URITests : public QObject
{
Q_OBJECT
private Q_SLOTS:
void uriTests();
};
#endif // RAVENDARK_QT_TEST_URITESTS_H
|
[
"j4ys0n@gmail.com"
] |
j4ys0n@gmail.com
|
ad656658ad1414291b8accf70d9023af491026c8
|
4258a21020932d0849a95c182aa8086a0467e641
|
/sdk/verify/mi_demo/alderaan/vpe/st_main_vpe.cpp
|
65bd8dc4eb7499503c3429ff7b88012308da7223
|
[] |
no_license
|
sengeiou/Democode-TAKOYAKI-BETA001-0312
|
a04647412764b57532a1b8ca02a1b4966a5a5395
|
0c3261e5c067314d2ac4f858399fff8cc2793f01
|
refs/heads/master
| 2022-05-24T09:48:13.816615
| 2020-04-13T10:47:24
| 2020-04-13T10:47:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 107,538
|
cpp
|
/* Copyright (c) 2018-2019 Sigmastar Technology Corp.
All rights reserved.
Unless otherwise stipulated in writing, any and all information contained
herein regardless in any format shall remain the sole proprietary of
Sigmastar Technology Corp. and be kept in strict confidence
(��Sigmastar Confidential Information��) by the recipient.
Any unauthorized act including without limitation unauthorized disclosure,
copying, use, reproduction, sale, distribution, modification, disassembling,
reverse engineering and compiling of the contents of Sigmastar Confidential
Information is unlawful and strictly prohibited. Sigmastar hereby reserves the
rights to any and all damages, losses, costs and expenses resulting therefrom.
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/syscall.h>
#include "st_common.h"
#include "st_vif.h"
#include "st_vpe.h"
#include "st_venc.h"
#include "BasicUsageEnvironment.hh"
#include "liveMedia.hh"
#include "Live555RTSPServer.hh"
//#include "mi_rgn.h"
#include "mi_sensor.h"
#include "mi_sensor_datatype.h"
#include "mi_isp.h"
#include "mi_iqserver.h"
#include "mi_eptz.h"
#include "mi_ldc.h"
#include "mi_eptz.h"
#define RTSP_LISTEN_PORT 554
static Live555RTSPServer *g_pRTSPServer = NULL;
#define PATH_PREFIX "/mnt"
int s32LoadIQBin = 1;
#define NONHDR_PATH "/customer/nohdr.bin"
#define HDR_PATH "/customer/hdr.bin"
#define ST_MAX_PORT_NUM (5)
#define ST_MAX_SCL_NUM (3)
#define ST_MAX_SENSOR_NUM (3)
#define ST_MAX_STREAM_NUM (ST_MAX_PORT_NUM * ST_MAX_SENSOR_NUM)
#define ST_LDC_MAX_VIEWNUM (4)
#define ASCII_COLOR_GREEN "\033[1;32m"
#define ASCII_COLOR_END "\033[0m"
#define ASCII_COLOR_RED "\033[1;31m"
#define DBG_INFO(fmt, args...) printf(ASCII_COLOR_GREEN"%s[%d]: " fmt ASCII_COLOR_END, __FUNCTION__,__LINE__, ##args);
#define DBG_ERR(fmt, args...) printf(ASCII_COLOR_RED"%s[%d]: " fmt ASCII_COLOR_END, __FUNCTION__,__LINE__, ##args);
typedef struct ST_Sensor_Attr_s
{
MI_U32 u32BindVifDev;
MI_BOOL bUsed;
}ST_Sensor_Attr_t;
typedef struct ST_Vif_Attr_s
{
MI_U32 u32BindVpeChan;
MI_SYS_BindType_e eBindType;
MI_VIF_WorkMode_e eWorkMode;
}ST_Vif_Attr_t;
typedef struct ST_VpePortAttr_s
{
MI_BOOL bUsed;
MI_U32 u32BindVencChan;
MI_BOOL bMirror;
MI_BOOL bFlip;
MI_SYS_PixelFormat_e ePixelFormat;
MI_SYS_WindowRect_t stPortCrop;
MI_SYS_WindowSize_t stPortSize;
MI_SYS_WindowSize_t stOrigPortSize;
MI_SYS_WindowRect_t stOrigPortCrop;
MI_S32 s32DumpBuffNum;
char FilePath[256];
pthread_mutex_t Portmutex;
pthread_t pGetDatathread;
}ST_VpePortAttr_t;
typedef struct ST_VpeChannelAttr_s
{
ST_VpePortAttr_t stVpePortAttr[ST_MAX_PORT_NUM];
MI_VPE_HDRType_e eHdrType;
MI_VPE_3DNR_Level_e e3DNRLevel;
MI_SYS_Rotate_e eVpeRotate;
MI_BOOL bChnMirror;
MI_BOOL bChnFlip;
MI_SYS_WindowRect_t stVpeChnCrop;
MI_SYS_WindowRect_t stOrgVpeChnCrop;
MI_BOOL bEnLdc;
MI_U32 u32ChnPortMode;
MI_VPE_RunningMode_e eRunningMode;
char LdcCfgbin_Path[128];
mi_eptz_config_param tconfig_para;
MI_U32 u32ViewNum;
LDC_BIN_HANDLE ldcBinBuffer[ST_LDC_MAX_VIEWNUM];
MI_U32 u32LdcBinSize[ST_LDC_MAX_VIEWNUM];
MI_S32 s32Rot[ST_LDC_MAX_VIEWNUM];
}ST_VpeChannelAttr_t;
typedef struct ST_VencAttr_s
{
MI_U32 u32BindVpeChn;
MI_U32 u32BindVpePort;
MI_SYS_BindType_e eBindType;
MI_U32 u32BindParam;
MI_VENC_CHN vencChn;
MI_VENC_ModType_e eType;
MI_U32 u32Width;
MI_U32 u32Height;
char szStreamName[128];
MI_BOOL bUsed;
MI_BOOL bStart;
}ST_VencAttr_t;
static MI_S32 gbPreviewByVenc = FALSE;
static ST_Sensor_Attr_t gstSensorAttr[ST_MAX_SENSOR_NUM];
static ST_Vif_Attr_t gstVifAttr[ST_MAX_SENSOR_NUM];
static ST_VpeChannelAttr_t gstVpeChnattr[ST_MAX_SENSOR_NUM];
static ST_VencAttr_t gstVencattr[ST_MAX_STREAM_NUM];
static MI_BOOL bExit = FALSE;
void ST_Flush(void)
{
char c;
while((c = getchar()) != '\n' && c != EOF);
}
void *ST_OpenStream(char const *szStreamName, void *arg)
{
MI_U32 i = 0;
MI_S32 s32Ret = MI_SUCCESS;
for(i = 0; i < ST_MAX_STREAM_NUM; i ++)
{
if(!strncmp(szStreamName, gstVencattr[i].szStreamName,
strlen(szStreamName)))
{
break;
}
}
if(i >= ST_MAX_STREAM_NUM)
{
ST_ERR("not found this stream, \"%s\"", szStreamName);
return NULL;
}
ST_VencAttr_t *pstVencAttr = &gstVencattr[i];
s32Ret = MI_VENC_RequestIdr(pstVencAttr->vencChn, TRUE);
ST_DBG("open stream \"%s\" success, chn:%d\n", szStreamName, pstVencAttr->vencChn);
if(MI_SUCCESS != s32Ret)
{
ST_WARN("request IDR fail, error:%x\n", s32Ret);
}
return pstVencAttr;
}
MI_U32 u32GetCnt=0, u32ReleaseCnt=0;
int ST_VideoReadStream(void *handle, unsigned char *ucpBuf, int BufLen, struct timeval *p_Timestamp, void *arg)
{
MI_SYS_BufInfo_t stBufInfo;
MI_S32 s32Ret = MI_SUCCESS;
MI_S32 len = 0;
MI_U32 u32DevId = 0;
MI_VENC_Stream_t stStream;
MI_VENC_Pack_t stPack;
MI_VENC_ChnStat_t stStat;
MI_VENC_CHN vencChn ;
if(handle == NULL)
{
return -1;
}
ST_VencAttr_t *pstStreamInfo = (ST_VencAttr_t *)handle;
vencChn = pstStreamInfo->vencChn;
if(pstStreamInfo->bStart == FALSE)
return 0;
s32Ret = MI_VENC_GetChnDevid(vencChn, &u32DevId);
if(MI_SUCCESS != s32Ret)
{
ST_INFO("MI_VENC_GetChnDevid %d error, %X\n", vencChn, s32Ret);
}
memset(&stBufInfo, 0x0, sizeof(MI_SYS_BufInfo_t));
memset(&stStream, 0, sizeof(stStream));
memset(&stPack, 0, sizeof(stPack));
stStream.pstPack = &stPack;
stStream.u32PackCount = 1;
s32Ret = MI_VENC_Query(vencChn, &stStat);
if(s32Ret != MI_SUCCESS || stStat.u32CurPacks == 0)
{
return 0;
}
s32Ret = MI_VENC_GetStream(vencChn, &stStream, 40);
if(MI_SUCCESS == s32Ret)
{
u32GetCnt++;
len = stStream.pstPack[0].u32Len;
memcpy(ucpBuf, stStream.pstPack[0].pu8Addr, MIN(len, BufLen));
s32Ret = MI_VENC_ReleaseStream(vencChn, &stStream);
if(s32Ret != MI_SUCCESS)
{
ST_WARN("RELEASE venc buffer fail\n");
}
u32ReleaseCnt ++;
return len;
}
return 0;
}
int ST_CloseStream(void *handle, void *arg)
{
if(handle == NULL)
{
return -1;
}
ST_VencAttr_t *pstStreamInfo = (ST_VencAttr_t *)handle;
ST_DBG("close \"%s\" success\n", pstStreamInfo->szStreamName);
return 0;
}
MI_S32 ST_RtspServerStart(void)
{
unsigned int rtspServerPortNum = RTSP_LISTEN_PORT;
int iRet = 0;
char *urlPrefix = NULL;
int arraySize = ARRAY_SIZE(gstVencattr);
ST_VencAttr_t *pstStreamAttr = gstVencattr;
int i = 0;
ServerMediaSession *mediaSession = NULL;
ServerMediaSubsession *subSession = NULL;
Live555RTSPServer *pRTSPServer = NULL;
pRTSPServer = new Live555RTSPServer();
if(pRTSPServer == NULL)
{
ST_ERR("malloc error\n");
return -1;
}
iRet = pRTSPServer->SetRTSPServerPort(rtspServerPortNum);
while(iRet < 0)
{
rtspServerPortNum++;
if(rtspServerPortNum > 65535)
{
ST_INFO("Failed to create RTSP server: %s\n", pRTSPServer->getResultMsg());
delete pRTSPServer;
pRTSPServer = NULL;
return -2;
}
iRet = pRTSPServer->SetRTSPServerPort(rtspServerPortNum);
}
urlPrefix = pRTSPServer->rtspURLPrefix();
for(i = 0; i < arraySize; i ++)
{
if(pstStreamAttr[i].bUsed != TRUE)
continue;
printf("=================URL===================\n");
printf("%s%s\n", urlPrefix, pstStreamAttr[i].szStreamName);
printf("=================URL===================\n");
pRTSPServer->createServerMediaSession(mediaSession,
pstStreamAttr[i].szStreamName,
NULL, NULL);
if(pstStreamAttr[i].eType == E_MI_VENC_MODTYPE_H264E)
{
subSession = WW_H264VideoFileServerMediaSubsession::createNew(
*(pRTSPServer->GetUsageEnvironmentObj()),
pstStreamAttr[i].szStreamName,
ST_OpenStream,
ST_VideoReadStream,
ST_CloseStream, 30);
}
else if(pstStreamAttr[i].eType == E_MI_VENC_MODTYPE_H265E)
{
subSession = WW_H265VideoFileServerMediaSubsession::createNew(
*(pRTSPServer->GetUsageEnvironmentObj()),
pstStreamAttr[i].szStreamName,
ST_OpenStream,
ST_VideoReadStream,
ST_CloseStream, 30);
}
else if(pstStreamAttr[i].eType == E_MI_VENC_MODTYPE_JPEGE)
{
subSession = WW_JPEGVideoFileServerMediaSubsession::createNew(
*(pRTSPServer->GetUsageEnvironmentObj()),
pstStreamAttr[i].szStreamName,
ST_OpenStream,
ST_VideoReadStream,
ST_CloseStream, 30);
}
pRTSPServer->addSubsession(mediaSession, subSession);
pRTSPServer->addServerMediaSession(mediaSession);
}
pRTSPServer->Start();
g_pRTSPServer = pRTSPServer;
return 0;
}
MI_S32 ST_RtspServerStop(void)
{
if(g_pRTSPServer)
{
g_pRTSPServer->Join();
delete g_pRTSPServer;
g_pRTSPServer = NULL;
}
return 0;
}
MI_S32 ST_WriteOneFrame(FILE *fp, int offset, char *pDataFrame, int line_offset, int line_size, int lineNumber)
{
int size = 0;
int i = 0;
char *pData = NULL;
int yuvSize = line_size;
MI_S32 s32Ret = -1;
for(i = 0; i < lineNumber; i++)
{
pData = pDataFrame + line_offset * i;
yuvSize = line_size;
do
{
if(yuvSize < 256)
{
size = yuvSize;
}
else
{
size = 256;
}
size = fwrite(pData, 1, size, fp);
if(size == 0)
{
break;
}
else if(size < 0)
{
break;
}
pData += size;
yuvSize -= size;
}
while(yuvSize > 0);
s32Ret = MI_SUCCESS;
}
return s32Ret;
}
MI_S32 ST_GetVpeOutputData(MI_U32 u32SensorNum)
{
MI_S32 s32Portid = 0;
MI_S32 s32Channelid = 0;
MI_S32 s32DumpBuffNum =0;
char sFilePath[128];
time_t stTime = 0;
ST_VpePortAttr_t *pstVpePortAttr = NULL;
MI_VPE_PortMode_t stVpePortMode;
memset(&stVpePortMode, 0x0, sizeof(MI_VPE_PortMode_t));
memset(&stTime, 0, sizeof(stTime));
if(u32SensorNum > 1)
{
printf("select channel id:");
scanf("%d", &s32Channelid);
ST_Flush();
if(s32Channelid >= ST_MAX_SENSOR_NUM)
{
printf("chnid %d > max %d \n", s32Channelid, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
s32Channelid = 0;
}
printf("select port id:");
scanf("%d", &s32Portid);
ST_Flush();
printf("Dump Buffer Num:");
scanf("%d", &s32DumpBuffNum);
ST_Flush();
printf("write file path:\n");
scanf("%s", sFilePath);
ST_Flush();
if(s32Portid >= ST_MAX_PORT_NUM)
{
printf("port %d, not valid 0~3 \n", s32Portid);
return 0;
}
pstVpePortAttr = &gstVpeChnattr[s32Channelid].stVpePortAttr[s32Portid];
if(pstVpePortAttr->bUsed != TRUE)
{
printf("port %d, not valid \n", s32Portid);
return 0;
}
pthread_mutex_lock(&pstVpePortAttr->Portmutex);
MI_VPE_GetPortMode(0, s32Portid, &stVpePortMode);
sprintf(pstVpePortAttr->FilePath, "%s/vpeport%d_%dx%d_pixel%d_%ld.raw", sFilePath, s32Portid, stVpePortMode.u16Width, stVpePortMode.u16Height, stVpePortMode.ePixelFormat, time(&stTime));
pstVpePortAttr->s32DumpBuffNum = s32DumpBuffNum;
pthread_mutex_unlock(&pstVpePortAttr->Portmutex);
return 0;
}
MI_S32 ST_VpeDisablePort(MI_U32 u32SensorNum)
{
MI_S32 s32Portid = 0;
ST_VpePortAttr_t *pstVpePortAttr = NULL;
MI_S32 s32Channelid = 0;
if(u32SensorNum > 1)
{
printf("select channel id:");
scanf("%d", &s32Channelid);
ST_Flush();
if(s32Channelid >= ST_MAX_SENSOR_NUM)
{
printf("chnid %d > max %d \n", s32Channelid, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
s32Channelid = 0;
}
printf("select port id:");
scanf("%d", &s32Portid);
ST_Flush();
if(s32Portid >= ST_MAX_PORT_NUM)
{
printf("port %d, not valid 0~3 \n", s32Portid);
return 0;
}
pstVpePortAttr = &gstVpeChnattr[s32Channelid].stVpePortAttr[s32Portid];
pstVpePortAttr->bUsed = FALSE;
MI_VPE_DisablePort(s32Channelid, s32Portid);
return 0;
}
MI_S32 ST_GetVencOut()
{
MI_S32 s32Ret = MI_SUCCESS;
MI_VENC_Stream_t stStream;
MI_VENC_Pack_t stPack;
MI_U32 u32BypassCnt = 0;
MI_S32 s32DumpBuffNum = 0;
MI_S32 VencChn = 0;
MI_VENC_Pack_t *pstPack = NULL;
MI_U32 i=0;
FILE *fp = NULL;
char FilePath[256];
char sFilePath[128];
time_t stTime = 0;
MI_VENC_ChnStat_t stStat;
MI_VENC_ChnAttr_t stVencAttr;
memset(&stVencAttr, 0x0, sizeof(MI_VENC_ChnAttr_t));
memset(&stStat, 0x0, sizeof(MI_VENC_ChnStat_t));
memset(&stStream, 0, sizeof(MI_VENC_Stream_t));
memset(&stPack, 0, sizeof(MI_VENC_Pack_t));
stStream.pstPack = &stPack;
stStream.u32PackCount = 1;
printf("select venc chn id:");
scanf("%d", &VencChn);
ST_Flush();
printf("Dump Buffer Num:");
scanf("%d", &s32DumpBuffNum);
ST_Flush();
printf("write file path:\n");
scanf("%s", sFilePath);
ST_Flush();
s32Ret = MI_VENC_GetChnAttr(VencChn, &stVencAttr);
if(s32Ret != MI_SUCCESS)
{
printf("channel %d, not valid \n", VencChn);
return 0;
}
if(stVencAttr.stVeAttr.eType == E_MI_VENC_MODTYPE_JPEGE)
sprintf(FilePath, "%s/venc_%ld.jpg", sFilePath, time(&stTime));
else
sprintf(FilePath, "%s/venc_%ld.es", sFilePath, time(&stTime));
fp = fopen(FilePath,"wb");
if(fp == NULL)
{
printf("open file %s fail \n",FilePath);
return 0;
}
while(s32DumpBuffNum > 0)
{
s32Ret = MI_VENC_Query(VencChn, &stStat);
if(s32Ret != MI_SUCCESS || stStat.u32CurPacks == 0)
{
usleep(1 * 1000);
continue;
}
s32Ret = MI_VENC_GetStream(VencChn, &stStream, 100);
if(MI_SUCCESS == s32Ret)
{
if (0 == u32BypassCnt)
{
printf("##########Start to write file %s, id %d !!!#####################\n",FilePath, s32DumpBuffNum);
for(i = 0; i < stStream.u32PackCount; i ++)
{
pstPack = &stStream.pstPack[i];
fwrite(pstPack->pu8Addr + pstPack->u32Offset, pstPack->u32Len - pstPack->u32Offset, 1, fp);
}
printf("##########End to write file id %d !!!#####################\n", s32DumpBuffNum);
s32DumpBuffNum --;
}
else
{
u32BypassCnt--;
printf("Bypasss frame %d !\n", u32BypassCnt);
}
s32Ret = MI_VENC_ReleaseStream(VencChn, &stStream);
if(MI_SUCCESS != s32Ret)
{
ST_DBG("MI_VENC_ReleaseStream fail, ret:0x%x\n", s32Ret);
}
}
usleep(200 * 1000);
}
fclose(fp);
return 0;
}
MI_S32 ST_ReadLdcTableBin(const char *pConfigPath, LDC_BIN_HANDLE *tldc_bin, MI_U32 *pu32BinSize)
{
struct stat statbuff;
MI_U8 *pBufData = NULL;
MI_S32 s32Fd = 0;
MI_U32 u32Size = 0;
if (pConfigPath == NULL)
{
ST_ERR("File path null!\n");
return MI_ERR_LDC_ILLEGAL_PARAM;
}
printf("Read file %s\n", pConfigPath);
memset(&statbuff, 0, sizeof(struct stat));
if(stat(pConfigPath, &statbuff) < 0)
{
ST_ERR("Bb table file not exit!\n");
return MI_ERR_LDC_ILLEGAL_PARAM;
}
else
{
if (statbuff.st_size == 0)
{
ST_ERR("File size is zero!\n");
return MI_ERR_LDC_ILLEGAL_PARAM;
}
u32Size = statbuff.st_size;
}
s32Fd = open(pConfigPath, O_RDONLY);
if (s32Fd < 0)
{
ST_ERR("Open file[%d] error!\n", s32Fd);
return MI_ERR_LDC_ILLEGAL_PARAM;
}
pBufData = (MI_U8 *)malloc(u32Size);
if (!pBufData)
{
ST_ERR("Malloc error!\n");
close(s32Fd);
return MI_ERR_LDC_ILLEGAL_PARAM;
}
memset(pBufData, 0, u32Size);
read(s32Fd, pBufData, u32Size);
close(s32Fd);
*tldc_bin = pBufData;
*pu32BinSize = u32Size;
printf("%d: read buffer %p \n",__LINE__, pBufData);
printf("%d: &bin address %p, *binbuffer %p \n",__LINE__, tldc_bin, *tldc_bin);
//free(pBufData);
return MI_SUCCESS;
}
MI_S32 ST_GetLdcCfgViewNum(mi_LDC_MODE eLdcMode)
{
MI_U32 u32ViewNum = 0;
switch(eLdcMode)
{
case LDC_MODE_1R:
case LDC_MODE_1P_CM:
case LDC_MODE_1P_WM:
case LDC_MODE_1O:
case LDC_MODE_1R_WM:
u32ViewNum = 1;
break;
case LDC_MODE_2P_CM:
case LDC_MODE_2P_DM:
u32ViewNum = 2;
break;
case LDC_MODE_4R_CM:
case LDC_MODE_4R_WM:
u32ViewNum = 4;
break;
default:
printf("########### ldc mode %d err \n", eLdcMode);
break;
}
printf("view num %d \n", u32ViewNum);
return u32ViewNum;
}
MI_S32 ST_Parse_LibarayCfgFilePath(char *pLdcLibCfgPath, mi_eptz_config_param *ptconfig_para)
{
mi_eptz_err err_state = MI_EPTZ_ERR_NONE;
printf("cfg file path %s\n", pLdcLibCfgPath);
//check cfg file, in out path with bin position
err_state = mi_eptz_config_parse(pLdcLibCfgPath, ptconfig_para);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("confile file read error: %d\n", err_state);
return err_state;
}
printf("ldc mode %d \n", ptconfig_para->ldc_mode);
return 0;
}
MI_S32 ST_Libaray_CreatBin(MI_S32 s32ViewId, mi_eptz_config_param *ptconfig_para, LDC_BIN_HANDLE *ptldc_bin, MI_U32 *pu32LdcBinSize, MI_S32 s32Rot)
{
unsigned char* pWorkingBuffer;
int working_buf_len = 0;
mi_eptz_err err_state = MI_EPTZ_ERR_NONE;
EPTZ_DEV_HANDLE eptz_handle = NULL;
mi_eptz_para teptz_para;
memset(&teptz_para, 0x0, sizeof(mi_eptz_para));
printf("view %d rot %d\n", s32ViewId, s32Rot);
working_buf_len = mi_eptz_get_buffer_info(ptconfig_para);
pWorkingBuffer = (unsigned char*)malloc(working_buf_len);
if (pWorkingBuffer == NULL)
{
printf("buffer allocate error\n");
return MI_EPTZ_ERR_MEM_ALLOCATE_FAIL;
}
// printf("%s:%d working_buf_len %d \n", __FUNCTION__, __LINE__, working_buf_len);
//EPTZ init
teptz_para.ptconfig_para = ptconfig_para; //ldc configure
// printf("%s:%d ptconfig_para %p, pWorkingBuffer %p, working_buf_len %d\n", __FUNCTION__, __LINE__, teptz_para.ptconfig_para,
// pWorkingBuffer, working_buf_len);
eptz_handle = mi_eptz_runtime_init(pWorkingBuffer, working_buf_len, &teptz_para);
if (eptz_handle == NULL)
{
printf("EPTZ init error\n");
return MI_EPTZ_ERR_NOT_INIT;
}
teptz_para.pan = 0;
teptz_para.tilt = -60;
if(ptconfig_para->ldc_mode == 1)
teptz_para.tilt = 60;
teptz_para.rotate = s32Rot;
teptz_para.zoom = 150.00;
teptz_para.out_rot = 0;
teptz_para.view_index = s32ViewId;
//Gen bin files from 0 to 360 degree
switch (ptconfig_para->ldc_mode)
{
case LDC_MODE_4R_CM: //LDC_MODE_4R_CM/Desk, if in desk mount mode, tilt is nagetive.
teptz_para.view_index = s32ViewId;
teptz_para.pan = 0;
teptz_para.tilt = -50; //In CM mode, tilt is positive, but in desk mode, tilt is negative.
teptz_para.rotate = s32Rot;
teptz_para.zoom = 150;
teptz_para.out_rot = 0;
err_state = (mi_eptz_err)mi_eptz_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("[EPTZ ERR] = %d !! \n", err_state);
}
break;
case LDC_MODE_4R_WM: //LDC_MODE_4R_WM
teptz_para.view_index = s32ViewId;
teptz_para.pan = 0;
teptz_para.tilt = 50; //In CM mode, tilt is positive, but in desk mode, tilt is negative.
teptz_para.rotate = s32Rot;
teptz_para.zoom = 150;
teptz_para.out_rot = 0;
err_state = (mi_eptz_err)mi_eptz_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("[EPTZ ERR] = %d !! \n", err_state);
}
break;
case LDC_MODE_1R: //LDC_MODE_1R CM/Desk, if in desk mount mode, tilt is negative.
teptz_para.view_index = s32ViewId;
teptz_para.pan = 0;
teptz_para.tilt = 0; //In CM mode, tilt is positive, but in desk mode, tilt is negative.
teptz_para.rotate = s32Rot;
teptz_para.zoom = 150;
teptz_para.out_rot = 0;
err_state = (mi_eptz_err)mi_eptz_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("[EPTZ ERR] = %d !! \n", err_state);
}
break;
case LDC_MODE_1R_WM: //LDC_MODE_1R WM
teptz_para.view_index = s32ViewId;
teptz_para.pan = 0;
teptz_para.tilt = 50; //In CM mode, tilt is positive, but in desk mode, tilt is negative.
teptz_para.rotate = s32Rot;
teptz_para.zoom = 150;
teptz_para.out_rot = 0;
err_state = (mi_eptz_err)mi_eptz_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("[EPTZ ERR] = %d !! \n", err_state);
}
break;
case LDC_MODE_2P_CM: //LDC_MODE_2P_CM
case LDC_MODE_2P_DM: //LDC_MODE_2P_DM
case LDC_MODE_1P_CM: //LDC_MODE_1P_CM
//Set the input parameters for donut mode
if(s32Rot > 180)
{
//Degree 180 ~ 360
teptz_para.view_index = s32ViewId;
teptz_para.r_inside = 550;
teptz_para.r_outside = 10;
teptz_para.theta_start = s32Rot;
teptz_para.theta_end = s32Rot+360;
}
else
{
//Degree 180 ~ 0
teptz_para.view_index = s32ViewId;
teptz_para.r_inside = 10;
teptz_para.r_outside = 550;
teptz_para.theta_start = s32Rot;
teptz_para.theta_end = s32Rot+360;
}
err_state = (mi_eptz_err)mi_donut_runtime_map_gen(eptz_handle, (mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("[EPTZ ERR] = %d !! \n", err_state);
}
break;
case LDC_MODE_1P_WM: //LDC_MODE_1P wall mount.
teptz_para.view_index = s32ViewId;
teptz_para.pan = 0;
teptz_para.tilt = 0;
teptz_para.zoom_h = 100;
teptz_para.zoom_v = 100;
err_state = (mi_eptz_err)mi_erp_runtime_map_gen(eptz_handle,(mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("[EPTZ ERR] = %d !! \n", err_state);
}
break;
case LDC_MODE_1O: //bypass mode
teptz_para.view_index = 0; //view index
printf("begin mi_bypass_runtime_map_gen \n");
err_state = (mi_eptz_err)mi_bypass_runtime_map_gen(eptz_handle, (mi_eptz_para*)&teptz_para, ptldc_bin, (int *)pu32LdcBinSize);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("[MODE %d ERR] = %d !! \n", LDC_MODE_1O, err_state);
return err_state;
}
printf("end mi_bypass_runtime_map_gen\n");
break;
default :
printf("********************err ldc mode %d \n", ptconfig_para->ldc_mode);
return 0;
}
#if 0
FILE *fp = NULL;
fp = fopen("/mnt/ldc.bin","wb");
fwrite(ptldc_bin, *pu32LdcBinSize, 1, fp);
fclose(fp);
#endif
//Free bin buffer
/*
err_state = mi_eptz_buffer_free((LDC_BIN_HANDLE)tldc_bin);
if (err_state != MI_EPTZ_ERR_NONE)
{
printf("[MI EPTZ ERR] = %d !! \n", err_state);
}*/
//release working buffer
free(pWorkingBuffer);
return 0;
}
MI_S32 ST_GetLdcBinBuffer(MI_S32 s32Cfg_Param, char *pCfgFilePath, mi_eptz_config_param *ptconfig_para, MI_U32 *pu32ViewNum, LDC_BIN_HANDLE *ptldc_bin, MI_U32 *pu32LdcBinSize, MI_S32 *ps32Rot)
{
MI_U8 i =0;
MI_U32 u32ViewNum = 0;
if(s32Cfg_Param == 0)
{
ST_Parse_LibarayCfgFilePath(pCfgFilePath, ptconfig_para);
u32ViewNum = ST_GetLdcCfgViewNum(ptconfig_para->ldc_mode);
for(i=0; i<u32ViewNum; i++)
{
ST_Libaray_CreatBin(i, ptconfig_para, &ptldc_bin[i], &pu32LdcBinSize[i], ps32Rot[i]);
}
*pu32ViewNum = u32ViewNum;
}
else
{
ST_ReadLdcTableBin(pCfgFilePath, ptldc_bin, pu32LdcBinSize);
*pu32ViewNum = 1;
}
return 0;
}
MI_S32 ST_SetLdcOnOff(MI_U32 u32SensorNum)
{
MI_S32 s32LdcOnoff = 0;
MI_VPE_ChannelPara_t stVpeChnParam;
memset(&stVpeChnParam, 0x0, sizeof(MI_VPE_ChannelPara_t));
MI_S32 s32Channelid = 0;
if(u32SensorNum > 1)
{
printf("select channel id:");
scanf("%d", &s32Channelid);
ST_Flush();
if(s32Channelid >= ST_MAX_SENSOR_NUM)
{
printf("chnid %d > max %d \n", s32Channelid, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
s32Channelid = 0;
}
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[s32Channelid];
printf("Set Ldc ON(1), OFF(0): \n");
scanf("%d", &s32LdcOnoff);
ST_Flush();
if(s32LdcOnoff == TRUE && pstVpeChnattr->bEnLdc == FALSE)
{
printf("ldc onoff %d, before enldc %d need set bin path \n", s32LdcOnoff, pstVpeChnattr->bEnLdc);
printf("set Ldc libaray cfg path: ");
scanf("%s", pstVpeChnattr->LdcCfgbin_Path);
ST_Flush();
ST_ReadLdcTableBin(pstVpeChnattr->LdcCfgbin_Path, &pstVpeChnattr->ldcBinBuffer[0], &pstVpeChnattr->u32LdcBinSize[0]);
}
MI_VPE_StopChannel(s32Channelid);
MI_VPE_GetChannelParam(s32Channelid, &stVpeChnParam);
printf("get channel param benldc %d, bmirror %d, bflip %d, e3dnrlevel %d, hdrtype %d \n",
stVpeChnParam.bEnLdc, stVpeChnParam.bMirror,stVpeChnParam.bFlip,stVpeChnParam.e3DNRLevel,stVpeChnParam.eHDRType);
stVpeChnParam.bEnLdc = s32LdcOnoff;
MI_VPE_SetChannelParam(s32Channelid, &stVpeChnParam);
if(s32LdcOnoff == TRUE && pstVpeChnattr->bEnLdc == FALSE)
{
MI_VPE_LDCBegViewConfig(s32Channelid);
MI_VPE_LDCSetViewConfig(s32Channelid, pstVpeChnattr->ldcBinBuffer[0], pstVpeChnattr->u32LdcBinSize[0]);
MI_VPE_LDCEndViewConfig(s32Channelid);
//free(pstVpeChnattr->ldcBinBuffer);
if(mi_eptz_buffer_free(pstVpeChnattr->ldcBinBuffer[0]) != MI_EPTZ_ERR_NONE)
{
printf("[MI EPTZ ERR] %d !! \n", __LINE__);
}
pstVpeChnattr->bEnLdc = TRUE;
}
MI_VPE_StartChannel(s32Channelid);
return 0;
}
void * ST_GetVpeOutputDataThread(void * args)
{
MI_SYS_BufInfo_t stBufInfo;
MI_SYS_BUF_HANDLE hHandle;
MI_U8 u8Params = *((MI_U8 *)(args));
MI_U8 u8Chnid = u8Params / ST_MAX_PORT_NUM;
MI_U8 u8Portid = u8Params % ST_MAX_PORT_NUM;
FILE *fp = NULL;
ST_VpePortAttr_t *pstVpePortAttr = &gstVpeChnattr[u8Chnid].stVpePortAttr[u8Portid];
MI_BOOL bFileOpen = FALSE;
MI_SYS_ChnPort_t stChnPort;
memset(&stChnPort, 0x0, sizeof(MI_SYS_ChnPort_t));
stChnPort.eModId = E_MI_MODULE_ID_VPE;
stChnPort.u32DevId = 0;
stChnPort.u32ChnId = u8Chnid;
stChnPort.u32PortId = u8Portid;
if(pstVpePortAttr->bUsed == TRUE)
{
MI_SYS_SetChnOutputPortDepth(&stChnPort, 1, 4);
}
while (!bExit)
{
pthread_mutex_lock(&pstVpePortAttr->Portmutex);
if(pstVpePortAttr->s32DumpBuffNum > 0 && bFileOpen == FALSE)
{
fp = fopen(pstVpePortAttr->FilePath ,"wb");
if(fp == NULL)
{
printf("file %s open fail\n", pstVpePortAttr->FilePath);
pstVpePortAttr->s32DumpBuffNum = 0;\
pthread_mutex_unlock(&pstVpePortAttr->Portmutex);
continue;
}
else
{
bFileOpen = TRUE;
}
}
if(pstVpePortAttr->bUsed == TRUE)
{
if (MI_SUCCESS == MI_SYS_ChnOutputPortGetBuf(&stChnPort, &stBufInfo, &hHandle))
{
//printf("get out success \n");
if(pstVpePortAttr->s32DumpBuffNum > 0)
{
pstVpePortAttr->s32DumpBuffNum--;
printf(
"=======begin writ port %d file id %d, file path %s, bufsize %d, stride %d, height %d\n", u8Portid, pstVpePortAttr->s32DumpBuffNum, pstVpePortAttr->FilePath,
stBufInfo.stFrameData.u32BufSize,stBufInfo.stFrameData.u32Stride[0], stBufInfo.stFrameData.u16Height);
fwrite(stBufInfo.stFrameData.pVirAddr[0], stBufInfo.stFrameData.u32BufSize, 1, fp);
printf(
"=======end writ port %d file id %d, file path %s \n", u8Portid, pstVpePortAttr->s32DumpBuffNum, pstVpePortAttr->FilePath);
}
//printf("begin release out \n");
MI_SYS_ChnOutputPortPutBuf(hHandle);
//printf("end release out \n");
}
}
if(bFileOpen == TRUE && pstVpePortAttr->s32DumpBuffNum == 0)
{
fclose(fp);
bFileOpen = FALSE;
}
pthread_mutex_unlock(&pstVpePortAttr->Portmutex);
usleep(10*1000);
}
return NULL;
}
void *ST_IQthread(void * args)
{
MI_VIF_ChnPortAttr_t stVifAttr;
MI_VPE_ChannelPara_t stVpeParam;
MI_VPE_HDRType_e eLastHdrType = E_MI_VPE_HDR_TYPE_MAX;
MI_ISP_IQ_PARAM_INIT_INFO_TYPE_t status;
MI_U8 u8ispreadycnt = 0;
memset(&stVifAttr, 0x0, sizeof(MI_VIF_ChnPortAttr_t));
memset(&stVpeParam, 0x0, sizeof(MI_VPE_ChannelPara_t));
MI_IQSERVER_Open(1920, 1080, 0);
while(1)
{
if(u8ispreadycnt > 100)
{
printf("%s:%d, isp ready time out \n", __FUNCTION__, __LINE__);
u8ispreadycnt = 0;
}
MI_ISP_IQ_GetParaInitStatus(0, &status);
if(status.stParaAPI.bFlag != 1)
{
usleep(10*1000);
u8ispreadycnt++;
continue;
}
u8ispreadycnt = 0;
MI_VPE_GetChannelParam(0, &stVpeParam);
if(eLastHdrType != stVpeParam.eHDRType)
{
printf("hdr type change before %d, current %d, load api bin\n", eLastHdrType, stVpeParam.eHDRType);
MI_ISP_API_CmdLoadBinFile(0, (char *)((stVpeParam.eHDRType>0) ? HDR_PATH : NONHDR_PATH), 1234);
}
eLastHdrType = stVpeParam.eHDRType;
usleep(10*1000);
}
return NULL;
}
void *ST_SendVpeBufthread(void * args)
{
MI_SYS_ChnPort_t stVpeChnInput;
MI_SYS_BUF_HANDLE hHandle = 0;
MI_SYS_BufConf_t stBufConf;
MI_SYS_BufInfo_t stBufInfo;
struct timeval stTv;
MI_U16 u16Width = 1920, u16Height = 1080;
FILE *fp = NULL;
memset(&stVpeChnInput, 0x0, sizeof(MI_SYS_ChnPort_t));
memset(&stBufConf, 0x0, sizeof(MI_SYS_BufConf_t));
memset(&stBufInfo, 0x0, sizeof(MI_SYS_BufInfo_t));
stVpeChnInput.eModId = E_MI_MODULE_ID_VPE;
stVpeChnInput.u32DevId = 0;
stVpeChnInput.u32ChnId = 0;
stVpeChnInput.u32PortId = 0;
fp = fopen("/mnt/vpeport0_1920x1080_pixel0_737.raw","rb");
if(fp == NULL)
{
printf("file %s open fail\n", "/mnt/vpeport0_1920x1080_pixel0_737.raw");
return 0;
}
while(1)
{
stBufConf.eBufType = E_MI_SYS_BUFDATA_FRAME;
gettimeofday(&stTv, NULL);
stBufConf.u64TargetPts = stTv.tv_sec*1000000 + stTv.tv_usec;
stBufConf.stFrameCfg.eFormat = E_MI_SYS_PIXEL_FRAME_YUV422_YUYV;
stBufConf.stFrameCfg.eFrameScanMode = E_MI_SYS_FRAME_SCAN_MODE_PROGRESSIVE;
stBufConf.stFrameCfg.u16Width = u16Width;
stBufConf.stFrameCfg.u16Height = u16Height;
if(MI_SUCCESS == MI_SYS_ChnInputPortGetBuf(&stVpeChnInput,&stBufConf,&stBufInfo,&hHandle,0))
{
if(fread(stBufInfo.stFrameData.pVirAddr[0], u16Width*u16Height*2, 1, fp) <= 0)
{
fseek(fp, 0, SEEK_SET);
}
MI_SYS_ChnInputPortPutBuf(hHandle,&stBufInfo, FALSE);
}
}
}
MI_S32 ST_BaseModuleInit(MI_SNR_PAD_ID_e eSnrPad)
{
MI_U32 u32CapWidth = 0, u32CapHeight = 0;
MI_VIF_FrameRate_e eFrameRate = E_MI_VIF_FRAMERATE_FULL;
MI_SYS_PixelFormat_e ePixFormat;
MI_SNR_PADInfo_t stPad0Info;
MI_SNR_PlaneInfo_t stSnrPlane0Info;
MI_SNR_PAD_ID_e eSnrPadId = eSnrPad;
MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev;
MI_VIF_CHN vifChn = vifDev*4;
MI_VPE_CHANNEL vpechn = gstVifAttr[vifDev].u32BindVpeChan;
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[vpechn];
ST_Vif_Attr_t *pstVifDevAttr = &gstVifAttr[vifDev];
MI_U8 i=0;
memset(&stPad0Info, 0x0, sizeof(MI_SNR_PADInfo_t));
if(E_MI_VPE_HDR_TYPE_OFF== pstVpeChnattr->eHdrType
|| E_MI_VPE_HDR_TYPE_EMBEDDED == pstVpeChnattr->eHdrType
|| E_MI_VPE_HDR_TYPE_LI== pstVpeChnattr->eHdrType)
{
MI_SNR_SetPlaneMode(eSnrPad, FALSE);
}
else
{
MI_SNR_SetPlaneMode(eSnrPad, TRUE);
}
MI_U32 u32ResCount =0;
MI_U8 u8ResIndex =0;
MI_SNR_Res_t stRes;
MI_U8 u8ChocieRes =0;
MI_S32 s32Input =0;
memset(&stRes, 0x0, sizeof(MI_SNR_Res_t));
MI_SNR_QueryResCount(eSnrPadId, &u32ResCount);
for(u8ResIndex=0; u8ResIndex < u32ResCount; u8ResIndex++)
{
MI_SNR_GetRes(eSnrPadId, u8ResIndex, &stRes);
printf("index %d, Crop(%d,%d,%d,%d), outputsize(%d,%d), maxfps %d, minfps %d, ResDesc %s\n",
u8ResIndex,
stRes.stCropRect.u16X, stRes.stCropRect.u16Y, stRes.stCropRect.u16Width,stRes.stCropRect.u16Height,
stRes.stOutputSize.u16Width, stRes.stOutputSize.u16Height,
stRes.u32MaxFps,stRes.u32MinFps,
stRes.strResDesc);
}
printf("choice which resolution use, cnt %d\n", u32ResCount);
do
{
scanf("%d", &s32Input);
u8ChocieRes = (MI_U8)s32Input;
ST_Flush();
MI_SNR_QueryResCount(eSnrPadId, &u32ResCount);
if(u8ChocieRes >= u32ResCount)
{
printf("choice err res %d > =cnt %d\n", u8ChocieRes, u32ResCount);
}
}while(u8ChocieRes >= u32ResCount);
printf("You select %d res\n", u8ChocieRes);
MI_SNR_SetRes(eSnrPadId,u8ChocieRes);
MI_SNR_Enable(eSnrPadId);
MI_SNR_GetPadInfo(eSnrPadId, &stPad0Info);
MI_SNR_GetPlaneInfo(eSnrPadId, 0, &stSnrPlane0Info);
u32CapWidth = stSnrPlane0Info.stCapRect.u16Width;
u32CapHeight = stSnrPlane0Info.stCapRect.u16Height;
eFrameRate = E_MI_VIF_FRAMERATE_FULL;
ePixFormat = (MI_SYS_PixelFormat_e)RGB_BAYER_PIXEL(stSnrPlane0Info.ePixPrecision, stSnrPlane0Info.eBayerId);;
/************************************************
Step1: init SYS
*************************************************/
STCHECKRESULT(ST_Sys_Init());
/*
stSnrPlane0Info.stCapRect.u16X = 0;
stSnrPlane0Info.stCapRect.u16Y = 0;
stSnrPlane0Info.stCapRect.u16Width = 1920;
stSnrPlane0Info.stCapRect.u16Height = 1080;
ePixFormat = E_MI_SYS_PIXEL_FRAME_YUV422_YUYV;
pstVifDevAttr->eWorkMode = E_MI_VIF_WORK_MODE_RGB_FRAMEMODE;
pstVpeChnattr->eRunningMode = E_MI_VPE_RUN_DVR_MODE;
*/
/************************************************
Step2: init VIF(for IPC, only one dev)
*************************************************/
MI_VIF_DevAttr_t stDevAttr;
memset(&stDevAttr, 0x0, sizeof(MI_VIF_DevAttr_t));
stDevAttr.eIntfMode = stPad0Info.eIntfMode;
stDevAttr.eWorkMode = pstVifDevAttr->eWorkMode;
stDevAttr.eHDRType = (MI_VIF_HDRType_e)pstVpeChnattr->eHdrType;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656)
stDevAttr.eClkEdge = stPad0Info.unIntfAttr.stBt656Attr.eClkEdge;
else
stDevAttr.eClkEdge = E_MI_VIF_CLK_EDGE_DOUBLE;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_MIPI)
stDevAttr.eDataSeq =stPad0Info.unIntfAttr.stMipiAttr.eDataYUVOrder;
else
stDevAttr.eDataSeq = E_MI_VIF_INPUT_DATA_YUYV;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656)
memcpy(&stDevAttr.stSyncAttr, &stPad0Info.unIntfAttr.stBt656Attr.stSyncAttr, sizeof(MI_VIF_SyncAttr_t));
stDevAttr.eBitOrder = E_MI_VIF_BITORDER_NORMAL;
ExecFunc(MI_VIF_SetDevAttr(vifDev, &stDevAttr), MI_SUCCESS);
ExecFunc(MI_VIF_EnableDev(vifDev), MI_SUCCESS);
ST_VIF_PortInfo_T stVifPortInfoInfo;
memset(&stVifPortInfoInfo, 0, sizeof(ST_VIF_PortInfo_T));
stVifPortInfoInfo.u32RectX = stSnrPlane0Info.stCapRect.u16X;
stVifPortInfoInfo.u32RectY = stSnrPlane0Info.stCapRect.u16Y;
stVifPortInfoInfo.u32RectWidth = u32CapWidth;
stVifPortInfoInfo.u32RectHeight = u32CapHeight;
stVifPortInfoInfo.u32DestWidth = u32CapWidth;
stVifPortInfoInfo.u32DestHeight = u32CapHeight;
stVifPortInfoInfo.eFrameRate = eFrameRate;
stVifPortInfoInfo.ePixFormat = ePixFormat;
STCHECKRESULT(ST_Vif_CreatePort(vifChn, 0, &stVifPortInfoInfo));
STCHECKRESULT(ST_Vif_StartPort(0, vifChn, 0));
/************************************************
Step3: init VPE (create one VPE)
*************************************************/
MI_VPE_ChannelAttr_t stChannelVpeAttr;
MI_VPE_ChannelPara_t stChannelVpeParam;
memset(&stChannelVpeAttr, 0, sizeof(MI_VPE_ChannelAttr_t));
memset(&stChannelVpeParam, 0x00, sizeof(MI_VPE_ChannelPara_t));
stChannelVpeParam.eHDRType = pstVpeChnattr->eHdrType;
stChannelVpeParam.e3DNRLevel = pstVpeChnattr->e3DNRLevel;
stChannelVpeParam.bMirror = pstVpeChnattr->bChnMirror;
stChannelVpeParam.bFlip = pstVpeChnattr->bChnFlip;
MI_VPE_SetChannelParam(vpechn, &stChannelVpeParam);
stChannelVpeAttr.u16MaxW = u32CapWidth;
stChannelVpeAttr.u16MaxH = u32CapHeight;
stChannelVpeAttr.ePixFmt = ePixFormat;
stChannelVpeAttr.eRunningMode = pstVpeChnattr->eRunningMode;
stChannelVpeAttr.eSensorBindId = (MI_VPE_SensorChannel_e)(eSnrPadId+1);
stChannelVpeAttr.bEnLdc = pstVpeChnattr->bEnLdc;
stChannelVpeAttr.u32ChnPortMode = pstVpeChnattr->u32ChnPortMode;
stChannelVpeAttr.eHDRType = pstVpeChnattr->eHdrType;
ExecFunc(MI_VPE_CreateChannel(vpechn, &stChannelVpeAttr), MI_VPE_OK);
if(pstVpeChnattr->bEnLdc == TRUE
&& pstVpeChnattr->ldcBinBuffer[0] != NULL)
{
MI_VPE_LDCBegViewConfig(vpechn);
for(i=0; i<pstVpeChnattr->u32ViewNum; i++)
{
MI_VPE_LDCSetViewConfig(vpechn, pstVpeChnattr->ldcBinBuffer[i], pstVpeChnattr->u32LdcBinSize[i]);
//free(pstVpeChnattr->ldcBinBuffer);
if(mi_eptz_buffer_free(pstVpeChnattr->ldcBinBuffer[i]) != MI_EPTZ_ERR_NONE)
{
printf("[MI EPTZ ERR] %d !! \n", __LINE__);
}
}
MI_VPE_LDCEndViewConfig(vpechn);
}
else
printf("##############benldc %d, ldc bin buffer %p \n",pstVpeChnattr->bEnLdc, pstVpeChnattr->ldcBinBuffer);
STCHECKRESULT(MI_VPE_SetChannelRotation(vpechn, pstVpeChnattr->eVpeRotate));
STCHECKRESULT(MI_VPE_SetChannelCrop(vpechn, &pstVpeChnattr->stVpeChnCrop));
STCHECKRESULT(ST_Vpe_StartChannel(vpechn));
for(i=0; i<ST_MAX_PORT_NUM; i++)
{
MI_VPE_PortMode_t stVpeMode;
memset(&stVpeMode, 0, sizeof(stVpeMode));
if(pstVpeChnattr->stVpePortAttr[i].bUsed == TRUE)
{
MI_VPE_SetPortCrop(vpechn, i, &pstVpeChnattr->stVpePortAttr[i].stPortCrop);
stVpeMode.u16Width = pstVpeChnattr->stVpePortAttr[i].stPortSize.u16Width;
stVpeMode.u16Height = pstVpeChnattr->stVpePortAttr[i].stPortSize.u16Height;
stVpeMode.ePixelFormat = pstVpeChnattr->stVpePortAttr[i].ePixelFormat;
stVpeMode.eCompressMode = E_MI_SYS_COMPRESS_MODE_NONE;
stVpeMode.bMirror =pstVpeChnattr->stVpePortAttr[i].bMirror;
stVpeMode.bFlip = pstVpeChnattr->stVpePortAttr[i].bFlip;
ExecFunc(MI_VPE_SetPortMode(vpechn, i, &stVpeMode), MI_VPE_OK);
ExecFunc(MI_VPE_EnablePort(vpechn, i), MI_VPE_OK);
}
}
/************************************************
Step1: bind VIF->VPE
*************************************************/
ST_Sys_BindInfo_T stBindInfo;
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF;
stBindInfo.stSrcChnPort.u32DevId = vifDev;
stBindInfo.stSrcChnPort.u32ChnId = vifChn;
stBindInfo.stSrcChnPort.u32PortId = 0;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stDstChnPort.u32DevId = 0;
stBindInfo.stDstChnPort.u32ChnId = vpechn;
stBindInfo.stDstChnPort.u32PortId = 0;
stBindInfo.u32SrcFrmrate = 30;
stBindInfo.u32DstFrmrate = 30;
stBindInfo.eBindType = pstVifDevAttr->eBindType;
STCHECKRESULT(ST_Sys_Bind(&stBindInfo));
return MI_SUCCESS;
}
MI_S32 ST_BaseModuleUnInit(MI_SNR_PAD_ID_e eSnrPad)
{
MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev;
MI_VIF_CHN vifChn = vifDev*4;
MI_VPE_CHANNEL vpechn = gstVifAttr[vifDev].u32BindVpeChan;
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[vpechn];
MI_U32 i = 0;
ST_Sys_BindInfo_T stBindInfo;
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF;
stBindInfo.stSrcChnPort.u32DevId = vifDev;
stBindInfo.stSrcChnPort.u32ChnId = vifChn;
stBindInfo.stSrcChnPort.u32PortId = 0;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stDstChnPort.u32DevId = 0;
stBindInfo.stDstChnPort.u32ChnId = vpechn;
stBindInfo.stDstChnPort.u32PortId = 0;
stBindInfo.u32SrcFrmrate = 30;
stBindInfo.u32DstFrmrate = 30;
STCHECKRESULT(ST_Sys_UnBind(&stBindInfo));
for(i = 0; i < ST_MAX_PORT_NUM; i ++)
{
if(pstVpeChnattr->stVpePortAttr[i].bUsed == TRUE)
{
STCHECKRESULT(ST_Vpe_StopPort(vpechn, i));
}
}
/************************************************
Step2: destory VPE
*************************************************/
STCHECKRESULT(ST_Vpe_StopChannel(vpechn));
STCHECKRESULT(ST_Vpe_DestroyChannel(vpechn));
/************************************************
Step3: destory VIF
*************************************************/
STCHECKRESULT(ST_Vif_StopPort(vifChn, 0));
STCHECKRESULT(ST_Vif_DisableDev(vifDev));
MI_SNR_Disable(eSnrPad);
/************************************************
Step4: destory SYS
*************************************************/
STCHECKRESULT(ST_Sys_Exit());
return MI_SUCCESS;
}
MI_S32 ST_VencStart(MI_U32 u32MaxVencWidth, MI_U32 u32MaxVencHeight, MI_U32 u32VpeChn)
{
MI_U32 u32VenBitRate = 0;
MI_U32 i = 0;
ST_Sys_BindInfo_T stBindInfo;
MI_U32 u32DevId = -1;
MI_VENC_ChnAttr_t stChnAttr;
for(i = 0; i < ST_MAX_PORT_NUM; i ++)
{
MI_U32 u32VencChn = gstVpeChnattr[u32VpeChn].stVpePortAttr[i].u32BindVencChan;
ST_VencAttr_t *pstStreamAttr = &gstVencattr[u32VencChn];
memset(&stChnAttr, 0, sizeof(MI_VENC_ChnAttr_t));
if(pstStreamAttr->bUsed != TRUE)
continue;
u32VenBitRate = ((pstStreamAttr->u32Width * pstStreamAttr->u32Height + 500000)/1000000)*1024*1024;
DBG_INFO("chn %d, pichwidth %d, height %d, MaxWidth %d, MaxHeight %d \n", u32VencChn,
pstStreamAttr->u32Width, pstStreamAttr->u32Height, u32MaxVencWidth, u32MaxVencHeight);
if(pstStreamAttr->eType == E_MI_VENC_MODTYPE_H264E)
{
stChnAttr.stVeAttr.stAttrH264e.u32PicWidth = pstStreamAttr->u32Width;
stChnAttr.stVeAttr.stAttrH264e.u32PicHeight = pstStreamAttr->u32Height;
stChnAttr.stVeAttr.stAttrH264e.u32MaxPicWidth = u32MaxVencWidth;
stChnAttr.stVeAttr.stAttrH264e.u32BFrameNum = 2;
stChnAttr.stVeAttr.stAttrH264e.bByFrame = TRUE;
stChnAttr.stVeAttr.stAttrH264e.u32MaxPicHeight = u32MaxVencHeight;
stChnAttr.stRcAttr.eRcMode = E_MI_VENC_RC_MODE_H264CBR;
stChnAttr.stRcAttr.stAttrH264Cbr.u32BitRate = u32VenBitRate;
stChnAttr.stRcAttr.stAttrH264Cbr.u32FluctuateLevel = 0;
stChnAttr.stRcAttr.stAttrH264Cbr.u32Gop = 30;
stChnAttr.stRcAttr.stAttrH264Cbr.u32SrcFrmRateNum = 30;
stChnAttr.stRcAttr.stAttrH264Cbr.u32SrcFrmRateDen = 1;
stChnAttr.stRcAttr.stAttrH264Cbr.u32StatTime = 0;
}
else if(pstStreamAttr->eType == E_MI_VENC_MODTYPE_H265E)
{
stChnAttr.stVeAttr.stAttrH265e.u32PicWidth = pstStreamAttr->u32Width;
stChnAttr.stVeAttr.stAttrH265e.u32PicHeight = pstStreamAttr->u32Height;
stChnAttr.stVeAttr.stAttrH265e.u32MaxPicWidth = u32MaxVencWidth;
stChnAttr.stVeAttr.stAttrH265e.u32MaxPicHeight = u32MaxVencHeight;
stChnAttr.stVeAttr.stAttrH265e.bByFrame = TRUE;
stChnAttr.stRcAttr.eRcMode = E_MI_VENC_RC_MODE_H265CBR;
stChnAttr.stRcAttr.stAttrH265Cbr.u32BitRate = u32VenBitRate;
stChnAttr.stRcAttr.stAttrH265Cbr.u32SrcFrmRateNum = 30;
stChnAttr.stRcAttr.stAttrH265Cbr.u32SrcFrmRateDen = 1;
stChnAttr.stRcAttr.stAttrH265Cbr.u32Gop = 30;
stChnAttr.stRcAttr.stAttrH265Cbr.u32FluctuateLevel = 0;
stChnAttr.stRcAttr.stAttrH265Cbr.u32StatTime = 0;
}
else if(pstStreamAttr->eType == E_MI_VENC_MODTYPE_JPEGE)
{
stChnAttr.stVeAttr.eType = E_MI_VENC_MODTYPE_JPEGE;
stChnAttr.stRcAttr.eRcMode = E_MI_VENC_RC_MODE_MJPEGFIXQP;
stChnAttr.stVeAttr.stAttrJpeg.u32PicWidth = pstStreamAttr->u32Width;
stChnAttr.stVeAttr.stAttrJpeg.u32PicHeight = pstStreamAttr->u32Height;
stChnAttr.stVeAttr.stAttrJpeg.u32MaxPicWidth = u32MaxVencWidth;
stChnAttr.stVeAttr.stAttrJpeg.u32MaxPicHeight = u32MaxVencHeight;
}
stChnAttr.stVeAttr.eType = pstStreamAttr->eType;
u32VencChn = pstStreamAttr->vencChn;
STCHECKRESULT(ST_Venc_CreateChannel(u32VencChn, &stChnAttr));
ExecFunc(MI_VENC_GetChnDevid(u32VencChn, &u32DevId), MI_SUCCESS);
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stSrcChnPort.u32DevId = 0;
stBindInfo.stSrcChnPort.u32ChnId = pstStreamAttr->u32BindVpeChn;
stBindInfo.stSrcChnPort.u32PortId = pstStreamAttr->u32BindVpePort;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VENC;
stBindInfo.stDstChnPort.u32DevId = u32DevId;
stBindInfo.stDstChnPort.u32ChnId = u32VencChn;
stBindInfo.stDstChnPort.u32PortId = 0;
stBindInfo.u32SrcFrmrate = 30;
stBindInfo.u32DstFrmrate = 30;
stBindInfo.eBindType = pstStreamAttr->eBindType;
stBindInfo.u32BindParam = pstStreamAttr->u32BindParam;
STCHECKRESULT(ST_Sys_Bind(&stBindInfo));
STCHECKRESULT(ST_Venc_StartChannel(u32VencChn));
pstStreamAttr->bStart = TRUE;
}
return MI_SUCCESS;
}
MI_S32 ST_VencStop(MI_U32 u32VpeChn)
{
MI_U32 i = 0;
ST_Sys_BindInfo_T stBindInfo;
MI_VENC_CHN VencChn = 0;
MI_U32 u32DevId = -1;
for(i = 0; i < ST_MAX_PORT_NUM; i ++)
{
MI_U32 u32VencChn = gstVpeChnattr[u32VpeChn].stVpePortAttr[i].u32BindVencChan;
ST_VencAttr_t *pstStreamAttr = &gstVencattr[u32VencChn];
if(pstStreamAttr->bUsed != TRUE)
continue;
VencChn = pstStreamAttr->vencChn;
ExecFunc(MI_VENC_GetChnDevid(VencChn, &u32DevId), MI_SUCCESS);
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stSrcChnPort.u32DevId = 0;
stBindInfo.stSrcChnPort.u32ChnId = pstStreamAttr->u32BindVpeChn;
stBindInfo.stSrcChnPort.u32PortId = pstStreamAttr->u32BindVpePort;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VENC;
stBindInfo.stDstChnPort.u32DevId = u32DevId;
stBindInfo.stDstChnPort.u32ChnId = VencChn;
stBindInfo.stDstChnPort.u32PortId = 0;
stBindInfo.u32SrcFrmrate = 30;
stBindInfo.u32DstFrmrate = 30;
STCHECKRESULT(ST_Sys_UnBind(&stBindInfo));
STCHECKRESULT(ST_Venc_StopChannel(VencChn));
STCHECKRESULT(ST_Venc_DestoryChannel(VencChn));
pstStreamAttr->bStart = FALSE;
}
return MI_SUCCESS;
}
void ST_SetArgs(MI_U32 u32SensorId)
{
MI_S32 s32HDRtype = 0;
MI_S32 s323DNRLevel = 0;
MI_S32 s32Rotation = 0;
MI_S32 s32ChannelCropX =0, s32ChannelCropY=0,s32ChannelCropW=0,s32ChannelCropH =0;
MI_S32 s32bEnLdc =0;
MI_S32 s32ChnPortMode = 0, s32PortSelect =0;
MI_U8 i=0;
MI_U32 u32VifDev = gstSensorAttr[u32SensorId].u32BindVifDev;
MI_U32 u32VpeChn = gstVifAttr[u32VifDev].u32BindVpeChan;
DBG_INFO("set vpe channelid %d \n", u32VpeChn);
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[u32VpeChn];
printf("preview by venc ?(0: write file, 1:preview use rtsp)\n");
scanf("%d", &gbPreviewByVenc);
ST_Flush();
printf("Use HDR ?\n 0 not use, 1 use VC, 2 use DOL, 3 use EMBEDDED, 4 use LI\n");
printf("sony sensor(ex imx307) use DOL, sc sensor(ex sc4238) use VC\n");
scanf("%d", &s32HDRtype);
ST_Flush();
printf("3dnr level(0~2):");
scanf("%d", &s323DNRLevel);
ST_Flush();
printf("rotation(0:0, 1:90, 2:180, 3:270, 4:mirror, 5:flip):");
scanf("%d", &s32Rotation);
ST_Flush();
printf("Channel Crop x:");
scanf("%d", &s32ChannelCropX);
ST_Flush();
printf("Channel Crop y:");
scanf("%d", &s32ChannelCropY);
ST_Flush();
printf("Channel Crop width:");
scanf("%d", &s32ChannelCropW);
ST_Flush();
printf("Channel Crop height:");
scanf("%d", &s32ChannelCropH);
ST_Flush();
printf("bEnLdc:");
scanf("%d", &s32bEnLdc);
ST_Flush();
if(s32bEnLdc == TRUE)
{
printf("set Ldc libaray cfg path: ");
scanf("%s", pstVpeChnattr->LdcCfgbin_Path);
ST_Flush();
}
pstVpeChnattr->e3DNRLevel = (MI_VPE_3DNR_Level_e)s323DNRLevel;
pstVpeChnattr->eHdrType = (MI_VPE_HDRType_e)s32HDRtype;
if(s32Rotation < 4)
pstVpeChnattr->eVpeRotate = (MI_SYS_Rotate_e)s32Rotation;
else if(s32Rotation == 4)
{
pstVpeChnattr->bChnMirror = TRUE;
pstVpeChnattr->bChnFlip = FALSE;
}
else if(s32Rotation == 5)
{
pstVpeChnattr->bChnMirror = FALSE;
pstVpeChnattr->bChnFlip = TRUE;
}
pstVpeChnattr->stOrgVpeChnCrop.u16X = s32ChannelCropX;
pstVpeChnattr->stOrgVpeChnCrop.u16Y = s32ChannelCropY;
pstVpeChnattr->stOrgVpeChnCrop.u16Width = s32ChannelCropW;
pstVpeChnattr->stOrgVpeChnCrop.u16Height = s32ChannelCropH;
pstVpeChnattr->bEnLdc = s32bEnLdc;
if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90
|| pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270)
{
pstVpeChnattr->stVpeChnCrop.u16X = pstVpeChnattr->stOrgVpeChnCrop.u16Y;
pstVpeChnattr->stVpeChnCrop.u16Y = pstVpeChnattr->stOrgVpeChnCrop.u16X;
pstVpeChnattr->stVpeChnCrop.u16Width = pstVpeChnattr->stOrgVpeChnCrop.u16Height;
pstVpeChnattr->stVpeChnCrop.u16Height = pstVpeChnattr->stOrgVpeChnCrop.u16Width;
}
else
{
pstVpeChnattr->stVpeChnCrop.u16X = pstVpeChnattr->stOrgVpeChnCrop.u16X;
pstVpeChnattr->stVpeChnCrop.u16Y = pstVpeChnattr->stOrgVpeChnCrop.u16Y;
pstVpeChnattr->stVpeChnCrop.u16Width = pstVpeChnattr->stOrgVpeChnCrop.u16Width;
pstVpeChnattr->stVpeChnCrop.u16Height = pstVpeChnattr->stOrgVpeChnCrop.u16Height;
}
for(i=0; i<ST_MAX_SCL_NUM; i++)
{
printf("port %d 0:real, 1:frame:", i);
scanf("%d", &s32PortSelect);
ST_Flush();
if(s32PortSelect == 1)
{
switch(i)
{
case 0:
s32ChnPortMode |= E_MI_VPE_ZOOM_LDC_PORT0;
break;
case 1:
s32ChnPortMode |= E_MI_VPE_ZOOM_LDC_PORT1;
break;
case 2:
s32ChnPortMode |= E_MI_VPE_ZOOM_LDC_PORT2;
break;
case 3:
s32ChnPortMode = s32ChnPortMode;
break;
default:
s32ChnPortMode = 0;
break;
}
}
}
for(i=0; i<ST_MAX_PORT_NUM; i++)
{
MI_S32 s32BusePort = 0;
MI_S32 s32PortCropX =0, s32PortCropY=0,s32PortCropW=0,s32PortCropH =0;
MI_S32 s32PortPixelFormat =0;
MI_S32 s32PortMirror=0, s32PortFlip=0;
MI_S32 s32PortW=0, s32PortH=0;
printf("use port%d ?(0,not use, 1 use):", i);
scanf("%d", &s32BusePort);
ST_Flush();
if(s32BusePort > 0)
{
ST_VpePortAttr_t *pstVpePortAttr = &pstVpeChnattr->stVpePortAttr[i];
if(i < ST_MAX_SCL_NUM)
{
printf("port %d port crop x:", i);
scanf("%d", &s32PortCropX);
ST_Flush();
printf("port %d port crop y:", i);
scanf("%d", &s32PortCropY);
ST_Flush();
printf("port %d port crop width:", i);
scanf("%d", &s32PortCropW);
ST_Flush();
printf("port %d port crop height:", i);
scanf("%d", &s32PortCropH);
ST_Flush();
printf("port %d bmirror:", i);
scanf("%d", &s32PortMirror);
ST_Flush();
printf("port %d bflip:", i);
scanf("%d", &s32PortFlip);
ST_Flush();
printf("port %d port width:", i);
scanf("%d", &s32PortW);
ST_Flush();
printf("port %d port height:", i);
scanf("%d", &s32PortH);
ST_Flush();
}
else
{
MI_SNR_PlaneInfo_t stPlaneInfo;
memset(&stPlaneInfo, 0x0, sizeof(MI_SNR_PlaneInfo_t));
MI_SNR_GetPlaneInfo((MI_SNR_PAD_ID_e)u32SensorId, 0, &stPlaneInfo);
if(i==3)
{
s32PortW = stPlaneInfo.stCapRect.u16Width;
s32PortH = stPlaneInfo.stCapRect.u16Height;
}
else if(i==4)
{
s32PortW = stPlaneInfo.stCapRect.u16Width/2;
s32PortH = stPlaneInfo.stCapRect.u16Height/2;
}
}
if(gbPreviewByVenc > 0)
{
MI_S32 s32BindType =0;
MI_S32 eType = 0;
MI_U32 u32VencChnid = pstVpePortAttr->u32BindVencChan;
ST_VencAttr_t *pstVencAttr = &gstVencattr[u32VencChnid];
printf("vpe port bindtype venc ?\n0 frame mode, 1 ring mode, 2 imi mode, 3 ring mode(half)\n");
scanf("%d", &s32BindType);
ST_Flush();
if(s32BindType == 0)
{
pstVencAttr->eBindType = E_MI_SYS_BIND_TYPE_FRAME_BASE;
pstVencAttr->u32BindParam = 0;
}
else if(s32BindType == 1)
{
pstVencAttr->eBindType = E_MI_SYS_BIND_TYPE_HW_RING;
pstVencAttr->u32BindParam = s32PortH;
}
else if(s32BindType == 2)
{
pstVencAttr->eBindType = E_MI_SYS_BIND_TYPE_REALTIME;
pstVencAttr->u32BindParam = 0;
}
else if(s32BindType == 3)
{
pstVencAttr->eBindType = E_MI_SYS_BIND_TYPE_HW_RING;
pstVencAttr->u32BindParam = s32PortH/2;
}
printf("venc encode type ?\n 2 h264, 3 h265, 4 JPEG\n");
scanf("%d", &eType);
ST_Flush();
if(eType == 4)
{
pstVencAttr->eType = E_MI_VENC_MODTYPE_JPEGE;
if(pstVencAttr->eBindType == E_MI_SYS_BIND_TYPE_REALTIME)
s32PortPixelFormat = E_MI_SYS_PIXEL_FRAME_YUV422_YUYV;
else
s32PortPixelFormat = E_MI_SYS_PIXEL_FRAME_YUV_SEMIPLANAR_420;
}
else
{
pstVencAttr->eType = (MI_VENC_ModType_e)eType;
s32PortPixelFormat = E_MI_SYS_PIXEL_FRAME_YUV_SEMIPLANAR_420;
}
pstVencAttr->vencChn = u32VencChnid;
pstVencAttr->bUsed = TRUE;
sprintf(pstVencAttr->szStreamName, "video%d", u32VencChnid);
if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90
|| pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270)
{
pstVencAttr->u32Width = s32PortH;
pstVencAttr->u32Height = s32PortW;
}
else
{
pstVencAttr->u32Width = s32PortW;
pstVencAttr->u32Height = s32PortH;
}
pstVencAttr->u32BindVpeChn = u32VpeChn;
pstVencAttr->u32BindVpePort = i;
}
else
{
printf("port %d port pixel:", i);
printf("yuv422:0, argb8888:1, abgr8888:2, bgra8888:3, yuv420:11\n");
scanf("%d", &s32PortPixelFormat);
ST_Flush();
}
pstVpePortAttr->bMirror = s32PortMirror;
pstVpePortAttr->bFlip = s32PortFlip;
pstVpePortAttr->stOrigPortCrop.u16X = s32PortCropX;
pstVpePortAttr->stOrigPortCrop.u16Y = s32PortCropY;
pstVpePortAttr->stOrigPortCrop.u16Width = s32PortCropW;
pstVpePortAttr->stOrigPortCrop.u16Height = s32PortCropH;
pstVpePortAttr->stOrigPortSize.u16Width = s32PortW;
pstVpePortAttr->stOrigPortSize.u16Height = s32PortH;
if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90
|| pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270)
{
pstVpePortAttr->stPortSize.u16Width = pstVpePortAttr->stOrigPortSize.u16Height;
pstVpePortAttr->stPortSize.u16Height = pstVpePortAttr->stOrigPortSize.u16Width;
pstVpePortAttr->stPortCrop.u16X = pstVpePortAttr->stOrigPortCrop.u16Y;
pstVpePortAttr->stPortCrop.u16Y = pstVpePortAttr->stOrigPortCrop.u16X;
pstVpePortAttr->stPortCrop.u16Width = pstVpePortAttr->stOrigPortCrop.u16Height;
pstVpePortAttr->stPortCrop.u16Height = pstVpePortAttr->stOrigPortCrop.u16Width;
}
else
{
pstVpePortAttr->stPortSize.u16Width = pstVpePortAttr->stOrigPortSize.u16Width;
pstVpePortAttr->stPortSize.u16Height = pstVpePortAttr->stOrigPortSize.u16Height;
pstVpePortAttr->stPortCrop.u16X = pstVpePortAttr->stOrigPortCrop.u16X;
pstVpePortAttr->stPortCrop.u16Y = pstVpePortAttr->stOrigPortCrop.u16Y;
pstVpePortAttr->stPortCrop.u16Width = pstVpePortAttr->stOrigPortCrop.u16Width;
pstVpePortAttr->stPortCrop.u16Height = pstVpePortAttr->stOrigPortCrop.u16Height;
}
pstVpePortAttr->ePixelFormat = (MI_SYS_PixelFormat_e)s32PortPixelFormat;
pstVpePortAttr->bUsed = TRUE;
}
}
if((s32ChnPortMode & E_MI_VPE_ZOOM_LDC_PORT1)
|| (s32ChnPortMode & E_MI_VPE_ZOOM_LDC_PORT2))
{
s32ChnPortMode |= E_MI_VPE_ZOOM_LDC_PORT1 | E_MI_VPE_ZOOM_LDC_PORT2;
}
pstVpeChnattr->u32ChnPortMode = s32ChnPortMode;
printf("chnport mode %d \n", pstVpeChnattr->u32ChnPortMode);
if(pstVpeChnattr->bEnLdc == TRUE)
{
MI_U32 u32Cfg_Param = 0;
pstVpeChnattr->s32Rot[0] = 0;
pstVpeChnattr->s32Rot[1] = 90;
pstVpeChnattr->s32Rot[2] = 180;
pstVpeChnattr->s32Rot[3] = 270;
ST_GetLdcBinBuffer(u32Cfg_Param, pstVpeChnattr->LdcCfgbin_Path, &pstVpeChnattr->tconfig_para, &pstVpeChnattr->u32ViewNum, pstVpeChnattr->ldcBinBuffer, pstVpeChnattr->u32LdcBinSize, pstVpeChnattr->s32Rot);
}
}
MI_BOOL ST_DoGetVifRawData(MI_S32 HDRtype)
{
MI_SNR_PADInfo_t stPad0Info;
MI_SNR_PlaneInfo_t stSnrPlane0Info;
MI_U32 u32CapWidth = 0, u32CapHeight = 0;
MI_VIF_FrameRate_e eFrameRate = E_MI_VIF_FRAMERATE_FULL;
MI_SYS_PixelFormat_e ePixFormat;
MI_VIF_DEV vifDev = 1;
MI_VIF_CHN vifChn = 4;
MI_SNR_GetPadInfo(E_MI_SNR_PAD_ID_0, &stPad0Info);
MI_SNR_GetPlaneInfo(E_MI_SNR_PAD_ID_0, 0, &stSnrPlane0Info);
u32CapWidth = stSnrPlane0Info.stCapRect.u16Width;
u32CapHeight = stSnrPlane0Info.stCapRect.u16Height;
eFrameRate = E_MI_VIF_FRAMERATE_FULL;
ePixFormat = (MI_SYS_PixelFormat_e)RGB_BAYER_PIXEL(stSnrPlane0Info.ePixPrecision, stSnrPlane0Info.eBayerId);
/************************************************
Step2: init VIF(for IPC, only one dev)
*************************************************/
MI_VIF_Dev2SnrPadMuxCfg_t stVifDevMap[4];
memset(stVifDevMap, 0xff, sizeof(MI_VIF_Dev2SnrPadMuxCfg_t)*4);
if(HDRtype > 0)
{
/* stVifDevMap[0].eSensorPadID = E_MI_VIF_SNRPAD_ID_0;
stVifDevMap[0].u32PlaneID = 1;
stVifDevMap[1].eSensorPadID = E_MI_VIF_SNRPAD_ID_0;
stVifDevMap[1].u32PlaneID = 0;
stVifDevMap[2].eSensorPadID = E_MI_VIF_SNRPAD_ID_0;
stVifDevMap[2].u32PlaneID = 1;*/
printf("HDR ON not support");
return 0;
}
else
{
stVifDevMap[0].eSensorPadID = E_MI_VIF_SNRPAD_ID_0;
stVifDevMap[0].u32PlaneID = 0XFF;
stVifDevMap[1].eSensorPadID = E_MI_VIF_SNRPAD_ID_0;
stVifDevMap[1].u32PlaneID = 0XFF;
}
printf("devmap %p\n", stVifDevMap);
MI_VIF_SetDev2SnrPadMux(stVifDevMap, 4);
MI_VIF_DevAttr_t stDevAttr;
memset(&stDevAttr, 0x0, sizeof(MI_VIF_DevAttr_t));
stDevAttr.eIntfMode = stPad0Info.eIntfMode;
stDevAttr.eWorkMode = E_MI_VIF_WORK_MODE_RGB_FRAMEMODE;
stDevAttr.eHDRType = E_MI_VIF_HDR_TYPE_OFF;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656)
stDevAttr.eClkEdge = stPad0Info.unIntfAttr.stBt656Attr.eClkEdge;
else
stDevAttr.eClkEdge = E_MI_VIF_CLK_EDGE_DOUBLE;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_MIPI)
stDevAttr.eDataSeq =stPad0Info.unIntfAttr.stMipiAttr.eDataYUVOrder;
else
stDevAttr.eDataSeq = E_MI_VIF_INPUT_DATA_YUYV;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656)
memcpy(&stDevAttr.stSyncAttr, &stPad0Info.unIntfAttr.stBt656Attr.stSyncAttr, sizeof(MI_VIF_SyncAttr_t));
stDevAttr.eBitOrder = E_MI_VIF_BITORDER_NORMAL;
ExecFunc(MI_VIF_SetDevAttr(vifDev, &stDevAttr), MI_SUCCESS);
ExecFunc(MI_VIF_EnableDev(vifDev), MI_SUCCESS);
ST_VIF_PortInfo_T stVifPortInfoInfo;
memset(&stVifPortInfoInfo, 0, sizeof(ST_VIF_PortInfo_T));
stVifPortInfoInfo.u32RectX = 0;
stVifPortInfoInfo.u32RectY = 0;
stVifPortInfoInfo.u32RectWidth = u32CapWidth;
stVifPortInfoInfo.u32RectHeight = u32CapHeight;
stVifPortInfoInfo.u32DestWidth = u32CapWidth;
stVifPortInfoInfo.u32DestHeight = u32CapHeight;
stVifPortInfoInfo.eFrameRate = eFrameRate;
stVifPortInfoInfo.ePixFormat = ePixFormat;//E_MI_SYS_PIXEL_FRAME_RGB_BAYER_12BPP_GR;
STCHECKRESULT(ST_Vif_CreatePort(vifChn, 0, &stVifPortInfoInfo));
STCHECKRESULT(ST_Vif_StartPort(0, vifChn, 0));
{
MI_SYS_ChnPort_t stChnPort;
MI_SYS_BufInfo_t stBufInfo;
MI_SYS_BUF_HANDLE hHandle;
MI_S32 s32WriteCnt = 0;
FILE *fp = NULL;
char aName[128];
struct timeval CurTime;
MI_U64 u64Time = 0;
memset(&stChnPort, 0x0, sizeof(MI_SYS_ChnPort_t));
stChnPort.eModId = E_MI_MODULE_ID_VIF;
stChnPort.u32DevId = 0;
stChnPort.u32ChnId = vifChn;
stChnPort.u32PortId = 0;
gettimeofday(&CurTime,NULL);
u64Time = CurTime.tv_sec*1000;
sprintf(aName, "/mnt/dump_vif4_port0_%dx%d_pts%llu.yuv",u32CapWidth,u32CapHeight, u64Time);
fp = fopen(aName,"wb");
if(fp == NULL)
printf("file open fail\n");
while (s32WriteCnt < 10)
{
if (MI_SUCCESS == MI_SYS_ChnOutputPortGetBuf(&stChnPort, &stBufInfo, &hHandle))
{
int size = stBufInfo.stFrameData.u32BufSize;
fwrite(stBufInfo.stFrameData.pVirAddr[0], size, 1, fp);
s32WriteCnt++;
printf("\t vif(%d) size(%d) get buf cnt (%d)...w(%d)...h(%d)..\n", vifChn, size, s32WriteCnt, stBufInfo.stFrameData.u16Width, stBufInfo.stFrameData.u16Height);
MI_SYS_ChnOutputPortPutBuf(hHandle);
}
usleep(10*1000);
}
fclose(fp);
}
STCHECKRESULT(ST_Vif_StopPort(vifChn, 0));
STCHECKRESULT(ST_Vif_DisableDev(vifDev));
return MI_SUCCESS;
}
MI_BOOL ST_DoChangeRes(MI_U32 u32SensorNum)
{
char select = 0xFF;
MI_U8 u8ResIdx =0;
MI_SNR_Res_t stRes;
ST_Sys_BindInfo_T stBindInfo;
MI_SNR_PADInfo_t stPad0Info;
MI_SNR_PlaneInfo_t stSnrPlane0Info;
MI_U32 u32CapWidth = 0, u32CapHeight = 0;
MI_VIF_FrameRate_e eFrameRate = E_MI_VIF_FRAMERATE_FULL;
MI_SYS_PixelFormat_e ePixFormat;
MI_U32 u32ResCount =0;
MI_U8 u8ResIndex =0;
MI_S32 s32SnrPad =0;
memset(&stRes, 0x0, sizeof(MI_SNR_Res_t));
if(u32SensorNum > 1)
{
printf("select SensorPad id:");
scanf("%d", &s32SnrPad);
ST_Flush();
if(s32SnrPad >= ST_MAX_SENSOR_NUM)
{
printf("s32SnrPad %d > max %d \n", s32SnrPad, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
s32SnrPad = 0;
}
MI_SNR_PAD_ID_e eSnrPad = (MI_SNR_PAD_ID_e)s32SnrPad;
MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev;
MI_VIF_CHN vifChn = vifDev*4;
MI_U8 u8VpeChn = gstVifAttr[vifDev].u32BindVpeChan;
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[u8VpeChn];
ST_Vif_Attr_t *pstVifAttr = &gstVifAttr[vifDev];
MI_SNR_QueryResCount(eSnrPad, &u32ResCount);
for(u8ResIndex=0; u8ResIndex < u32ResCount; u8ResIndex++)
{
MI_SNR_GetRes(eSnrPad, u8ResIndex, &stRes);
printf("index %d, Crop(%d,%d,%d,%d), outputsize(%d,%d), maxfps %d, minfps %d, ResDesc %s\n",
u8ResIndex,
stRes.stCropRect.u16X, stRes.stCropRect.u16Y, stRes.stCropRect.u16Width,stRes.stCropRect.u16Height,
stRes.stOutputSize.u16Width, stRes.stOutputSize.u16Height,
stRes.u32MaxFps,stRes.u32MinFps,
stRes.strResDesc);
}
printf("select res\n");
scanf("%c", &select);
ST_Flush();
if(select == 'q')
{
return 1;
}
u8ResIdx = atoi(&select);
if(u8ResIdx >= u32ResCount)
return 0;
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF;
stBindInfo.stSrcChnPort.u32DevId = vifDev;
stBindInfo.stSrcChnPort.u32ChnId = vifChn;
stBindInfo.stSrcChnPort.u32PortId = 0;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stDstChnPort.u32DevId = 0;
stBindInfo.stDstChnPort.u32ChnId = u8VpeChn;
stBindInfo.stDstChnPort.u32PortId = 0;
STCHECKRESULT(ST_Sys_UnBind(&stBindInfo));
STCHECKRESULT(ST_Vpe_StopChannel(u8VpeChn));
/************************************************
Step3: destory VIF
*************************************************/
STCHECKRESULT(ST_Vif_StopPort(vifChn, 0));
STCHECKRESULT(ST_Vif_DisableDev(vifDev));
MI_SNR_Disable(eSnrPad);
if(pstVpeChnattr->eHdrType > 0)
{
MI_SNR_SetPlaneMode(eSnrPad, TRUE);
}
else
{
MI_SNR_SetPlaneMode(eSnrPad, FALSE);
}
MI_SNR_SetRes(eSnrPad,u8ResIdx);
MI_SNR_Enable(eSnrPad);
MI_SNR_GetPadInfo(eSnrPad, &stPad0Info);
MI_SNR_GetPlaneInfo(eSnrPad, 0, &stSnrPlane0Info);
u32CapWidth = stSnrPlane0Info.stCapRect.u16Width;
u32CapHeight = stSnrPlane0Info.stCapRect.u16Height;
eFrameRate = E_MI_VIF_FRAMERATE_FULL;
ePixFormat = (MI_SYS_PixelFormat_e)RGB_BAYER_PIXEL(stSnrPlane0Info.ePixPrecision, stSnrPlane0Info.eBayerId);
/************************************************
Step2: init VIF(for IPC, only one dev)
*************************************************/
MI_VIF_DevAttr_t stDevAttr;
memset(&stDevAttr, 0x0, sizeof(MI_VIF_DevAttr_t));
stDevAttr.eIntfMode = stPad0Info.eIntfMode;
stDevAttr.eWorkMode = pstVifAttr->eWorkMode;
stDevAttr.eHDRType = (MI_VIF_HDRType_e)pstVpeChnattr->eHdrType;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656)
stDevAttr.eClkEdge = stPad0Info.unIntfAttr.stBt656Attr.eClkEdge;
else
stDevAttr.eClkEdge = E_MI_VIF_CLK_EDGE_DOUBLE;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_MIPI)
stDevAttr.eDataSeq =stPad0Info.unIntfAttr.stMipiAttr.eDataYUVOrder;
else
stDevAttr.eDataSeq = E_MI_VIF_INPUT_DATA_YUYV;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656)
memcpy(&stDevAttr.stSyncAttr, &stPad0Info.unIntfAttr.stBt656Attr.stSyncAttr, sizeof(MI_VIF_SyncAttr_t));
stDevAttr.eBitOrder = E_MI_VIF_BITORDER_NORMAL;
ExecFunc(MI_VIF_SetDevAttr(vifDev, &stDevAttr), MI_SUCCESS);
ExecFunc(MI_VIF_EnableDev(vifDev), MI_SUCCESS);
ST_VIF_PortInfo_T stVifPortInfoInfo;
memset(&stVifPortInfoInfo, 0, sizeof(ST_VIF_PortInfo_T));
stVifPortInfoInfo.u32RectX = stSnrPlane0Info.stCapRect.u16X;
stVifPortInfoInfo.u32RectY = stSnrPlane0Info.stCapRect.u16Y;
stVifPortInfoInfo.u32RectWidth = u32CapWidth;
stVifPortInfoInfo.u32RectHeight = u32CapHeight;
stVifPortInfoInfo.u32DestWidth = u32CapWidth;
stVifPortInfoInfo.u32DestHeight = u32CapHeight;
stVifPortInfoInfo.eFrameRate = eFrameRate;
stVifPortInfoInfo.ePixFormat = ePixFormat;//E_MI_SYS_PIXEL_FRAME_RGB_BAYER_12BPP_GR;
STCHECKRESULT(ST_Vif_CreatePort(vifChn, 0, &stVifPortInfoInfo));
STCHECKRESULT(ST_Vif_StartPort(vifDev, vifChn, 0));
STCHECKRESULT(ST_Vpe_StartChannel(u8VpeChn));
/************************************************
Step1: bind VIF->VPE
*************************************************/
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF;
stBindInfo.stSrcChnPort.u32DevId = vifDev;
stBindInfo.stSrcChnPort.u32ChnId = vifChn;
stBindInfo.stSrcChnPort.u32PortId = 0;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stDstChnPort.u32DevId = 0;
stBindInfo.stDstChnPort.u32ChnId = u8VpeChn;
stBindInfo.stDstChnPort.u32PortId = 0;
stBindInfo.u32SrcFrmrate = 30;
stBindInfo.u32DstFrmrate = 30;
stBindInfo.eBindType = pstVifAttr->eBindType;
STCHECKRESULT(ST_Sys_Bind(&stBindInfo));
return 0;
}
MI_BOOL ST_DoChangeHDRtype()
{
MI_S32 select = 0;
MI_U8 u8ResIdx =0;
MI_SNR_Res_t stRes;
MI_SNR_PAD_ID_e eSnrPad = E_MI_SNR_PAD_ID_0;
ST_Sys_BindInfo_T stBindInfo;
MI_SNR_PADInfo_t stPad0Info;
MI_SNR_PlaneInfo_t stSnrPlane0Info;
MI_U32 u32CapWidth = 0, u32CapHeight = 0;
MI_VIF_FrameRate_e eFrameRate = E_MI_VIF_FRAMERATE_FULL;
MI_SYS_PixelFormat_e ePixFormat;
MI_VIF_HDRType_e eVifHdrType = E_MI_VIF_HDR_TYPE_OFF;
MI_VPE_HDRType_e eVpeHdrType = E_MI_VPE_HDR_TYPE_OFF;
MI_VIF_DEV vifDev = 0;
MI_VIF_CHN vifChn = 0;
MI_U32 u32VpeChn = 0;
MI_VPE_ChannelPara_t stVpeChParam;
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[u32VpeChn];
memset(&stVpeChParam, 0x0, sizeof(MI_VPE_ChannelPara_t));
memset(&stRes, 0x0, sizeof(MI_SNR_Res_t));
printf("Use HDR ?\n 0 not use, 1 use VC, 2 use DOL, 3 use EMBEDDED, 4 use LI\n");
printf("sony sensor(ex imx307) use DOL, sc sensor(ex sc4238) use VC\n");
scanf("%d", &select);
ST_Flush();
printf("You select %d HDR\n", select);
if(select == 0)
{
eVifHdrType = E_MI_VIF_HDR_TYPE_OFF;
eVpeHdrType = E_MI_VPE_HDR_TYPE_OFF;
}
else if(select == 1)
{
eVifHdrType = E_MI_VIF_HDR_TYPE_VC;
eVpeHdrType = E_MI_VPE_HDR_TYPE_VC;
}
else if(select == 2)
{
eVifHdrType = E_MI_VIF_HDR_TYPE_DOL;
eVpeHdrType = E_MI_VPE_HDR_TYPE_DOL;
}
else if(select == 3)
{
eVifHdrType = E_MI_VIF_HDR_TYPE_EMBEDDED;
eVpeHdrType = E_MI_VPE_HDR_TYPE_EMBEDDED;
}
else if(select == 4)
{
eVifHdrType = E_MI_VIF_HDR_TYPE_LI;
eVpeHdrType = E_MI_VPE_HDR_TYPE_LI;
}
else
{
printf("select hdrtype %d not support \n", select);
return 0;
}
pstVpeChnattr->eHdrType = eVpeHdrType;
/************************************************
Step1: unbind VIF->VPE
*************************************************/
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF;
stBindInfo.stSrcChnPort.u32DevId = vifDev;
stBindInfo.stSrcChnPort.u32ChnId = vifChn;
stBindInfo.stSrcChnPort.u32PortId = 0;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stDstChnPort.u32DevId = 0;
stBindInfo.stDstChnPort.u32ChnId = u32VpeChn;
stBindInfo.stDstChnPort.u32PortId = 0;
STCHECKRESULT(ST_Sys_UnBind(&stBindInfo));
STCHECKRESULT(ST_Vpe_StopChannel(u32VpeChn));
/************************************************
Step3: destory VIF
*************************************************/
STCHECKRESULT(ST_Vif_StopPort(vifChn, 0));
STCHECKRESULT(ST_Vif_DisableDev(vifDev));
MI_SNR_Disable(eSnrPad);
if(E_MI_VIF_HDR_TYPE_OFF==eVifHdrType
|| E_MI_VIF_HDR_TYPE_EMBEDDED==eVifHdrType
|| E_MI_VIF_HDR_TYPE_LI==eVifHdrType)
{
MI_SNR_SetPlaneMode(eSnrPad, FALSE);
}
else
{
MI_SNR_SetPlaneMode(eSnrPad, TRUE);
}
MI_SNR_SetRes(eSnrPad,u8ResIdx);
MI_SNR_Enable(eSnrPad);
MI_SNR_GetPadInfo(eSnrPad, &stPad0Info);
MI_SNR_GetPlaneInfo(eSnrPad, 0, &stSnrPlane0Info);
u32CapWidth = stSnrPlane0Info.stCapRect.u16Width;
u32CapHeight = stSnrPlane0Info.stCapRect.u16Height;
eFrameRate = E_MI_VIF_FRAMERATE_FULL;
ePixFormat = (MI_SYS_PixelFormat_e)RGB_BAYER_PIXEL(stSnrPlane0Info.ePixPrecision, stSnrPlane0Info.eBayerId);
/************************************************
Step2: init VIF(for IPC, only one dev)
*************************************************/
MI_VIF_DevAttr_t stDevAttr;
memset(&stDevAttr, 0x0, sizeof(MI_VIF_DevAttr_t));
stDevAttr.eIntfMode = stPad0Info.eIntfMode;
stDevAttr.eWorkMode = gstVifAttr[vifDev].eWorkMode;
stDevAttr.eHDRType = eVifHdrType;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656)
stDevAttr.eClkEdge = stPad0Info.unIntfAttr.stBt656Attr.eClkEdge;
else
stDevAttr.eClkEdge = E_MI_VIF_CLK_EDGE_DOUBLE;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_MIPI)
stDevAttr.eDataSeq =stPad0Info.unIntfAttr.stMipiAttr.eDataYUVOrder;
else
stDevAttr.eDataSeq = E_MI_VIF_INPUT_DATA_YUYV;
if(stDevAttr.eIntfMode == E_MI_VIF_MODE_BT656)
memcpy(&stDevAttr.stSyncAttr, &stPad0Info.unIntfAttr.stBt656Attr.stSyncAttr, sizeof(MI_VIF_SyncAttr_t));
stDevAttr.eBitOrder = E_MI_VIF_BITORDER_NORMAL;
ExecFunc(MI_VIF_SetDevAttr(vifDev, &stDevAttr), MI_SUCCESS);
ExecFunc(MI_VIF_EnableDev(vifDev), MI_SUCCESS);
ST_VIF_PortInfo_T stVifPortInfoInfo;
memset(&stVifPortInfoInfo, 0, sizeof(ST_VIF_PortInfo_T));
stVifPortInfoInfo.u32RectX = stSnrPlane0Info.stCapRect.u16X;
stVifPortInfoInfo.u32RectY = stSnrPlane0Info.stCapRect.u16Y;
stVifPortInfoInfo.u32RectWidth = u32CapWidth;
stVifPortInfoInfo.u32RectHeight = u32CapHeight;
stVifPortInfoInfo.u32DestWidth = u32CapWidth;
stVifPortInfoInfo.u32DestHeight = u32CapHeight;
stVifPortInfoInfo.eFrameRate = eFrameRate;
stVifPortInfoInfo.ePixFormat = ePixFormat;
STCHECKRESULT(ST_Vif_CreatePort(vifChn, 0, &stVifPortInfoInfo));
STCHECKRESULT(ST_Vif_StartPort(vifDev, vifChn, 0));
/************************************************
Step3: init VPE (create one VPE)
*************************************************/
MI_VPE_GetChannelParam(u32VpeChn, &stVpeChParam);
stVpeChParam.eHDRType = eVpeHdrType;
MI_VPE_SetChannelParam(u32VpeChn, &stVpeChParam);
STCHECKRESULT(ST_Vpe_StartChannel(0));
/************************************************
Step1: bind VIF->VPE
*************************************************/
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF;
stBindInfo.stSrcChnPort.u32DevId = vifDev;
stBindInfo.stSrcChnPort.u32ChnId = vifChn;
stBindInfo.stSrcChnPort.u32PortId = 0;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stDstChnPort.u32DevId = 0;
stBindInfo.stDstChnPort.u32ChnId = u32VpeChn;
stBindInfo.stDstChnPort.u32PortId = 0;
stBindInfo.u32SrcFrmrate = 30;
stBindInfo.u32DstFrmrate = 30;
stBindInfo.eBindType = gstVifAttr[vifDev].eBindType;
STCHECKRESULT(ST_Sys_Bind(&stBindInfo));
return 0;
}
MI_BOOL ST_DoChangeRotate(MI_U32 u32SensorNum)
{
ST_Sys_BindInfo_T stBindInfo;
MI_S32 s32Rotation = 0;
MI_S32 s32Mirror = 0;
MI_S32 s32Flip = 0;
ST_VencAttr_t *pstVencattr = gstVencattr;
MI_U8 i=0;
MI_U32 u32VifDev=0, vifChn=0;
MI_S32 VpeChn = 0;
MI_U32 u32MaxVencWidth =0, u32MaxVencHeight =0;
if(u32SensorNum > 1)
{
printf("select channel id:");
scanf("%d", &VpeChn);
ST_Flush();
if(VpeChn >= ST_MAX_SENSOR_NUM)
{
printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
VpeChn = 0;
}
u32VifDev = VpeChn;
vifChn = u32VifDev*4;
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[VpeChn];
printf("rotation(0:0, 1:90, 2:180, 3:270):");
scanf("%d", &s32Rotation);
ST_Flush();
printf("bmirror 0: FALSE, 1:TRUE :");
scanf("%d", &s32Mirror);
ST_Flush();
printf("bFlip 0: FALSE, 1:TRUE :");
scanf("%d", &s32Flip);
ST_Flush();
pstVpeChnattr->eVpeRotate = (MI_SYS_Rotate_e)s32Rotation;
pstVpeChnattr->bChnFlip = s32Flip;
pstVpeChnattr->bChnMirror = s32Mirror;
/************************************************
Step1: unbind VIF->VPE
*************************************************/
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF;
stBindInfo.stSrcChnPort.u32DevId = u32VifDev;
stBindInfo.stSrcChnPort.u32ChnId = vifChn;
stBindInfo.stSrcChnPort.u32PortId = 0;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stDstChnPort.u32DevId = 0;
stBindInfo.stDstChnPort.u32ChnId = VpeChn;
stBindInfo.stDstChnPort.u32PortId = 0;
STCHECKRESULT(ST_Sys_UnBind(&stBindInfo));
if(gbPreviewByVenc == TRUE)
{
ST_VencStop(VpeChn);
}
STCHECKRESULT(ST_Vpe_StopChannel(VpeChn));
if(pstVpeChnattr->eRunningMode == E_MI_VPE_RUN_REALTIME_MODE)
STCHECKRESULT(ST_Vif_StopPort(vifChn, 0));
/************************************************
Step3: init VPE (create one VPE)
*************************************************/
MI_VPE_SetChannelRotation(VpeChn, pstVpeChnattr->eVpeRotate);
MI_VPE_ChannelPara_t stChnParam;
memset(&stChnParam, 0x0, sizeof(MI_VPE_ChannelPara_t));
MI_VPE_GetChannelParam(VpeChn, &stChnParam);
stChnParam.bMirror = pstVpeChnattr->bChnMirror;
stChnParam.bFlip = pstVpeChnattr->bChnFlip;
MI_VPE_SetChannelParam(VpeChn, &stChnParam);
for(i=0; i<ST_MAX_PORT_NUM; i++)
{
MI_SYS_WindowRect_t stOutCropInfo;
MI_VPE_PortMode_t stVpeMode;
MI_U32 u32VencChn = pstVpeChnattr->stVpePortAttr[i].u32BindVencChan;
memset(&stOutCropInfo, 0x0, sizeof(MI_SYS_WindowRect_t));
memset(&stVpeMode, 0x0, sizeof(MI_VPE_PortMode_t));
if(pstVpeChnattr->stVpePortAttr[i].bUsed == TRUE)
{
MI_VPE_GetPortCrop(VpeChn, i, &stOutCropInfo);
MI_VPE_GetPortMode(VpeChn , i, &stVpeMode);
if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90
|| pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270)
{
stOutCropInfo.u16X = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Y;
stOutCropInfo.u16Y = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16X;
stOutCropInfo.u16Width = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Height;
stOutCropInfo.u16Height = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Width;
stVpeMode.u16Width = pstVpeChnattr->stVpePortAttr[i].stOrigPortSize.u16Height;
stVpeMode.u16Height = pstVpeChnattr->stVpePortAttr[i].stOrigPortSize.u16Width;
u32MaxVencWidth = 2160;
u32MaxVencHeight = 3840;
}
else
{
stOutCropInfo.u16X = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16X;
stOutCropInfo.u16Y = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Y;
stOutCropInfo.u16Width = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Width;
stOutCropInfo.u16Height = pstVpeChnattr->stVpePortAttr[i].stOrigPortCrop.u16Height;
stVpeMode.u16Width = pstVpeChnattr->stVpePortAttr[i].stOrigPortSize.u16Width;
stVpeMode.u16Height = pstVpeChnattr->stVpePortAttr[i].stOrigPortSize.u16Height;
u32MaxVencWidth = 3840;
u32MaxVencHeight = 2160;
}
MI_VPE_SetPortCrop(VpeChn, i, &stOutCropInfo);
MI_VPE_SetPortMode(VpeChn , i, &stVpeMode);
pstVencattr[u32VencChn].u32Width = stVpeMode.u16Width;
pstVencattr[u32VencChn].u32Height = stVpeMode.u16Height;
}
}
if(gbPreviewByVenc == TRUE)
{
ST_VencStart(u32MaxVencWidth, u32MaxVencHeight, VpeChn);
//ExecFunc(MI_VENC_StartRecvPic(pstVencattr[u32VencChn].vencChn), MI_SUCCESS);
}
if(pstVpeChnattr->eRunningMode == E_MI_VPE_RUN_REALTIME_MODE)
STCHECKRESULT(ST_Vif_StartPort(u32VifDev, vifChn, 0));
STCHECKRESULT(ST_Vpe_StartChannel(VpeChn));
/************************************************
Step1: bind VIF->VPE
*************************************************/
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VIF;
stBindInfo.stSrcChnPort.u32DevId = u32VifDev;
stBindInfo.stSrcChnPort.u32ChnId = vifChn;
stBindInfo.stSrcChnPort.u32PortId = 0;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stDstChnPort.u32DevId = 0;
stBindInfo.stDstChnPort.u32ChnId = VpeChn;
stBindInfo.stDstChnPort.u32PortId = 0;
stBindInfo.u32SrcFrmrate = 30;
stBindInfo.u32DstFrmrate = 30;
stBindInfo.eBindType = gstVifAttr[u32VifDev].eBindType;
STCHECKRESULT(ST_Sys_Bind(&stBindInfo));
return 0;
}
MI_BOOL ST_ResetPortMode(MI_U32 u32SensorNum)
{
MI_S32 s32Portid = 0;
MI_S32 s32PortPixelFormat =0;
MI_S32 s32PortMirror=0, s32PortFlip=0;
MI_S32 s32PortW=0, s32PortH=0;
MI_VPE_PortMode_t stVpePortMode;
ST_Sys_BindInfo_T stBindInfo;
MI_U32 u32DevId = 0;
memset(&stVpePortMode, 0x0, sizeof(MI_VPE_PortMode_t));
memset(&stBindInfo, 0x0, sizeof(ST_Sys_BindInfo_T));
MI_U32 VpeChn =0;
if(u32SensorNum > 1)
{
printf("select channel id:");
scanf("%d", &VpeChn);
ST_Flush();
if(VpeChn >= ST_MAX_SENSOR_NUM)
{
printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
VpeChn = 0;
}
printf("select port id:");
scanf("%d", &s32Portid);
ST_Flush();
if(s32Portid >= ST_MAX_PORT_NUM)
{
printf("port %d, not valid \n", s32Portid);
return 0;
}
printf("port %d bmirror:", s32Portid);
scanf("%d", &s32PortMirror);
ST_Flush();
printf("port %d bflip:", s32Portid);
scanf("%d", &s32PortFlip);
ST_Flush();
printf("port %d port width:", s32Portid);
scanf("%d", &s32PortW);
ST_Flush();
printf("port %d port height:", s32Portid);
scanf("%d", &s32PortH);
ST_Flush();
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[VpeChn];
ST_VpePortAttr_t *pstVpePortAttr = &pstVpeChnattr->stVpePortAttr[s32Portid];
MI_U32 U32VencChn = pstVpePortAttr->u32BindVencChan;
ST_VencAttr_t *pstVencattr = &gstVencattr[U32VencChn];
MI_VPE_GetPortMode(VpeChn, s32Portid, &stVpePortMode);
if(gbPreviewByVenc == FALSE)
{
printf("port %d port pixel:", s32Portid);
printf("yuv422:0, argb8888:1, abgr8888:2, bgra8888:3, yuv420:11\n");
scanf("%d", &s32PortPixelFormat);
ST_Flush();
}
else
s32PortPixelFormat = stVpePortMode.ePixelFormat;
if(gbPreviewByVenc == TRUE)
{
ExecFunc(MI_VENC_GetChnDevid(pstVencattr->vencChn, &u32DevId), MI_SUCCESS);
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stSrcChnPort.u32DevId = 0;
stBindInfo.stSrcChnPort.u32ChnId = VpeChn;
stBindInfo.stSrcChnPort.u32PortId = s32Portid;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VENC;
stBindInfo.stDstChnPort.u32DevId = u32DevId;
stBindInfo.stDstChnPort.u32ChnId = pstVencattr->vencChn;
stBindInfo.stDstChnPort.u32PortId = 0;
STCHECKRESULT(ST_Sys_UnBind(&stBindInfo));
if(pstVencattr->bUsed == TRUE)
ExecFunc(MI_VENC_StopRecvPic(pstVencattr->vencChn), MI_SUCCESS);
}
MI_VPE_DisablePort(VpeChn, s32Portid);
pstVpePortAttr->bMirror = s32PortMirror;
pstVpePortAttr->bFlip = s32PortFlip;
pstVpePortAttr->stOrigPortSize.u16Width = s32PortW;
pstVpePortAttr->stOrigPortSize.u16Height = s32PortH;
pstVpePortAttr->ePixelFormat = (MI_SYS_PixelFormat_e)s32PortPixelFormat;
pstVpePortAttr->bUsed = TRUE;
stVpePortMode.bMirror = pstVpePortAttr->bMirror;
stVpePortMode.bFlip = pstVpePortAttr->bFlip;
stVpePortMode.ePixelFormat = pstVpePortAttr->ePixelFormat;
if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90
|| pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270)
{
stVpePortMode.u16Width = pstVpePortAttr->stOrigPortSize.u16Height;
stVpePortMode.u16Height = pstVpePortAttr->stOrigPortSize.u16Width;
}
else
{
stVpePortMode.u16Width = pstVpePortAttr->stOrigPortSize.u16Width;
stVpePortMode.u16Height = pstVpePortAttr->stOrigPortSize.u16Height;
}
MI_VPE_SetPortMode(VpeChn, s32Portid, &stVpePortMode);
if(gbPreviewByVenc == TRUE)
{
MI_VENC_ChnAttr_t stChnAttr;
memset(&stChnAttr, 0x0, sizeof(MI_VENC_ChnAttr_t));
if(pstVencattr->bUsed == TRUE)
{
ExecFunc(MI_VENC_GetChnAttr(pstVencattr->vencChn, &stChnAttr), MI_SUCCESS);
if(pstVencattr->eType == E_MI_VENC_MODTYPE_H264E)
{
stChnAttr.stVeAttr.stAttrH264e.u32PicWidth = stVpePortMode.u16Width;
stChnAttr.stVeAttr.stAttrH264e.u32PicHeight = stVpePortMode.u16Height;
}
else if(pstVencattr->eType == E_MI_VENC_MODTYPE_H264E)
{
stChnAttr.stVeAttr.stAttrH265e.u32PicWidth = stVpePortMode.u16Width;
stChnAttr.stVeAttr.stAttrH265e.u32PicHeight = stVpePortMode.u16Height;
}
else if(pstVencattr->eType == E_MI_VENC_MODTYPE_H264E)
{
stChnAttr.stVeAttr.stAttrJpeg.u32PicWidth = stVpePortMode.u16Width;
stChnAttr.stVeAttr.stAttrJpeg.u32PicHeight = stVpePortMode.u16Height;
}
ExecFunc(MI_VENC_SetChnAttr(pstVencattr->vencChn, &stChnAttr), MI_SUCCESS);
}
else
printf("port %d, venc buse %d \n", s32Portid, pstVencattr->bUsed);
}
MI_VPE_EnablePort(VpeChn, s32Portid);
MI_SYS_ChnPort_t stChnPort;
memset(&stChnPort, 0x0, sizeof(MI_SYS_ChnPort_t));
stChnPort.eModId = E_MI_MODULE_ID_VPE;
stChnPort.u32DevId = 0;
stChnPort.u32ChnId = VpeChn;
stChnPort.u32PortId = s32Portid;
MI_SYS_SetChnOutputPortDepth(&stChnPort, 1, 4);
if(gbPreviewByVenc == TRUE)
{
if(pstVencattr->bUsed == TRUE)
ExecFunc(MI_VENC_StartRecvPic(pstVencattr->vencChn), MI_SUCCESS);
ExecFunc(MI_VENC_GetChnDevid(pstVencattr->vencChn, &u32DevId), MI_SUCCESS);
stBindInfo.stSrcChnPort.eModId = E_MI_MODULE_ID_VPE;
stBindInfo.stSrcChnPort.u32DevId = 0;
stBindInfo.stSrcChnPort.u32ChnId = VpeChn;
stBindInfo.stSrcChnPort.u32PortId = s32Portid;
stBindInfo.stDstChnPort.eModId = E_MI_MODULE_ID_VENC;
stBindInfo.stDstChnPort.u32DevId = u32DevId;
stBindInfo.stDstChnPort.u32ChnId = pstVencattr->vencChn;
stBindInfo.stDstChnPort.u32PortId = 0;
stBindInfo.u32SrcFrmrate = 30;
stBindInfo.u32DstFrmrate = 30;
stBindInfo.eBindType = pstVencattr->eBindType;
stBindInfo.u32BindParam = pstVencattr->u32BindParam;
STCHECKRESULT(ST_Sys_Bind(&stBindInfo));
}
return 0;
}
MI_BOOL ST_DoSetChnCrop(MI_U32 u32SensorNum)
{
MI_S32 s32ChannelCropX =0, s32ChannelCropY=0,s32ChannelCropW=0,s32ChannelCropH =0;
MI_SYS_WindowRect_t stVpeChnCrop;
memset(&stVpeChnCrop, 0x0, sizeof(MI_SYS_WindowRect_t));
MI_U32 VpeChn =0;
if(u32SensorNum > 1)
{
printf("select channel id:");
scanf("%d", &VpeChn);
ST_Flush();
if(VpeChn >= ST_MAX_SENSOR_NUM)
{
printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
VpeChn = 0;
}
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[VpeChn];
printf("Channel Crop x:");
scanf("%d", &s32ChannelCropX);
ST_Flush();
printf("Channel Crop y:");
scanf("%d", &s32ChannelCropY);
ST_Flush();
printf("Channel Crop width:");
scanf("%d", &s32ChannelCropW);
ST_Flush();
printf("Channel Crop height:");
scanf("%d", &s32ChannelCropH);
ST_Flush();
pstVpeChnattr->stOrgVpeChnCrop.u16X = s32ChannelCropX;
pstVpeChnattr->stOrgVpeChnCrop.u16Y = s32ChannelCropY;
pstVpeChnattr->stOrgVpeChnCrop.u16Width = s32ChannelCropW;
pstVpeChnattr->stOrgVpeChnCrop.u16Height = s32ChannelCropH;
if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90
|| pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270)
{
stVpeChnCrop.u16X = pstVpeChnattr->stOrgVpeChnCrop.u16Y;
stVpeChnCrop.u16Y = pstVpeChnattr->stOrgVpeChnCrop.u16X;
stVpeChnCrop.u16Width = pstVpeChnattr->stOrgVpeChnCrop.u16Height;
stVpeChnCrop.u16Height = pstVpeChnattr->stOrgVpeChnCrop.u16Width;
}
else
{
stVpeChnCrop.u16X = pstVpeChnattr->stOrgVpeChnCrop.u16X;
stVpeChnCrop.u16Y = pstVpeChnattr->stOrgVpeChnCrop.u16Y;
stVpeChnCrop.u16Width = pstVpeChnattr->stOrgVpeChnCrop.u16Width;
stVpeChnCrop.u16Height = pstVpeChnattr->stOrgVpeChnCrop.u16Height;
}
MI_VPE_SetChannelCrop(VpeChn,&stVpeChnCrop);
return 0;
}
MI_BOOL ST_DoSetChnZoom(MI_U32 u32SensorNum)
{
float r = 16.0/9;
MI_U16 ystep = 8;
MI_U16 xstep =ALIGN_UP((MI_U16)(r*ystep), 2);
int oriW = 0, oriH = 0;
MI_SYS_WindowRect_t stCropInfo;
MI_VIF_ChnPortAttr_t stVifPortInfo;
MI_U32 u32SleepTimeUs = 0;
MI_U32 u32Fps =0;
MI_S32 s32ZoomPosition = 0;
MI_S32 s32PortZoom = 0;
MI_BOOL bZoomDone = TRUE;
memset(&stVifPortInfo, 0x0, sizeof(MI_VIF_ChnPortAttr_t));
memset(&stCropInfo, 0, sizeof(MI_SYS_WindowRect_t));
MI_U32 VpeChn =0;
if(u32SensorNum > 1)
{
printf("select channel id:");
scanf("%d", &VpeChn);
ST_Flush();
if(VpeChn >= ST_MAX_SENSOR_NUM)
{
printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
VpeChn = 0;
}
MI_U32 u32VifDev = VpeChn;
MI_U32 u32VifChn = u32VifDev*4;
MI_SNR_PAD_ID_e eSnrPadId = E_MI_SNR_PAD_ID_0;
if(u32VifDev == 0)
eSnrPadId = E_MI_SNR_PAD_ID_0;
else if(u32VifDev == 2)
eSnrPadId = E_MI_SNR_PAD_ID_1;
else
DBG_ERR("VIF DEV ERR %d \n", u32VifDev);
MI_VIF_GetChnPortAttr(u32VifChn,0,&stVifPortInfo);
oriW = stVifPortInfo.stCapRect.u16Width;
oriH = stVifPortInfo.stCapRect.u16Height;
MI_SNR_GetFps(eSnrPadId, &u32Fps);
u32SleepTimeUs = 1000000/u32Fps;
printf("fps %d, sleeptime %d \n", u32Fps, u32SleepTimeUs);
printf("set zoom position: 1.vif, 2.vpe isp dma, 3.vpe scl pre-crop");
scanf("%d", &s32ZoomPosition);
ST_Flush();
if(s32ZoomPosition == 3)
{
printf("select which port zoom: 0:port0, 1:port1, 2:port2, 3: all port \n");
scanf("%d", &s32PortZoom);
ST_Flush();
}
while(1)
{
if(bZoomDone == TRUE)
{
stCropInfo.u16X += xstep;
stCropInfo.u16Y += ystep;
stCropInfo.u16Width = oriW - (2 * stCropInfo.u16X);
stCropInfo.u16Height = oriH -(2 * stCropInfo.u16Y);
stCropInfo.u16Width = ALIGN_UP(stCropInfo.u16Width, 2);
stCropInfo.u16Height = ALIGN_UP(stCropInfo.u16Height, 2);
if(stCropInfo.u16Width < 660 || stCropInfo.u16Height < 360)
{
bZoomDone = FALSE;
}
}
else
{
stCropInfo.u16X -= xstep;
stCropInfo.u16Y -= ystep;
stCropInfo.u16Width = oriW - (2 * stCropInfo.u16X);
stCropInfo.u16Height = oriH -(2 * stCropInfo.u16Y);
stCropInfo.u16Width = ALIGN_UP(stCropInfo.u16Width, 2);
stCropInfo.u16Height = ALIGN_UP(stCropInfo.u16Height, 2);
if(stCropInfo.u16Width > oriW || stCropInfo.u16Height > oriH)
{
break;
}
}
if(s32ZoomPosition == 1)
{
MI_VIF_ChnPortAttr_t stChnPortAttr;
ExecFunc(MI_VIF_GetChnPortAttr(u32VifChn, 0, &stChnPortAttr), MI_SUCCESS);
memcpy(&stChnPortAttr.stCapRect, &stCropInfo, sizeof(MI_SYS_WindowRect_t));
stChnPortAttr.stDestSize.u16Width = stCropInfo.u16Width;
stChnPortAttr.stDestSize.u16Height = stCropInfo.u16Height;
ExecFunc(MI_VIF_SetChnPortAttr(u32VifChn, 0, &stChnPortAttr), MI_SUCCESS);
}
else if(s32ZoomPosition == 2)
{
STCHECKRESULT(MI_VPE_SetChannelCrop(VpeChn, &stCropInfo));
STCHECKRESULT(MI_VPE_GetChannelCrop(VpeChn, &stCropInfo));
}
else if(s32ZoomPosition == 3)
{
if(s32PortZoom == 3)
{
MI_VPE_SetPortCrop(VpeChn, 0, &stCropInfo);
MI_VPE_SetPortCrop(VpeChn, 1, &stCropInfo);
MI_VPE_SetPortCrop(VpeChn, 2, &stCropInfo);
}
else
MI_VPE_SetPortCrop(VpeChn, s32PortZoom, &stCropInfo);
}
printf("after crop down x:%d y:%d w:%d h:%d\n", stCropInfo.u16X, stCropInfo.u16Y, stCropInfo.u16Width, stCropInfo.u16Height);
//ST_Flush();
usleep(u32SleepTimeUs);
}
return 0;
}
MI_BOOL ST_DoSetPortCrop(MI_U32 u32SensorNum)
{
MI_S32 s32Portid = 0;
MI_S32 s32PortCropX =0, s32PortCropY=0,s32PortCropW=0,s32PortCropH =0;
MI_SYS_WindowRect_t stPortCropSize;
memset(&stPortCropSize, 0x0, sizeof(MI_SYS_WindowRect_t));
MI_U32 VpeChn =0;
if(u32SensorNum > 1)
{
printf("select channel id:");
scanf("%d", &VpeChn);
ST_Flush();
if(VpeChn >= ST_MAX_SENSOR_NUM)
{
printf("VpeChn %d > max %d \n", VpeChn, ST_MAX_SENSOR_NUM);
return 0;
}
}
else
{
VpeChn = 0;
}
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[VpeChn];
ST_VpePortAttr_t *pstVpePortAttr = pstVpeChnattr->stVpePortAttr;
printf("select port id:");
scanf("%d", &s32Portid);
ST_Flush();
if(s32Portid >= ST_MAX_PORT_NUM || pstVpePortAttr[s32Portid].bUsed != TRUE)
{
printf("port %d, not valid \n", s32Portid);
return 0;
}
printf("port %d port crop x:", s32Portid);
scanf("%d", &s32PortCropX);
ST_Flush();
printf("port %d port crop y:", s32Portid);
scanf("%d", &s32PortCropY);
ST_Flush();
printf("port %d port crop width:", s32Portid);
scanf("%d", &s32PortCropW);
ST_Flush();
printf("port %d port crop height:", s32Portid);
scanf("%d", &s32PortCropH);
ST_Flush();
pstVpePortAttr[s32Portid].stOrigPortCrop.u16X = s32PortCropX;
pstVpePortAttr[s32Portid].stOrigPortCrop.u16Y = s32PortCropY;
pstVpePortAttr[s32Portid].stOrigPortCrop.u16Width = s32PortCropW;
pstVpePortAttr[s32Portid].stOrigPortCrop.u16Height = s32PortCropH;
if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90
|| pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270)
{
stPortCropSize.u16X = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Y;
stPortCropSize.u16Y = pstVpePortAttr[s32Portid].stOrigPortCrop.u16X;
stPortCropSize.u16Width = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Height;
stPortCropSize.u16Height = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Width;
}
else
{
stPortCropSize.u16X = pstVpePortAttr[s32Portid].stOrigPortCrop.u16X;
stPortCropSize.u16Y = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Y;
stPortCropSize.u16Width = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Width;
stPortCropSize.u16Height = pstVpePortAttr[s32Portid].stOrigPortCrop.u16Height;
}
MI_VPE_SetPortCrop(VpeChn , s32Portid, &stPortCropSize);
return 0;
}
int main(int argc, char **argv)
{
MI_U8 i = 0, j=0;
MI_SNR_PAD_ID_e eSnrPad = E_MI_SNR_PAD_ID_0;
MI_U32 u32SensorNum = 0;
gstSensorAttr[0].u32BindVifDev = 0;
gstSensorAttr[1].u32BindVifDev = 2;
if(argc > 1 && argc < 5)
{
for(i=0; i<argc-1;i++)
{
gstSensorAttr[i].bUsed = (MI_BOOL)atoi(argv[i+1]);
}
for(i=0; i<ST_MAX_SENSOR_NUM; i++)
{
gstVifAttr[i].eBindType = E_MI_SYS_BIND_TYPE_FRAME_BASE;
gstVifAttr[i].eWorkMode = E_MI_VIF_WORK_MODE_RGB_FRAMEMODE;
gstVifAttr[i].u32BindVpeChan = i;
gstVpeChnattr[i].eRunningMode = E_MI_VPE_RUN_CAM_MODE;
for(j=0; j< ST_MAX_PORT_NUM; j++)
{
gstVpeChnattr[i].stVpePortAttr[j].u32BindVencChan = i*ST_MAX_PORT_NUM + j;
}
}
}
else if(argc == 1)
{
gstSensorAttr[0].bUsed = TRUE;
gstVifAttr[0].eBindType = E_MI_SYS_BIND_TYPE_REALTIME;
gstVifAttr[0].eWorkMode = E_MI_VIF_WORK_MODE_RGB_REALTIME;
gstVifAttr[0].u32BindVpeChan = 0;
gstVpeChnattr[0].eRunningMode = E_MI_VPE_RUN_REALTIME_MODE;
for(j=0; j< ST_MAX_PORT_NUM; j++)
{
gstVpeChnattr[0].stVpePortAttr[j].u32BindVencChan = j;
}
}
else
{
printf("realtime ./prog_vpe, frame mode ./prog_vpe 1 0 0, which sensor use \n");
}
u32SensorNum = argc-1;
for(i=0; i<ST_MAX_SENSOR_NUM; i++)
{
if(gstSensorAttr[i].bUsed == TRUE)
ST_SetArgs(i);
}
for(i=0; i<ST_MAX_SENSOR_NUM; i++)
{
if(gstSensorAttr[i].bUsed == TRUE)
{
eSnrPad = (MI_SNR_PAD_ID_e)i;
MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev;
MI_VPE_CHANNEL vpechn = gstVifAttr[vifDev].u32BindVpeChan;
STCHECKRESULT(ST_BaseModuleInit(eSnrPad));
if(gbPreviewByVenc == TRUE)
{
ST_VpeChannelAttr_t *pstVpeChnattr = &gstVpeChnattr[vpechn];
MI_U32 u32MaxWidth =0, u32MaxHeight =0;
if(pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_90
|| pstVpeChnattr->eVpeRotate == E_MI_SYS_ROTATE_270)
{
u32MaxWidth = 2160;
u32MaxHeight = 3840;
}
else
{
u32MaxWidth = 3840;
u32MaxHeight = 2160;
}
STCHECKRESULT(ST_VencStart(u32MaxWidth,u32MaxHeight, vpechn));
}
}
}
ST_RtspServerStart();
#if 0
pthread_t pIQthread;
pthread_create(&pIQthread, NULL, ST_IQthread, NULL);
#endif
//pthread_t pSenVpeDatathread;
//pthread_create(&pSenVpeDatathread, NULL, ST_SendVpeBufthread, NULL);
if(gbPreviewByVenc == FALSE)
{
MI_U8 u8PortId[ST_MAX_SENSOR_NUM*ST_MAX_PORT_NUM];
for(j=0; j< ST_MAX_SENSOR_NUM; j++)
{
for(i=0; i< ST_MAX_PORT_NUM; i++)
{
u8PortId[j*ST_MAX_SENSOR_NUM+i] = j*ST_MAX_SENSOR_NUM+i;
pthread_mutex_init(&gstVpeChnattr[j].stVpePortAttr[i].Portmutex, NULL);
pthread_create(&gstVpeChnattr[j].stVpePortAttr[i].pGetDatathread, NULL, ST_GetVpeOutputDataThread, (void *)(&u8PortId[i]));
}
}
}
for(i=0; i<ST_MAX_SENSOR_NUM; i++)
{
if(gstSensorAttr[i].bUsed == TRUE)
{
eSnrPad = (MI_SNR_PAD_ID_e)i;
MI_SNR_PlaneInfo_t stSnrPlane0Info;
memset(&stSnrPlane0Info, 0x0, sizeof(MI_SNR_PlaneInfo_t));
MI_SNR_GetPlaneInfo(eSnrPad, 0, &stSnrPlane0Info);
MI_IQSERVER_Open(stSnrPlane0Info.stCapRect.u16Width, stSnrPlane0Info.stCapRect.u16Height, 0);
}
}
while(!bExit)
{
MI_U32 u32Select = 0xff;
printf("select 0: change res \n");
printf("select 1: change hdrtype\n");
printf("select 2: change rotate\n");
printf("select 3: change chancrop\n");
printf("select 4: change portMode\n");
printf("select 5: change portcrop\n");
printf("select 6: Get port buffer\n");
printf("select 7: disable port \n");
printf("select 8: get venc out \n");
printf("select 9: Ldc on/off \n");
printf("select 10: vpe chn zoom\n");
printf("select 11: exit\n");
scanf("%d", &u32Select);
ST_Flush();
if(u32Select == 0)
bExit = ST_DoChangeRes(u32SensorNum);
else if(u32Select == 1)
{
bExit = ST_DoChangeHDRtype();
}
else if(u32Select == 2)
{
bExit =ST_DoChangeRotate(u32SensorNum);
}
else if(u32Select == 3)
{
bExit =ST_DoSetChnCrop(u32SensorNum);
}
else if(u32Select == 4)
{
bExit =ST_ResetPortMode(u32SensorNum);
}
else if(u32Select == 5)
{
bExit =ST_DoSetPortCrop(u32SensorNum);
}
else if(u32Select == 6)
{
bExit =ST_GetVpeOutputData(u32SensorNum);
}
else if(u32Select == 7)
{
bExit =ST_VpeDisablePort(u32SensorNum);
}
else if(u32Select == 8)
{
bExit =ST_GetVencOut();
}
else if(u32Select == 9)
{
bExit =ST_SetLdcOnOff(u32SensorNum);
}
else if(u32Select == 10)
{
bExit =ST_DoSetChnZoom(u32SensorNum);
}
else if(u32Select == 11)
{
bExit = TRUE;
}
usleep(100 * 1000);
}
usleep(100 * 1000);
if(gbPreviewByVenc == FALSE)
{
for(j=0; j< ST_MAX_SENSOR_NUM; j++)
{
for(i=0; i< ST_MAX_PORT_NUM; i++)
{
void *retarg = NULL;
pthread_cancel(gstVpeChnattr[j].stVpePortAttr[i].pGetDatathread);
pthread_join(gstVpeChnattr[j].stVpePortAttr[i].pGetDatathread, &retarg);
}
for(i=0; i< ST_MAX_PORT_NUM; i++)
{
pthread_mutex_destroy(&gstVpeChnattr[j].stVpePortAttr[i].Portmutex);
}
}
}
ST_RtspServerStop();
for(i=0; i<ST_MAX_SENSOR_NUM; i++)
{
if(gstSensorAttr[i].bUsed == TRUE)
{
eSnrPad = (MI_SNR_PAD_ID_e)i;
MI_VIF_DEV vifDev = gstSensorAttr[eSnrPad].u32BindVifDev;
MI_VPE_CHANNEL vpechn = gstVifAttr[vifDev].u32BindVpeChan;
if(gbPreviewByVenc == TRUE)
{
STCHECKRESULT(ST_VencStop(vpechn));
}
STCHECKRESULT(ST_BaseModuleUnInit(eSnrPad));
}
}
memset(&gstSensorAttr, 0x0, sizeof(gstSensorAttr));
memset(&gstVifAttr, 0x0, sizeof(gstVifAttr));
memset(&gstVpeChnattr, 0x0, sizeof(gstVpeChnattr));
memset(&gstVencattr, 0x0, sizeof(gstVencattr));
return 0;
}
|
[
"zhaozhenhong5@aliyun.com"
] |
zhaozhenhong5@aliyun.com
|
aa7bcc521ec4e31416d884ccb82f1c5e1c0fb804
|
5d68b88653b6e495439d99194964fc4bf6c25aff
|
/lib/RcppParallel/include/tbb/flow_graph_opencl_node.h
|
89f4da7b167b1711b519b2b8ab0678bb85c738bc
|
[] |
no_license
|
BRICOMATA9/TRDFMLQEO
|
8b3b0690547ad5b40cebb45bf996dee9ee7dbc40
|
dadaff4a3aa290809336a784357b13787bd78046
|
refs/heads/master
| 2020-05-16T00:31:36.108773
| 2019-04-21T20:30:53
| 2019-04-21T20:30:53
| 182,571,145
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 60,073
|
h
|
/*
Copyright (c) 2005-2017 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB_flow_graph_opencl_node_H
#define __TBB_flow_graph_opencl_node_H
#include "tbb/tbb_config.h"
#if __TBB_PREVIEW_OPENCL_NODE
#include "flow_graph.h"
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <map>
#include <mutex>
#ifdef __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/cl.h>
#endif
namespace tbb {
namespace flow {
namespace interface9 {
class opencl_foundation;
class opencl_device_list;
template <typename Factory>
class opencl_buffer_impl;
template <typename Factory>
class opencl_program;
class default_opencl_factory;
class opencl_graph : public graph {
public:
//! Constructs a graph with isolated task_group_context
opencl_graph() : my_opencl_foundation( NULL ) {}
//! Constructs a graph with an user context
explicit opencl_graph( task_group_context& context ) : graph( context ), my_opencl_foundation( NULL ) {}
//! Destroys a graph
~opencl_graph();
//! Available devices
const opencl_device_list& available_devices();
default_opencl_factory& opencl_factory();
protected:
opencl_foundation *my_opencl_foundation;
opencl_foundation &get_opencl_foundation();
template <typename T, typename Factory>
friend class opencl_buffer;
template <cl_channel_order channel_order, cl_channel_type channel_type, typename Factory>
friend class opencl_image2d;
template<typename... Args>
friend class opencl_node;
template <typename DeviceFilter>
friend class opencl_factory;
};
template <typename DeviceFilter>
class opencl_factory;
template <typename T, typename Factory>
class dependency_msg;
inline void enforce_cl_retcode( cl_int err, std::string msg ) {
if ( err != CL_SUCCESS ) {
std::cerr << msg << "; error code: " << err << std::endl;
throw msg;
}
}
template <typename T>
T event_info( cl_event e, cl_event_info i ) {
T res;
enforce_cl_retcode( clGetEventInfo( e, i, sizeof( res ), &res, NULL ), "Failed to get OpenCL event information" );
return res;
}
template <typename T>
T device_info( cl_device_id d, cl_device_info i ) {
T res;
enforce_cl_retcode( clGetDeviceInfo( d, i, sizeof( res ), &res, NULL ), "Failed to get OpenCL device information" );
return res;
}
template <>
std::string device_info<std::string>( cl_device_id d, cl_device_info i ) {
size_t required;
enforce_cl_retcode( clGetDeviceInfo( d, i, 0, NULL, &required ), "Failed to get OpenCL device information" );
char *buff = (char*)alloca( required );
enforce_cl_retcode( clGetDeviceInfo( d, i, required, buff, NULL ), "Failed to get OpenCL device information" );
return buff;
}
template <typename T>
T platform_info( cl_platform_id p, cl_platform_info i ) {
T res;
enforce_cl_retcode( clGetPlatformInfo( p, i, sizeof( res ), &res, NULL ), "Failed to get OpenCL platform information" );
return res;
}
template <>
std::string platform_info<std::string>( cl_platform_id p, cl_platform_info i ) {
size_t required;
enforce_cl_retcode( clGetPlatformInfo( p, i, 0, NULL, &required ), "Failed to get OpenCL platform information" );
char *buff = (char*)alloca( required );
enforce_cl_retcode( clGetPlatformInfo( p, i, required, buff, NULL ), "Failed to get OpenCL platform information" );
return buff;
}
class opencl_device {
public:
typedef size_t device_id_type;
enum : device_id_type {
unknown = device_id_type( -2 ),
host = device_id_type( -1 )
};
opencl_device() : my_device_id( unknown ) {}
opencl_device( cl_device_id cl_d_id, device_id_type device_id ) : my_device_id( device_id ), my_cl_device_id( cl_d_id ) {}
std::string platform_profile() const {
return platform_info<std::string>( platform(), CL_PLATFORM_PROFILE );
}
std::string platform_version() const {
return platform_info<std::string>( platform(), CL_PLATFORM_VERSION );
}
std::string platform_name() const {
return platform_info<std::string>( platform(), CL_PLATFORM_NAME );
}
std::string platform_vendor() const {
return platform_info<std::string>( platform(), CL_PLATFORM_VENDOR );
}
std::string platform_extensions() const {
return platform_info<std::string>( platform(), CL_PLATFORM_EXTENSIONS );
}
template <typename T>
void info( cl_device_info i, T &t ) const {
t = device_info<T>( my_cl_device_id, i );
}
std::string version() const {
// The version string format: OpenCL<space><major_version.minor_version><space><vendor-specific information>
return device_info<std::string>( my_cl_device_id, CL_DEVICE_VERSION );
}
int major_version() const {
int major;
std::sscanf( version().c_str(), "OpenCL %d", &major );
return major;
}
int minor_version() const {
int major, minor;
std::sscanf( version().c_str(), "OpenCL %d.%d", &major, &minor );
return minor;
}
bool out_of_order_exec_mode_on_host_present() const {
#if CL_VERSION_2_0
if ( major_version() >= 2 )
return (device_info<cl_command_queue_properties>( my_cl_device_id, CL_DEVICE_QUEUE_ON_HOST_PROPERTIES ) & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) != 0;
else
#endif /* CL_VERSION_2_0 */
return (device_info<cl_command_queue_properties>( my_cl_device_id, CL_DEVICE_QUEUE_PROPERTIES ) & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) != 0;
}
bool out_of_order_exec_mode_on_device_present() const {
#if CL_VERSION_2_0
if ( major_version() >= 2 )
return (device_info<cl_command_queue_properties>( my_cl_device_id, CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES ) & CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) != 0;
else
#endif /* CL_VERSION_2_0 */
return false;
}
std::array<size_t, 3> max_work_item_sizes() const {
return device_info<std::array<size_t, 3>>( my_cl_device_id, CL_DEVICE_MAX_WORK_ITEM_SIZES );
}
size_t max_work_group_size() const {
return device_info<size_t>( my_cl_device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE );
}
bool built_in_kernel_available( const std::string& k ) const {
const std::string semi = ";";
// Added semicolumns to force an exact match (to avoid a partial match, e.g. "add" is partly matched with "madd").
return (semi + built_in_kernels() + semi).find( semi + k + semi ) != std::string::npos;
}
std::string built_in_kernels() const {
return device_info<std::string>( my_cl_device_id, CL_DEVICE_BUILT_IN_KERNELS );
}
std::string name() const {
return device_info<std::string>( my_cl_device_id, CL_DEVICE_NAME );
}
cl_bool available() const {
return device_info<cl_bool>( my_cl_device_id, CL_DEVICE_AVAILABLE );
}
cl_bool compiler_available() const {
return device_info<cl_bool>( my_cl_device_id, CL_DEVICE_COMPILER_AVAILABLE );
}
cl_bool linker_available() const {
return device_info<cl_bool>( my_cl_device_id, CL_DEVICE_LINKER_AVAILABLE );
}
bool extension_available( const std::string &ext ) const {
const std::string space = " ";
// Added space to force an exact match (to avoid a partial match, e.g. "ext" is partly matched with "ext2").
return (space + extensions() + space).find( space + ext + space ) != std::string::npos;
}
std::string extensions() const {
return device_info<std::string>( my_cl_device_id, CL_DEVICE_EXTENSIONS );
}
cl_device_type type() const {
return device_info<cl_device_type>( my_cl_device_id, CL_DEVICE_TYPE );
}
std::string vendor() const {
return device_info<std::string>( my_cl_device_id, CL_DEVICE_VENDOR );
}
cl_uint address_bits() const {
return device_info<cl_uint>( my_cl_device_id, CL_DEVICE_ADDRESS_BITS );
}
cl_device_id device_id() const {
return my_cl_device_id;
}
cl_command_queue command_queue() const {
return my_cl_command_queue;
}
void set_command_queue( cl_command_queue cmd_queue ) {
my_cl_command_queue = cmd_queue;
}
private:
opencl_device( cl_device_id d_id ) : my_device_id( unknown ), my_cl_device_id( d_id ) {}
cl_platform_id platform() const {
return device_info<cl_platform_id>( my_cl_device_id, CL_DEVICE_PLATFORM );
}
device_id_type my_device_id;
cl_device_id my_cl_device_id;
cl_command_queue my_cl_command_queue;
friend bool operator==(opencl_device d1, opencl_device d2) { return d1.my_cl_device_id == d2.my_cl_device_id; }
template <typename DeviceFilter>
friend class opencl_factory;
template <typename Factory>
friend class opencl_memory;
template <typename Factory>
friend class opencl_program;
friend class opencl_foundation;
#if TBB_USE_ASSERT
template <typename T, typename Factory>
friend class opencl_buffer;
#endif
};
class opencl_device_list {
typedef std::vector<opencl_device> container_type;
public:
typedef container_type::iterator iterator;
typedef container_type::const_iterator const_iterator;
typedef container_type::size_type size_type;
opencl_device_list() {}
opencl_device_list( std::initializer_list<opencl_device> il ) : my_container( il ) {}
void add( opencl_device d ) { my_container.push_back( d ); }
size_type size() const { return my_container.size(); }
bool empty() const { return my_container.empty(); }
iterator begin() { return my_container.begin(); }
iterator end() { return my_container.end(); }
const_iterator begin() const { return my_container.begin(); }
const_iterator end() const { return my_container.end(); }
const_iterator cbegin() const { return my_container.cbegin(); }
const_iterator cend() const { return my_container.cend(); }
private:
container_type my_container;
};
class callback_base : tbb::internal::no_copy {
public:
virtual void call() = 0;
virtual ~callback_base() {}
};
template <typename Callback, typename T>
class callback : public callback_base {
graph &my_graph;
Callback my_callback;
T my_data;
public:
callback( graph &g, Callback c, const T& t ) : my_graph( g ), my_callback( c ), my_data( t ) {
// Extend the graph lifetime until the callback completion.
my_graph.increment_wait_count();
}
~callback() {
// Release the reference to the graph.
my_graph.decrement_wait_count();
}
void call() __TBB_override {
my_callback( my_data );
}
};
template <typename T, typename Factory = default_opencl_factory>
class dependency_msg : public async_msg<T> {
public:
typedef T value_type;
dependency_msg() : my_callback_flag_ptr( std::make_shared< tbb::atomic<bool>>() ) {
my_callback_flag_ptr->store<tbb::relaxed>(false);
}
explicit dependency_msg( const T& data ) : my_data(data), my_callback_flag_ptr( std::make_shared<tbb::atomic<bool>>() ) {
my_callback_flag_ptr->store<tbb::relaxed>(false);
}
dependency_msg( opencl_graph &g, const T& data ) : my_data(data), my_graph(&g), my_callback_flag_ptr( std::make_shared<tbb::atomic<bool>>() ) {
my_callback_flag_ptr->store<tbb::relaxed>(false);
}
dependency_msg( const T& data, cl_event event ) : my_data(data), my_event(event), my_is_event(true), my_callback_flag_ptr( std::make_shared<tbb::atomic<bool>>() ) {
my_callback_flag_ptr->store<tbb::relaxed>(false);
enforce_cl_retcode( clRetainEvent( my_event ), "Failed to retain an event" );
}
T& data( bool wait = true ) {
if ( my_is_event && wait ) {
enforce_cl_retcode( clWaitForEvents( 1, &my_event ), "Failed to wait for an event" );
enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" );
my_is_event = false;
}
return my_data;
}
const T& data( bool wait = true ) const {
if ( my_is_event && wait ) {
enforce_cl_retcode( clWaitForEvents( 1, &my_event ), "Failed to wait for an event" );
enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" );
my_is_event = false;
}
return my_data;
}
dependency_msg( const dependency_msg &dmsg ) : async_msg<T>(dmsg),
my_data(dmsg.my_data), my_event(dmsg.my_event), my_is_event( dmsg.my_is_event ), my_graph( dmsg.my_graph ),
my_callback_flag_ptr(dmsg.my_callback_flag_ptr)
{
if ( my_is_event )
enforce_cl_retcode( clRetainEvent( my_event ), "Failed to retain an event" );
}
dependency_msg( dependency_msg &&dmsg ) : async_msg<T>(std::move(dmsg)),
my_data(std::move(dmsg.my_data)), my_event(dmsg.my_event), my_is_event(dmsg.my_is_event), my_graph(dmsg.my_graph),
my_callback_flag_ptr( std::move(dmsg.my_callback_flag_ptr) )
{
dmsg.my_is_event = false;
}
dependency_msg& operator=(const dependency_msg &dmsg) {
async_msg<T>::operator =(dmsg);
// Release original event
if ( my_is_event )
enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to retain an event" );
my_data = dmsg.my_data;
my_event = dmsg.my_event;
my_is_event = dmsg.my_is_event;
my_graph = dmsg.my_graph;
// Retain copied event
if ( my_is_event )
enforce_cl_retcode( clRetainEvent( my_event ), "Failed to retain an event" );
my_callback_flag_ptr = dmsg.my_callback_flag_ptr;
return *this;
}
~dependency_msg() {
if ( my_is_event )
enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" );
}
cl_event const * get_event() const { return my_is_event ? &my_event : NULL; }
void set_event( cl_event e ) const {
if ( my_is_event ) {
cl_command_queue cq = event_info<cl_command_queue>( my_event, CL_EVENT_COMMAND_QUEUE );
if ( cq != event_info<cl_command_queue>( e, CL_EVENT_COMMAND_QUEUE ) )
enforce_cl_retcode( clFlush( cq ), "Failed to flush an OpenCL command queue" );
enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" );
}
my_is_event = true;
my_event = e;
clRetainEvent( my_event );
}
void set_graph( graph &g ) {
my_graph = &g;
}
void clear_event() const {
if ( my_is_event ) {
enforce_cl_retcode( clFlush( event_info<cl_command_queue>( my_event, CL_EVENT_COMMAND_QUEUE ) ), "Failed to flush an OpenCL command queue" );
enforce_cl_retcode( clReleaseEvent( my_event ), "Failed to release an event" );
}
my_is_event = false;
}
template <typename Callback>
void register_callback( Callback c ) const {
__TBB_ASSERT( my_is_event, "The OpenCL event is not set" );
__TBB_ASSERT( my_graph, "The graph is not set" );
enforce_cl_retcode( clSetEventCallback( my_event, CL_COMPLETE, register_callback_func, new callback<Callback, T>( *my_graph, c, my_data ) ), "Failed to set an OpenCL callback" );
}
operator T&() { return data(); }
operator const T&() const { return data(); }
protected:
// Overridden in this derived class to inform that
// async calculation chain is over
void finalize() const __TBB_override {
receive_if_memory_object(*this);
if (! my_callback_flag_ptr->fetch_and_store(true)) {
dependency_msg a(*this);
if (my_is_event) {
register_callback([a](const T& t) mutable {
a.set(t);
});
}
else {
a.set(my_data);
}
}
clear_event();
}
private:
static void CL_CALLBACK register_callback_func( cl_event, cl_int event_command_exec_status, void *data ) {
tbb::internal::suppress_unused_warning( event_command_exec_status );
__TBB_ASSERT( event_command_exec_status == CL_COMPLETE, NULL );
__TBB_ASSERT( data, NULL );
callback_base *c = static_cast<callback_base*>(data);
c->call();
delete c;
}
T my_data;
mutable cl_event my_event;
mutable bool my_is_event = false;
graph *my_graph = NULL;
std::shared_ptr< tbb::atomic<bool> > my_callback_flag_ptr;
};
template <typename K, typename T, typename Factory>
K key_from_message( const dependency_msg<T, Factory> &dmsg ) {
using tbb::flow::key_from_message;
const T &t = dmsg.data( false );
__TBB_STATIC_ASSERT( true, "" );
return key_from_message<K, T>( t );
}
template <typename Factory>
class opencl_memory {
public:
opencl_memory() {}
opencl_memory( Factory &f ) : my_host_ptr( NULL ), my_factory( &f ), my_sending_event_present( false ) {
my_curr_device_id = my_factory->devices().begin()->my_device_id;
}
~opencl_memory() {
if ( my_sending_event_present ) enforce_cl_retcode( clReleaseEvent( my_sending_event ), "Failed to release an event for the OpenCL buffer" );
enforce_cl_retcode( clReleaseMemObject( my_cl_mem ), "Failed to release an memory object" );
}
cl_mem get_cl_mem() const {
return my_cl_mem;
}
void* get_host_ptr() {
if ( !my_host_ptr ) {
dependency_msg<void*, Factory> d = receive( NULL );
d.data();
__TBB_ASSERT( d.data() == my_host_ptr, NULL );
}
return my_host_ptr;
}
Factory *factory() const { return my_factory; }
dependency_msg<void*, Factory> send( opencl_device d, const cl_event *e );
dependency_msg<void*, Factory> receive( const cl_event *e );
virtual void map_memory( opencl_device, dependency_msg<void*, Factory> & ) = 0;
protected:
cl_mem my_cl_mem;
tbb::atomic<opencl_device::device_id_type> my_curr_device_id;
void* my_host_ptr;
Factory *my_factory;
tbb::spin_mutex my_sending_lock;
bool my_sending_event_present;
cl_event my_sending_event;
};
template <typename Factory>
class opencl_buffer_impl : public opencl_memory<Factory> {
size_t my_size;
public:
opencl_buffer_impl( size_t size, Factory& f ) : opencl_memory<Factory>( f ), my_size( size ) {
cl_int err;
this->my_cl_mem = clCreateBuffer( this->my_factory->context(), CL_MEM_ALLOC_HOST_PTR, size, NULL, &err );
enforce_cl_retcode( err, "Failed to create an OpenCL buffer" );
}
// The constructor for subbuffers.
opencl_buffer_impl( cl_mem m, size_t index, size_t size, Factory& f ) : opencl_memory<Factory>( f ), my_size( size ) {
cl_int err;
cl_buffer_region region = { index, size };
this->my_cl_mem = clCreateSubBuffer( m, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err );
enforce_cl_retcode( err, "Failed to create an OpenCL subbuffer" );
}
size_t size() const {
return my_size;
}
void map_memory( opencl_device device, dependency_msg<void*, Factory> &dmsg ) __TBB_override {
this->my_factory->enque_map_buffer( device, *this, dmsg );
}
#if TBB_USE_ASSERT
template <typename, typename>
friend class opencl_buffer;
#endif
};
enum access_type {
read_write,
write_only,
read_only
};
template <typename T, typename Factory = default_opencl_factory>
class opencl_subbuffer;
template <typename T, typename Factory = default_opencl_factory>
class opencl_buffer {
public:
typedef cl_mem native_object_type;
typedef opencl_buffer memory_object_type;
typedef Factory opencl_factory_type;
template<access_type a> using iterator = T*;
template <access_type a>
iterator<a> access() const {
T* ptr = (T*)my_impl->get_host_ptr();
__TBB_ASSERT( ptr, NULL );
return iterator<a>( ptr );
}
T* data() const { return &access<read_write>()[0]; }
template <access_type a = read_write>
iterator<a> begin() const { return access<a>(); }
template <access_type a = read_write>
iterator<a> end() const { return access<a>()+my_impl->size()/sizeof(T); }
size_t size() const { return my_impl->size()/sizeof(T); }
T& operator[] ( ptrdiff_t k ) { return begin()[k]; }
opencl_buffer() {}
opencl_buffer( opencl_graph &g, size_t size );
opencl_buffer( Factory &f, size_t size ) : my_impl( std::make_shared<impl_type>( size*sizeof(T), f ) ) {}
cl_mem native_object() const {
return my_impl->get_cl_mem();
}
const opencl_buffer& memory_object() const {
return *this;
}
void send( opencl_device device, dependency_msg<opencl_buffer, Factory> &dependency ) const {
__TBB_ASSERT( dependency.data( /*wait = */false ) == *this, NULL );
dependency_msg<void*, Factory> d = my_impl->send( device, dependency.get_event() );
const cl_event *e = d.get_event();
if ( e ) dependency.set_event( *e );
else dependency.clear_event();
}
void receive( const dependency_msg<opencl_buffer, Factory> &dependency ) const {
__TBB_ASSERT( dependency.data( /*wait = */false ) == *this, NULL );
dependency_msg<void*, Factory> d = my_impl->receive( dependency.get_event() );
const cl_event *e = d.get_event();
if ( e ) dependency.set_event( *e );
else dependency.clear_event();
}
opencl_subbuffer<T, Factory> subbuffer( size_t index, size_t size ) const;
private:
// The constructor for subbuffers.
opencl_buffer( Factory &f, cl_mem m, size_t index, size_t size ) : my_impl( std::make_shared<impl_type>( m, index*sizeof(T), size*sizeof(T), f ) ) {}
typedef opencl_buffer_impl<Factory> impl_type;
std::shared_ptr<impl_type> my_impl;
friend bool operator==(const opencl_buffer<T, Factory> &lhs, const opencl_buffer<T, Factory> &rhs) {
return lhs.my_impl == rhs.my_impl;
}
template <typename>
friend class opencl_factory;
template <typename, typename>
friend class opencl_subbuffer;
};
template <typename T, typename Factory>
class opencl_subbuffer : public opencl_buffer<T, Factory> {
opencl_buffer<T, Factory> my_owner;
public:
opencl_subbuffer() {}
opencl_subbuffer( const opencl_buffer<T, Factory> &owner, size_t index, size_t size ) :
opencl_buffer<T, Factory>( *owner.my_impl->factory(), owner.native_object(), index, size ), my_owner( owner ) {}
};
template <typename T, typename Factory>
opencl_subbuffer<T, Factory> opencl_buffer<T, Factory>::subbuffer( size_t index, size_t size ) const {
return opencl_subbuffer<T, Factory>( *this, index, size );
}
#define is_typedef(type) \
template <typename T> \
struct is_##type { \
template <typename C> \
static std::true_type check( typename C::type* ); \
template <typename C> \
static std::false_type check( ... ); \
\
static const bool value = decltype(check<T>(0))::value; \
}
is_typedef( native_object_type );
is_typedef( memory_object_type );
template <typename T>
typename std::enable_if<is_native_object_type<T>::value, typename T::native_object_type>::type get_native_object( const T &t ) {
return t.native_object();
}
template <typename T>
typename std::enable_if<!is_native_object_type<T>::value, T>::type get_native_object( T t ) {
return t;
}
// send_if_memory_object checks if the T type has memory_object_type and call the send method for the object.
template <typename T, typename Factory>
typename std::enable_if<is_memory_object_type<T>::value>::type send_if_memory_object( opencl_device device, dependency_msg<T, Factory> &dmsg ) {
const T &t = dmsg.data( false );
typedef typename T::memory_object_type mem_obj_t;
mem_obj_t mem_obj = t.memory_object();
dependency_msg<mem_obj_t, Factory> d( mem_obj );
if ( dmsg.get_event() ) d.set_event( *dmsg.get_event() );
mem_obj.send( device, d );
if ( d.get_event() ) dmsg.set_event( *d.get_event() );
}
template <typename T>
typename std::enable_if<is_memory_object_type<T>::value>::type send_if_memory_object( opencl_device device, T &t ) {
typedef typename T::memory_object_type mem_obj_t;
mem_obj_t mem_obj = t.memory_object();
dependency_msg<mem_obj_t, typename mem_obj_t::opencl_factory_type> dmsg( mem_obj );
mem_obj.send( device, dmsg );
}
template <typename T>
typename std::enable_if<!is_memory_object_type<T>::value>::type send_if_memory_object( opencl_device, T& ) {};
// receive_if_memory_object checks if the T type has memory_object_type and call the receive method for the object.
template <typename T, typename Factory>
typename std::enable_if<is_memory_object_type<T>::value>::type receive_if_memory_object( const dependency_msg<T, Factory> &dmsg ) {
const T &t = dmsg.data( false );
typedef typename T::memory_object_type mem_obj_t;
mem_obj_t mem_obj = t.memory_object();
dependency_msg<mem_obj_t, Factory> d( mem_obj );
if ( dmsg.get_event() ) d.set_event( *dmsg.get_event() );
mem_obj.receive( d );
if ( d.get_event() ) dmsg.set_event( *d.get_event() );
}
template <typename T>
typename std::enable_if<!is_memory_object_type<T>::value>::type receive_if_memory_object( const T& ) {}
class opencl_range {
public:
typedef size_t range_index_type;
typedef std::array<range_index_type, 3> nd_range_type;
template <typename G = std::initializer_list<int>, typename L = std::initializer_list<int>,
typename = typename std::enable_if<!std::is_same<typename std::decay<G>::type, opencl_range>::value>::type>
opencl_range(G&& global_work = std::initializer_list<int>({ 0 }), L&& local_work = std::initializer_list<int>({ 0, 0, 0 })) {
auto g_it = global_work.begin();
auto l_it = local_work.begin();
my_global_work_size = { size_t(-1), size_t(-1), size_t(-1) };
// my_local_work_size is still uninitialized
for (int s = 0; s < 3 && g_it != global_work.end(); ++g_it, ++l_it, ++s) {
__TBB_ASSERT(l_it != local_work.end(), "global_work & local_work must have same size");
my_global_work_size[s] = *g_it;
my_local_work_size[s] = *l_it;
}
}
const nd_range_type& global_range() const { return my_global_work_size; }
const nd_range_type& local_range() const { return my_local_work_size; }
private:
nd_range_type my_global_work_size;
nd_range_type my_local_work_size;
};
template <typename DeviceFilter>
class opencl_factory {
public:
template<typename T> using async_msg_type = dependency_msg<T, opencl_factory<DeviceFilter>>;
typedef opencl_device device_type;
class kernel : tbb::internal::no_assign {
public:
kernel( const kernel& k ) : my_factory( k.my_factory ) {
// Clone my_cl_kernel via opencl_program
size_t ret_size = 0;
std::vector<char> kernel_name;
for ( size_t curr_size = 32;; curr_size <<= 1 ) {
kernel_name.resize( curr_size <<= 1 );
enforce_cl_retcode( clGetKernelInfo( k.my_cl_kernel, CL_KERNEL_FUNCTION_NAME, curr_size, kernel_name.data(), &ret_size ), "Failed to get kernel info" );
if ( ret_size < curr_size ) break;
}
cl_program program;
enforce_cl_retcode( clGetKernelInfo( k.my_cl_kernel, CL_KERNEL_PROGRAM, sizeof(program), &program, &ret_size ), "Failed to get kernel info" );
__TBB_ASSERT( ret_size == sizeof(program), NULL );
my_cl_kernel = opencl_program< factory_type >( my_factory, program ).get_cl_kernel( kernel_name.data() );
}
~kernel() {
enforce_cl_retcode( clReleaseKernel( my_cl_kernel ), "Failed to release a kernel" );
}
private:
typedef opencl_factory<DeviceFilter> factory_type;
kernel( const cl_kernel& k, factory_type& f ) : my_cl_kernel( k ), my_factory( f ) {}
// Data
cl_kernel my_cl_kernel;
factory_type& my_factory;
template <typename DeviceFilter_>
friend class opencl_factory;
template <typename Factory>
friend class opencl_program;
};
typedef kernel kernel_type;
// 'range_type' enables kernel_executor with range support
// it affects expectations for enqueue_kernel(.....) interface method
typedef opencl_range range_type;
opencl_factory( opencl_graph &g ) : my_graph( g ) {}
~opencl_factory() {
if ( my_devices.size() ) {
for ( auto d = my_devices.begin(); d != my_devices.end(); ++d ) {
enforce_cl_retcode( clReleaseCommandQueue( (*d).my_cl_command_queue ), "Failed to release a command queue" );
}
enforce_cl_retcode( clReleaseContext( my_cl_context ), "Failed to release a context" );
}
}
bool init( const opencl_device_list &device_list ) {
tbb::spin_mutex::scoped_lock lock( my_devices_mutex );
if ( !my_devices.size() ) {
my_devices = device_list;
return true;
}
return false;
}
private:
template <typename Factory>
void enque_map_buffer( opencl_device device, opencl_buffer_impl<Factory> &buffer, dependency_msg<void*, Factory>& dmsg ) {
cl_event const* e1 = dmsg.get_event();
cl_event e2;
cl_int err;
void *ptr = clEnqueueMapBuffer( device.my_cl_command_queue, buffer.get_cl_mem(), false, CL_MAP_READ | CL_MAP_WRITE, 0, buffer.size(),
e1 == NULL ? 0 : 1, e1, &e2, &err );
enforce_cl_retcode( err, "Failed to map a buffer" );
dmsg.data( false ) = ptr;
dmsg.set_event( e2 );
enforce_cl_retcode( clReleaseEvent( e2 ), "Failed to release an event" );
}
template <typename Factory>
void enque_unmap_buffer( opencl_device device, opencl_memory<Factory> &memory, dependency_msg<void*, Factory>& dmsg ) {
cl_event const* e1 = dmsg.get_event();
cl_event e2;
enforce_cl_retcode(
clEnqueueUnmapMemObject( device.my_cl_command_queue, memory.get_cl_mem(), memory.get_host_ptr(), e1 == NULL ? 0 : 1, e1, &e2 ),
"Failed to unmap a buffer" );
dmsg.set_event( e2 );
enforce_cl_retcode( clReleaseEvent( e2 ), "Failed to release an event" );
}
// --------- Kernel argument & event list helpers --------- //
template <size_t NUM_ARGS, typename T>
void process_one_arg( const kernel_type& kernel, std::array<cl_event, NUM_ARGS>&, int&, int& place, const T& t ) {
auto p = get_native_object(t);
enforce_cl_retcode( clSetKernelArg(kernel.my_cl_kernel, place++, sizeof(p), &p), "Failed to set a kernel argument" );
}
template <size_t NUM_ARGS, typename T, typename F>
void process_one_arg( const kernel_type& kernel, std::array<cl_event, NUM_ARGS>& events, int& num_events, int& place, const dependency_msg<T, F>& msg ) {
__TBB_ASSERT((static_cast<typename std::array<cl_event, NUM_ARGS>::size_type>(num_events) < events.size()), NULL);
const cl_event * const e = msg.get_event();
if (e != NULL) {
events[num_events++] = *e;
}
process_one_arg( kernel, events, num_events, place, msg.data(false) );
}
template <size_t NUM_ARGS, typename T, typename ...Rest>
void process_arg_list( const kernel_type& kernel, std::array<cl_event, NUM_ARGS>& events, int& num_events, int& place, const T& t, const Rest&... args ) {
process_one_arg( kernel, events, num_events, place, t );
process_arg_list( kernel, events, num_events, place, args... );
}
template <size_t NUM_ARGS>
void process_arg_list( const kernel_type&, std::array<cl_event, NUM_ARGS>&, int&, int& ) {}
// ------------------------------------------- //
template <typename T>
void update_one_arg( cl_event, T& ) {}
template <typename T, typename F>
void update_one_arg( cl_event e, dependency_msg<T, F>& msg ) {
msg.set_event( e );
msg.set_graph( my_graph );
}
template <typename T, typename ...Rest>
void update_arg_list( cl_event e, T& t, Rest&... args ) {
update_one_arg( e, t );
update_arg_list( e, args... );
}
void update_arg_list( cl_event ) {}
// ------------------------------------------- //
public:
template <typename ...Args>
void send_kernel( opencl_device device, const kernel_type& kernel, const range_type& work_size, Args&... args ) {
std::array<cl_event, sizeof...(Args)> events;
int num_events = 0;
int place = 0;
process_arg_list( kernel, events, num_events, place, args... );
const cl_event e = send_kernel_impl( device, kernel.my_cl_kernel, work_size, num_events, events.data() );
update_arg_list(e, args...);
// Release our own reference to cl_event
enforce_cl_retcode( clReleaseEvent(e), "Failed to release an event" );
}
// ------------------------------------------- //
template <typename T, typename ...Rest>
void send_data(opencl_device device, T& t, Rest&... args) {
send_if_memory_object( device, t );
send_data( device, args... );
}
void send_data(opencl_device) {}
// ------------------------------------------- //
private:
cl_event send_kernel_impl( opencl_device device, const cl_kernel& kernel,
const range_type& work_size, cl_uint num_events, cl_event* event_list ) {
const typename range_type::nd_range_type g_offset = { { 0, 0, 0 } };
const typename range_type::nd_range_type& g_size = work_size.global_range();
const typename range_type::nd_range_type& l_size = work_size.local_range();
cl_uint s;
for ( s = 1; s < 3 && g_size[s] != size_t(-1); ++s) {}
cl_event event;
enforce_cl_retcode(
clEnqueueNDRangeKernel( device.my_cl_command_queue, kernel, s,
g_offset.data(), g_size.data(), l_size[0] ? l_size.data() : NULL, num_events, num_events ? event_list : NULL, &event ),
"Failed to enqueue a kernel" );
return event;
}
// ------------------------------------------- //
template <typename T>
bool get_event_from_one_arg( cl_event&, const T& ) {
return false;
}
template <typename T, typename F>
bool get_event_from_one_arg( cl_event& e, const dependency_msg<T, F>& msg) {
cl_event const *e_ptr = msg.get_event();
if ( e_ptr != NULL ) {
e = *e_ptr;
return true;
}
return false;
}
template <typename T, typename ...Rest>
bool get_event_from_args( cl_event& e, const T& t, const Rest&... args ) {
if ( get_event_from_one_arg( e, t ) ) {
return true;
}
return get_event_from_args( e, args... );
}
bool get_event_from_args( cl_event& ) {
return false;
}
// ------------------------------------------- //
struct finalize_fn : tbb::internal::no_assign {
virtual ~finalize_fn() {}
virtual void operator() () {}
};
template<typename Fn>
struct finalize_fn_leaf : public finalize_fn {
Fn my_fn;
finalize_fn_leaf(Fn fn) : my_fn(fn) {}
void operator() () __TBB_override { my_fn(); }
};
static void CL_CALLBACK finalize_callback(cl_event, cl_int event_command_exec_status, void *data) {
tbb::internal::suppress_unused_warning(event_command_exec_status);
__TBB_ASSERT(event_command_exec_status == CL_COMPLETE, NULL);
finalize_fn * const fn_ptr = static_cast<finalize_fn*>(data);
__TBB_ASSERT(fn_ptr != NULL, "Invalid finalize function pointer");
(*fn_ptr)();
// Function pointer was created by 'new' & this callback must be called once only
delete fn_ptr;
}
public:
template <typename FinalizeFn, typename ...Args>
void finalize( opencl_device device, FinalizeFn fn, Args&... args ) {
cl_event e;
if ( get_event_from_args( e, args... ) ) {
enforce_cl_retcode( clSetEventCallback( e, CL_COMPLETE, finalize_callback,
new finalize_fn_leaf<FinalizeFn>(fn) ), "Failed to set a callback" );
}
enforce_cl_retcode( clFlush( device.my_cl_command_queue ), "Failed to flush an OpenCL command queue" );
}
const opencl_device_list& devices() {
std::call_once( my_once_flag, &opencl_factory::init_once, this );
return my_devices;
}
private:
bool is_same_context( opencl_device::device_id_type d1, opencl_device::device_id_type d2 ) {
__TBB_ASSERT( d1 != opencl_device::unknown && d2 != opencl_device::unknown, NULL );
// Currently, factory supports only one context so if the both devices are not host it means the are in the same context.
if ( d1 != opencl_device::host && d2 != opencl_device::host )
return true;
return d1 == d2;
}
private:
opencl_factory( const opencl_factory& );
opencl_factory& operator=(const opencl_factory&);
cl_context context() {
std::call_once( my_once_flag, &opencl_factory::init_once, this );
return my_cl_context;
}
void init_once();
std::once_flag my_once_flag;
opencl_device_list my_devices;
cl_context my_cl_context;
opencl_graph &my_graph;
tbb::spin_mutex my_devices_mutex;
template <typename Factory>
friend class opencl_program;
template <typename Factory>
friend class opencl_buffer_impl;
template <typename Factory>
friend class opencl_memory;
};
template <typename Factory>
dependency_msg<void*, Factory> opencl_memory<Factory>::receive( const cl_event *e ) {
dependency_msg<void*, Factory> d = e ? dependency_msg<void*, Factory>( my_host_ptr, *e ) : dependency_msg<void*, Factory>( my_host_ptr );
// Concurrent receives are prohibited so we do not worry about synchronization.
if ( my_curr_device_id.load<tbb::relaxed>() != opencl_device::host ) {
map_memory( *my_factory->devices().begin(), d );
my_curr_device_id.store<tbb::relaxed>( opencl_device::host );
my_host_ptr = d.data( false );
}
// Release the sending event
if ( my_sending_event_present ) {
enforce_cl_retcode( clReleaseEvent( my_sending_event ), "Failed to release an event" );
my_sending_event_present = false;
}
return d;
}
template <typename Factory>
dependency_msg<void*, Factory> opencl_memory<Factory>::send( opencl_device device, const cl_event *e ) {
opencl_device::device_id_type device_id = device.my_device_id;
if ( !my_factory->is_same_context( my_curr_device_id.load<tbb::acquire>(), device_id ) ) {
{
tbb::spin_mutex::scoped_lock lock( my_sending_lock );
if ( !my_factory->is_same_context( my_curr_device_id.load<tbb::relaxed>(), device_id ) ) {
__TBB_ASSERT( my_host_ptr, "The buffer has not been mapped" );
dependency_msg<void*, Factory> d( my_host_ptr );
my_factory->enque_unmap_buffer( device, *this, d );
my_sending_event = *d.get_event();
my_sending_event_present = true;
enforce_cl_retcode( clRetainEvent( my_sending_event ), "Failed to retain an event" );
my_host_ptr = NULL;
my_curr_device_id.store<tbb::release>(device_id);
}
}
__TBB_ASSERT( my_sending_event_present, NULL );
}
// !e means that buffer has come from the host
if ( !e && my_sending_event_present ) e = &my_sending_event;
__TBB_ASSERT( !my_host_ptr, "The buffer has not been unmapped" );
return e ? dependency_msg<void*, Factory>( NULL, *e ) : dependency_msg<void*, Factory>( NULL );
}
struct default_opencl_factory_device_filter {
opencl_device_list operator()( const opencl_device_list &devices ) {
opencl_device_list dl;
dl.add( *devices.begin() );
return dl;
}
};
class default_opencl_factory : public opencl_factory < default_opencl_factory_device_filter > {
public:
template<typename T> using async_msg_type = dependency_msg<T, default_opencl_factory>;
default_opencl_factory( opencl_graph &g ) : opencl_factory( g ) {}
private:
default_opencl_factory( const default_opencl_factory& );
default_opencl_factory& operator=(const default_opencl_factory&);
};
class opencl_foundation : tbb::internal::no_assign {
struct default_device_selector_type {
opencl_device operator()( default_opencl_factory& f ) {
__TBB_ASSERT( ! f.devices().empty(), "No available devices" );
return *( f.devices().begin() );
}
};
public:
opencl_foundation(opencl_graph &g) : my_default_opencl_factory(g), my_default_device_selector() {
cl_uint num_platforms;
enforce_cl_retcode(clGetPlatformIDs(0, NULL, &num_platforms), "clGetPlatformIDs failed");
std::vector<cl_platform_id> platforms(num_platforms);
enforce_cl_retcode(clGetPlatformIDs(num_platforms, platforms.data(), NULL), "clGetPlatformIDs failed");
cl_uint num_devices;
std::vector<cl_platform_id>::iterator platforms_it = platforms.begin();
cl_uint num_all_devices = 0;
while (platforms_it != platforms.end()) {
cl_int err = clGetDeviceIDs(*platforms_it, CL_DEVICE_TYPE_ALL, 0, NULL, &num_devices);
if (err == CL_DEVICE_NOT_FOUND) {
platforms_it = platforms.erase(platforms_it);
} else {
enforce_cl_retcode(err, "clGetDeviceIDs failed");
num_all_devices += num_devices;
++platforms_it;
}
}
std::vector<cl_device_id> devices(num_all_devices);
std::vector<cl_device_id>::iterator devices_it = devices.begin();
for (auto p = platforms.begin(); p != platforms.end(); ++p) {
enforce_cl_retcode(clGetDeviceIDs((*p), CL_DEVICE_TYPE_ALL, (cl_uint)std::distance(devices_it, devices.end()), &*devices_it, &num_devices), "clGetDeviceIDs failed");
devices_it += num_devices;
}
for (auto d = devices.begin(); d != devices.end(); ++d) {
my_devices.add(opencl_device((*d)));
}
}
default_opencl_factory &get_default_opencl_factory() {
return my_default_opencl_factory;
}
const opencl_device_list &get_all_devices() {
return my_devices;
}
default_device_selector_type get_default_device_selector() { return my_default_device_selector; }
private:
default_opencl_factory my_default_opencl_factory;
opencl_device_list my_devices;
const default_device_selector_type my_default_device_selector;
};
opencl_foundation &opencl_graph::get_opencl_foundation() {
opencl_foundation* INITIALIZATION = (opencl_foundation*)1;
if ( my_opencl_foundation <= INITIALIZATION ) {
if ( tbb::internal::as_atomic( my_opencl_foundation ).compare_and_swap( INITIALIZATION, NULL ) == 0 ) {
my_opencl_foundation = new opencl_foundation( *this );
}
else {
tbb::internal::spin_wait_while_eq( my_opencl_foundation, INITIALIZATION );
}
}
__TBB_ASSERT( my_opencl_foundation > INITIALIZATION, "opencl_foundation is not initialized");
return *my_opencl_foundation;
}
opencl_graph::~opencl_graph() {
if ( my_opencl_foundation )
delete my_opencl_foundation;
}
template <typename DeviceFilter>
void opencl_factory<DeviceFilter>::init_once() {
{
tbb::spin_mutex::scoped_lock lock( my_devices_mutex );
if ( !my_devices.size() )
my_devices = DeviceFilter()(my_graph.get_opencl_foundation().get_all_devices());
}
enforce_cl_retcode( my_devices.size() ? CL_SUCCESS : CL_INVALID_DEVICE, "No devices in the device list" );
cl_platform_id platform_id = my_devices.begin()->platform();
for ( opencl_device_list::iterator it = ++my_devices.begin(); it != my_devices.end(); ++it )
enforce_cl_retcode( it->platform() == platform_id ? CL_SUCCESS : CL_INVALID_PLATFORM, "All devices should be in the same platform" );
std::vector<cl_device_id> cl_device_ids;
for (auto d = my_devices.begin(); d != my_devices.end(); ++d) {
cl_device_ids.push_back((*d).my_cl_device_id);
}
cl_context_properties context_properties[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)platform_id, (cl_context_properties)NULL };
cl_int err;
cl_context ctx = clCreateContext( context_properties,
(cl_uint)cl_device_ids.size(),
cl_device_ids.data(),
NULL, NULL, &err );
enforce_cl_retcode( err, "Failed to create context" );
my_cl_context = ctx;
size_t device_counter = 0;
for ( auto d = my_devices.begin(); d != my_devices.end(); d++ ) {
(*d).my_device_id = device_counter++;
cl_int err2;
cl_command_queue cq;
#if CL_VERSION_2_0
if ( (*d).major_version() >= 2 ) {
if ( (*d).out_of_order_exec_mode_on_host_present() ) {
cl_queue_properties props[] = { CL_QUEUE_PROPERTIES, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, 0 };
cq = clCreateCommandQueueWithProperties( ctx, (*d).my_cl_device_id, props, &err2 );
} else {
cl_queue_properties props[] = { 0 };
cq = clCreateCommandQueueWithProperties( ctx, (*d).my_cl_device_id, props, &err2 );
}
} else
#endif
{
cl_command_queue_properties props = (*d).out_of_order_exec_mode_on_host_present() ? CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE : 0;
// Suppress "declared deprecated" warning for the next line.
#if __TBB_GCC_WARNING_SUPPRESSION_PRESENT
#pragma GCC diagnostic push
// #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#if _MSC_VER || __INTEL_COMPILER
#pragma warning( push )
#if __INTEL_COMPILER
#pragma warning (disable: 1478)
#else
#pragma warning (disable: 4996)
#endif
#endif
cq = clCreateCommandQueue( ctx, (*d).my_cl_device_id, props, &err2 );
#if _MSC_VER || __INTEL_COMPILER
#pragma warning( pop )
#endif
#if __TBB_GCC_WARNING_SUPPRESSION_PRESENT
#pragma GCC diagnostic pop
#endif
}
enforce_cl_retcode( err2, "Failed to create command queue" );
(*d).my_cl_command_queue = cq;
}
}
const opencl_device_list &opencl_graph::available_devices() {
return get_opencl_foundation().get_all_devices();
}
default_opencl_factory &opencl_graph::opencl_factory() {
return get_opencl_foundation().get_default_opencl_factory();
}
template <typename T, typename Factory>
opencl_buffer<T, Factory>::opencl_buffer( opencl_graph &g, size_t size ) : my_impl( std::make_shared<impl_type>( size*sizeof(T), g.get_opencl_foundation().get_default_opencl_factory() ) ) {}
enum class opencl_program_type {
SOURCE,
PRECOMPILED,
SPIR
};
template <typename Factory = default_opencl_factory>
class opencl_program : tbb::internal::no_assign {
public:
typedef typename Factory::kernel_type kernel_type;
opencl_program( Factory& factory, opencl_program_type type, const std::string& program_name ) : my_factory( factory ), my_type(type) , my_arg_str( program_name) {}
opencl_program( Factory& factory, const char* program_name ) : opencl_program( factory, std::string( program_name ) ) {}
opencl_program( Factory& factory, const std::string& program_name ) : opencl_program( factory, opencl_program_type::SOURCE, program_name ) {}
opencl_program( opencl_graph& graph, opencl_program_type type, const std::string& program_name ) : opencl_program( graph.opencl_factory(), type, program_name ) {}
opencl_program( opencl_graph& graph, const char* program_name ) : opencl_program( graph.opencl_factory(), program_name ) {}
opencl_program( opencl_graph& graph, const std::string& program_name ) : opencl_program( graph.opencl_factory(), program_name ) {}
opencl_program( opencl_graph& graph, opencl_program_type type ) : opencl_program( graph.opencl_factory(), type ) {}
opencl_program( const opencl_program &src ) : my_factory( src.my_factory ), my_type( src.type ), my_arg_str( src.my_arg_str ), my_cl_program( src.my_cl_program ) {
// Set my_do_once_flag to the called state.
std::call_once( my_do_once_flag, [](){} );
}
kernel_type get_kernel( const std::string& k ) const {
return kernel_type( get_cl_kernel(k), my_factory );
}
private:
opencl_program( Factory& factory, cl_program program ) : my_factory( factory ), my_cl_program( program ) {
// Set my_do_once_flag to the called state.
std::call_once( my_do_once_flag, [](){} );
}
cl_kernel get_cl_kernel( const std::string& k ) const {
std::call_once( my_do_once_flag, [this, &k](){ this->init( k ); } );
cl_int err;
cl_kernel kernel = clCreateKernel( my_cl_program, k.c_str(), &err );
enforce_cl_retcode( err, std::string( "Failed to create kernel: " ) + k );
return kernel;
}
class file_reader {
public:
file_reader( const std::string& filepath ) {
std::ifstream file_descriptor( filepath, std::ifstream::binary );
if ( !file_descriptor.is_open() ) {
std::string str = std::string( "Could not open file: " ) + filepath;
std::cerr << str << std::endl;
throw str;
}
file_descriptor.seekg( 0, file_descriptor.end );
size_t length = size_t( file_descriptor.tellg() );
file_descriptor.seekg( 0, file_descriptor.beg );
my_content.resize( length );
char* begin = &*my_content.begin();
file_descriptor.read( begin, length );
file_descriptor.close();
}
const char* content() { return &*my_content.cbegin(); }
size_t length() { return my_content.length(); }
private:
std::string my_content;
};
class opencl_program_builder {
public:
typedef void (CL_CALLBACK *cl_callback_type)(cl_program, void*);
opencl_program_builder( Factory& f, const std::string& name, cl_program program,
cl_uint num_devices, cl_device_id* device_list,
const char* options, cl_callback_type callback,
void* user_data ) {
cl_int err = clBuildProgram( program, num_devices, device_list, options,
callback, user_data );
if( err == CL_SUCCESS )
return;
std::string str = std::string( "Failed to build program: " ) + name;
if ( err == CL_BUILD_PROGRAM_FAILURE ) {
const opencl_device_list &devices = f.devices();
for ( auto d = devices.begin(); d != devices.end(); ++d ) {
std::cerr << "Build log for device: " << (*d).name() << std::endl;
size_t log_size;
cl_int query_err = clGetProgramBuildInfo(
program, (*d).my_cl_device_id, CL_PROGRAM_BUILD_LOG, 0, NULL,
&log_size );
enforce_cl_retcode( query_err, "Failed to get build log size" );
if( log_size ) {
std::vector<char> output;
output.resize( log_size );
query_err = clGetProgramBuildInfo(
program, (*d).my_cl_device_id, CL_PROGRAM_BUILD_LOG,
output.size(), output.data(), NULL );
enforce_cl_retcode( query_err, "Failed to get build output" );
std::cerr << output.data() << std::endl;
} else {
std::cerr << "No build log available" << std::endl;
}
}
}
enforce_cl_retcode( err, str );
}
};
class opencl_device_filter {
public:
template<typename Filter>
opencl_device_filter( cl_uint& num_devices, cl_device_id* device_list,
Filter filter, const char* message ) {
for ( cl_uint i = 0; i < num_devices; ++i )
if ( filter(device_list[i]) ) {
device_list[i--] = device_list[--num_devices];
}
if ( !num_devices )
enforce_cl_retcode( CL_DEVICE_NOT_AVAILABLE, message );
}
};
void init( const std::string& ) const {
cl_uint num_devices;
enforce_cl_retcode( clGetContextInfo( my_factory.context(), CL_CONTEXT_NUM_DEVICES, sizeof( num_devices ), &num_devices, NULL ),
"Failed to get OpenCL context info" );
if ( !num_devices )
enforce_cl_retcode( CL_DEVICE_NOT_FOUND, "No supported devices found" );
cl_device_id *device_list = (cl_device_id *)alloca( num_devices*sizeof( cl_device_id ) );
enforce_cl_retcode( clGetContextInfo( my_factory.context(), CL_CONTEXT_DEVICES, num_devices*sizeof( cl_device_id ), device_list, NULL ),
"Failed to get OpenCL context info" );
const char *options = NULL;
switch ( my_type ) {
case opencl_program_type::SOURCE: {
file_reader fr( my_arg_str );
const char *s[] = { fr.content() };
const size_t l[] = { fr.length() };
cl_int err;
my_cl_program = clCreateProgramWithSource( my_factory.context(), 1, s, l, &err );
enforce_cl_retcode( err, std::string( "Failed to create program: " ) + my_arg_str );
opencl_device_filter(
num_devices, device_list,
[]( const opencl_device& d ) -> bool {
return !d.compiler_available() || !d.linker_available();
}, "No one device supports building program from sources" );
opencl_program_builder(
my_factory, my_arg_str, my_cl_program, num_devices, device_list,
options, /*callback*/ NULL, /*user data*/NULL );
break;
}
case opencl_program_type::SPIR:
options = "-x spir";
case opencl_program_type::PRECOMPILED: {
file_reader fr( my_arg_str );
std::vector<const unsigned char*> s(
num_devices, reinterpret_cast<const unsigned char*>(fr.content()) );
std::vector<size_t> l( num_devices, fr.length() );
std::vector<cl_int> bin_statuses( num_devices, -1 );
cl_int err;
my_cl_program = clCreateProgramWithBinary( my_factory.context(), num_devices,
device_list, l.data(), s.data(),
bin_statuses.data(), &err );
if( err != CL_SUCCESS ) {
std::string statuses_str;
for (auto st = bin_statuses.begin(); st != bin_statuses.end(); ++st) {
statuses_str += std::to_string((*st));
}
enforce_cl_retcode( err, std::string( "Failed to create program, error " + std::to_string( err ) + " : " ) + my_arg_str +
std::string( ", binary_statuses = " ) + statuses_str );
}
opencl_program_builder(
my_factory, my_arg_str, my_cl_program, num_devices, device_list,
options, /*callback*/ NULL, /*user data*/NULL );
break;
}
default:
__TBB_ASSERT( false, "Unsupported program type" );
}
}
Factory& my_factory;
opencl_program_type my_type;
std::string my_arg_str;
mutable cl_program my_cl_program;
mutable std::once_flag my_do_once_flag;
template <typename DeviceFilter>
friend class opencl_factory;
template <typename DeviceFilter>
friend class opencl_factory<DeviceFilter>::kernel;
};
template<typename... Args>
class opencl_node;
template<typename JP, typename Factory, typename... Ports>
class opencl_node< tuple<Ports...>, JP, Factory > : public streaming_node< tuple<Ports...>, JP, Factory > {
typedef streaming_node < tuple<Ports...>, JP, Factory > base_type;
public:
typedef typename base_type::kernel_type kernel_type;
opencl_node( opencl_graph &g, const kernel_type& kernel )
: base_type( g, kernel, g.get_opencl_foundation().get_default_device_selector(), g.get_opencl_foundation().get_default_opencl_factory() )
{}
opencl_node( opencl_graph &g, const kernel_type& kernel, Factory &f )
: base_type( g, kernel, g.get_opencl_foundation().get_default_device_selector(), f )
{}
template <typename DeviceSelector>
opencl_node( opencl_graph &g, const kernel_type& kernel, DeviceSelector d, Factory &f)
: base_type( g, kernel, d, f)
{}
};
template<typename JP, typename... Ports>
class opencl_node< tuple<Ports...>, JP > : public opencl_node < tuple<Ports...>, JP, default_opencl_factory > {
typedef opencl_node < tuple<Ports...>, JP, default_opencl_factory > base_type;
public:
typedef typename base_type::kernel_type kernel_type;
opencl_node( opencl_graph &g, const kernel_type& kernel )
: base_type( g, kernel, g.get_opencl_foundation().get_default_device_selector(), g.get_opencl_foundation().get_default_opencl_factory() )
{}
template <typename DeviceSelector>
opencl_node( opencl_graph &g, const kernel_type& kernel, DeviceSelector d )
: base_type( g, kernel, d, g.get_opencl_foundation().get_default_opencl_factory() )
{}
};
template<typename... Ports>
class opencl_node< tuple<Ports...> > : public opencl_node < tuple<Ports...>, queueing, default_opencl_factory > {
typedef opencl_node < tuple<Ports...>, queueing, default_opencl_factory > base_type;
public:
typedef typename base_type::kernel_type kernel_type;
opencl_node( opencl_graph &g, const kernel_type& kernel )
: base_type( g, kernel, g.get_opencl_foundation().get_default_device_selector(), g.get_opencl_foundation().get_default_opencl_factory() )
{}
template <typename DeviceSelector>
opencl_node( opencl_graph &g, const kernel_type& kernel, DeviceSelector d )
: base_type( g, kernel, d, g.get_opencl_foundation().get_default_opencl_factory() )
{}
};
} // namespace interface9
using interface9::opencl_graph;
using interface9::opencl_node;
using interface9::read_only;
using interface9::read_write;
using interface9::write_only;
using interface9::opencl_buffer;
using interface9::opencl_subbuffer;
using interface9::opencl_device;
using interface9::opencl_device_list;
using interface9::opencl_program;
using interface9::opencl_program_type;
using interface9::dependency_msg;
using interface9::opencl_factory;
using interface9::opencl_range;
} // namespace flow
} // namespace tbb
#endif /* __TBB_PREVIEW_OPENCL_NODE */
#endif // __TBB_flow_graph_opencl_node_H
|
[
"githubfortyuds@gmail.com"
] |
githubfortyuds@gmail.com
|
bd9d1112e540706e20bb52c10417811b68da86fb
|
1d450ef7469a01208e67b0820f0e91bd3630630a
|
/third-party/jni.hpp-4.0.0/include/jni/native_method.hpp
|
978b733d24f7c236099446afe4c899ac251ec9d3
|
[
"BSD-3-Clause",
"Apache-2.0",
"ISC"
] |
permissive
|
folkene/pyjadx
|
db3ff1e9f4625add618388f28441ebd7dd894692
|
d16ece0df2cb9b0500d00cac49df84578a81fc56
|
refs/heads/master
| 2020-08-04T14:59:14.259823
| 2019-10-08T14:24:40
| 2019-10-08T14:24:40
| 212,176,491
| 1
| 0
|
Apache-2.0
| 2019-10-01T18:59:38
| 2019-10-01T18:59:38
| null |
UTF-8
|
C++
| false
| false
| 13,769
|
hpp
|
#pragma once
#include <jni/types.hpp>
#include <jni/errors.hpp>
#include <jni/functions.hpp>
#include <jni/tagging.hpp>
#include <jni/class.hpp>
#include <jni/object.hpp>
#include <exception>
#include <type_traits>
#include <iostream>
namespace jni
{
template < class M, class Enable = void >
struct NativeMethodTraits;
template < class R, class... Args >
struct NativeMethodTraits< R (Args...) >
{
using Type = R (Args...);
using ResultType = R;
};
template < class R, class... Args >
struct NativeMethodTraits< R (*)(Args...) >
: NativeMethodTraits< R (Args...) > {};
template < class T, class R, class... Args >
struct NativeMethodTraits< R (T::*)(Args...) const >
: NativeMethodTraits< R (Args...) > {};
template < class T, class R, class... Args >
struct NativeMethodTraits< R (T::*)(Args...) >
: NativeMethodTraits< R (Args...) > {};
template < class M >
struct NativeMethodTraits< M, std::enable_if_t< std::is_class<M>::value > >
: NativeMethodTraits< decltype(&M::operator()) > {};
/// Low-level, lambda
template < class M >
auto MakeNativeMethod(const char* name, const char* sig, const M& m,
std::enable_if_t< std::is_class<M>::value >* = nullptr)
{
using FunctionType = typename NativeMethodTraits<M>::Type;
using ResultType = typename NativeMethodTraits<M>::ResultType;
static FunctionType* method = m;
auto wrapper = [] (JNIEnv* env, auto... args)
{
try
{
return method(env, args...);
}
catch (...)
{
ThrowJavaError(*env, std::current_exception());
return ResultType();
}
};
return JNINativeMethod< FunctionType > { name, sig, wrapper };
}
/// Low-level, function pointer
template < class M, M method >
auto MakeNativeMethod(const char* name, const char* sig)
{
using FunctionType = typename NativeMethodTraits<M>::Type;
using ResultType = typename NativeMethodTraits<M>::ResultType;
auto wrapper = [] (JNIEnv* env, auto... args)
{
try
{
return method(env, args...);
}
catch (...)
{
ThrowJavaError(*env, std::current_exception());
return ResultType();
}
};
return JNINativeMethod< FunctionType > { name, sig, wrapper };
}
/// High-level, lambda
template < class T, T*... >
struct NativeMethodMaker;
template < class T, class R, class Subject, class... Args >
struct NativeMethodMaker< R (T::*)(JNIEnv&, Subject, Args...) const >
{
template < class M >
auto operator()(const char* name, const M& m)
{
static M method(m);
auto wrapper = [] (JNIEnv* env, UntaggedType<Subject> subject, UntaggedType<Args>... args)
{
return ReleaseUnique(method(*env, AsLvalue(Tag<std::decay_t<Subject>>(*env, *subject)), AsLvalue(Tag<std::decay_t<Args>>(*env, args))...));
};
return MakeNativeMethod(name, TypeSignature<RemoveUniqueType<R> (std::decay_t<Args>...)>()(), wrapper);
}
};
template < class T, class Subject, class... Args >
struct NativeMethodMaker< void (T::*)(JNIEnv&, Subject, Args...) const >
{
template < class M >
auto operator()(const char* name, const M& m)
{
static M method(m);
auto wrapper = [] (JNIEnv* env, UntaggedType<Subject> subject, UntaggedType<Args>... args)
{
method(*env, AsLvalue(Tag<std::decay_t<Subject>>(*env, *subject)), AsLvalue(Tag<std::decay_t<Args>>(*env, args))...);
};
return MakeNativeMethod(name, TypeSignature<void (std::decay_t<Args>...)>()(), wrapper);
}
};
template < class M >
auto MakeNativeMethod(const char* name, const M& m)
{
return NativeMethodMaker<decltype(&M::operator())>()(name, m);
}
/// High-level, function pointer
template < class R, class Subject, class... Args, R (*method)(JNIEnv&, Subject, Args...) >
struct NativeMethodMaker< R (JNIEnv&, Subject, Args...), method >
{
auto operator()(const char* name)
{
auto wrapper = [] (JNIEnv* env, UntaggedType<Subject> subject, UntaggedType<Args>... args)
{
return ReleaseUnique(method(*env, AsLvalue(Tag<std::decay_t<Subject>>(*env, *subject)), AsLvalue(Tag<std::decay_t<Args>>(*env, args))...));
};
return MakeNativeMethod(name, TypeSignature<RemoveUniqueType<R> (std::decay_t<Args>...)>()(), wrapper);
}
};
template < class Subject, class... Args, void (*method)(JNIEnv&, Subject, Args...) >
struct NativeMethodMaker< void (JNIEnv&, Subject, Args...), method >
{
auto operator()(const char* name)
{
auto wrapper = [] (JNIEnv* env, UntaggedType<Subject> subject, UntaggedType<Args>... args)
{
method(*env, AsLvalue(Tag<std::decay_t<Subject>>(*env, *subject)), AsLvalue(Tag<std::decay_t<Args>>(*env, args))...);
};
return MakeNativeMethod(name, TypeSignature<void (std::decay_t<Args>...)>()(), wrapper);
}
};
template < class M, M method >
auto MakeNativeMethod(const char* name)
{
using FunctionType = typename NativeMethodTraits<M>::Type;
return NativeMethodMaker<FunctionType, method>()(name);
}
/// High-level peer, lambda
template < class L, class >
class NativePeerLambdaMethod;
template < class L, class R, class P, class... Args >
class NativePeerLambdaMethod< L, R (L::*)(JNIEnv&, P&, Args...) const >
{
private:
const char* name;
L lambda;
public:
NativePeerLambdaMethod(const char* n, const L& l)
: name(n), lambda(l)
{}
template < class Peer, class TagType, class = std::enable_if_t< std::is_same<P, Peer>::value > >
auto operator()(const Field<TagType, jlong>& field)
{
auto wrapper = [field, lambda = lambda] (JNIEnv& env, Object<TagType>& obj, Args... args)
{
return lambda(env, *reinterpret_cast<P*>(obj.Get(env, field)), args...);
};
return MakeNativeMethod(name, wrapper);
}
};
template < class L >
auto MakeNativePeerMethod(const char* name, const L& lambda,
std::enable_if_t< std::is_class<L>::value >* = nullptr)
{
return NativePeerLambdaMethod<L, decltype(&L::operator())>(name, lambda);
}
/// High-level peer, function pointer
template < class M, M* >
class NativePeerFunctionPointerMethod;
template < class R, class P, class... Args, R (*method)(JNIEnv&, P&, Args...) >
class NativePeerFunctionPointerMethod< R (JNIEnv&, P&, Args...), method >
{
private:
const char* name;
public:
NativePeerFunctionPointerMethod(const char* n)
: name(n)
{}
template < class Peer, class TagType, class = std::enable_if_t< std::is_same<P, Peer>::value > >
auto operator()(const Field<TagType, jlong>& field)
{
auto wrapper = [field] (JNIEnv& env, Object<TagType>& obj, Args... args)
{
return method(env, *reinterpret_cast<P*>(obj.Get(env, field)), args...);
};
return MakeNativeMethod(name, wrapper);
}
};
template < class M, M method >
auto MakeNativePeerMethod(const char* name,
std::enable_if_t< !std::is_member_function_pointer<M>::value >* = nullptr)
{
using FunctionType = typename NativeMethodTraits<M>::Type;
return NativePeerFunctionPointerMethod<FunctionType, method>(name);
}
/// High-level peer, member function pointer
template < class M, M >
class NativePeerMemberFunctionMethod;
template < class R, class P, class... Args, R (P::*method)(JNIEnv&, Args...) >
class NativePeerMemberFunctionMethod< R (P::*)(JNIEnv&, Args...), method >
{
private:
const char* name;
public:
NativePeerMemberFunctionMethod(const char* n)
: name(n)
{}
template < class Peer, class TagType, class = std::enable_if_t< std::is_same<P, Peer>::value > >
auto operator()(const Field<TagType, jlong>& field)
{
auto wrapper = [field] (JNIEnv& env, Object<TagType>& obj, Args... args)
{
return (reinterpret_cast<P*>(obj.Get(env, field))->*method)(env, args...);
};
return MakeNativeMethod(name, wrapper);
}
};
template < class M, M method >
auto MakeNativePeerMethod(const char* name,
std::enable_if_t< std::is_member_function_pointer<M>::value >* = nullptr)
{
return NativePeerMemberFunctionMethod<M, method>(name);
}
/**
* A registration function for native methods on a "native peer": a long-lived native
* object corresponding to a Java object, usually created when the Java object is created
* and destroyed when the Java object's finalizer runs.
*
* It assumes that the Java object has a field, named by `fieldName`, of Java type `long`,
* which is used to hold a pointer to the native peer.
*
* `Methods` must be a sequence of `NativePeerMethod` instances, instantiated with pointer
* to member functions of the native peer class. For each method in `methods`, a native
* method is bound with a signature corresponding to that of the member function. The
* wrapper for that native method obtains the native peer instance from the Java field and
* calls the native peer method on it, passing along any arguments.
*
* An overload is provided that accepts a Callable object with a unique_ptr result type and
* the names for native creation and finalization methods, allowing creation and disposal of
* the native peer from Java.
*
* For an example of all of the above, see the `examples` directory.
*/
template < class Peer, class TagType, class... Methods >
void RegisterNativePeer(JNIEnv& env, const Class<TagType>& clazz, const char* fieldName, Methods&&... methods)
{
static Field<TagType, jni::jlong> field { env, clazz, fieldName };
RegisterNatives(env, *clazz, methods.template operator()<Peer>(field)...);
}
template < class Peer, class TagType, class >
struct NativePeerHelper;
template < class Peer, class TagType, class... Args >
struct NativePeerHelper< Peer, TagType, std::unique_ptr<Peer> (JNIEnv&, Args...) >
{
using UniquePeer = std::unique_ptr<Peer>;
using Initializer = UniquePeer (JNIEnv&, Args...);
auto MakeInitializer(const Field<TagType, jlong>& field, const char* name, Initializer* initializer) const
{
auto wrapper = [field, initializer] (JNIEnv& e, Object<TagType>& obj, std::decay_t<Args>&... args)
{
UniquePeer previous(reinterpret_cast<Peer*>(obj.Get(e, field)));
UniquePeer instance(initializer(e, args...));
obj.Set(e, field, reinterpret_cast<jlong>(instance.get()));
instance.release();
};
return MakeNativeMethod(name, wrapper);
}
auto MakeFinalizer(const Field<TagType, jlong>& field, const char* name) const
{
auto wrapper = [field] (JNIEnv& e, Object<TagType>& obj)
{
UniquePeer instance(reinterpret_cast<Peer*>(obj.Get(e, field)));
if (instance) obj.Set(e, field, jlong(0));
instance.reset();
};
return MakeNativeMethod(name, wrapper);
}
};
template < class Peer, class TagType, class Initializer, class... Methods >
void RegisterNativePeer(JNIEnv& env, const Class<TagType>& clazz, const char* fieldName,
Initializer initialize,
const char* initializeMethodName,
const char* finalizeMethodName,
Methods&&... methods)
{
static Field<TagType, jlong> field { env, clazz, fieldName };
using InitializerMethodType = typename NativeMethodTraits<Initializer>::Type;
NativePeerHelper<Peer, TagType, InitializerMethodType> helper;
RegisterNatives(env, *clazz,
helper.MakeInitializer(field, initializeMethodName, initialize),
helper.MakeFinalizer(field, finalizeMethodName),
methods.template operator()<Peer>(field)...);
}
// Like std::make_unique, but with non-universal reference arguments, so it can be
// explicitly specialized (jni::MakePeer<Peer, jni::jboolean, ...>).
template < class Peer, class... Args >
std::unique_ptr<Peer> MakePeer(jni::JNIEnv& env, Args... args)
{
return std::make_unique<Peer>(env, args...);
}
}
|
[
"romainthomasc@gmail.com"
] |
romainthomasc@gmail.com
|
02792efc58567c93adaa1f8f828d230c4152afb2
|
c5efae416d17809142a24bf6536eb3d48c75843e
|
/pywin32-217/com/win32com/src/PythonCOM.cpp
|
18b4d8d9afbe3a7d7523f6faaf5940bc20906367
|
[] |
no_license
|
ctismer/Python-2.7.5-VS2010
|
846a804cee8fa7143d6fdcd3b4e9b60c24c1428f
|
63476264a452d856ae197f46070f96fd8f4a066d
|
refs/heads/master
| 2020-12-14T02:11:04.334418
| 2013-08-09T20:45:04
| 2013-08-09T20:45:04
| null | 0
| 0
| null | null | null | null |
WINDOWS-1250
|
C++
| false
| false
| 98,519
|
cpp
|
// pythoncom.cpp :
/***
Note that this source file contains embedded documentation.
This documentation consists of marked up text inside the
C comments, and is prefixed with an '@' symbol. The source
files are processed by a tool called "autoduck" which
generates Windows .hlp files.
@doc
***/
#include "stdafx.h"
#include <objbase.h>
#include "PythonCOM.h"
#include "PythonCOMServer.h"
#include "PyFactory.h"
#include "PyRecord.h"
#include "PyComTypeObjects.h"
#include "OleAcc.h" // for ObjectFromLresult proto...
#include "pyerrors.h" // for PyErr_Warn in 2.5 and earlier...
extern int PyCom_RegisterCoreIIDs(PyObject *dict);
extern int PyCom_RegisterCoreSupport(void);
extern PyObject *pythoncom_IsGatewayRegistered(PyObject *self, PyObject *args);
extern PyObject *g_obPyCom_MapIIDToType;
extern PyObject *g_obPyCom_MapGatewayIIDToName;
extern PyObject *g_obPyCom_MapInterfaceNameToIID;
PyObject *g_obEmpty = NULL;
PyObject *g_obMissing = NULL;
PyObject *g_obArgNotFound = NULL;
PyObject *PyCom_InternalError = NULL;
// Storage related functions.
extern PyObject *pythoncom_StgOpenStorage(PyObject *self, PyObject *args);
extern PyObject *pythoncom_StgOpenStorageEx(PyObject *self, PyObject *args);
extern PyObject *pythoncom_FmtIdToPropStgName(PyObject *self, PyObject *args);
extern PyObject *pythoncom_PropStgNameToFmtId(PyObject *self, PyObject *args);
#ifndef MS_WINCE
extern PyObject *pythoncom_StgIsStorageFile(PyObject *self, PyObject *args);
#endif // MS_WINCE
extern PyObject *pythoncom_StgCreateDocfile(PyObject *self, PyObject *args);
extern PyObject *pythoncom_StgCreateDocfileOnILockBytes(PyObject *self, PyObject *args);
extern PyObject *pythoncom_WriteClassStg(PyObject *self, PyObject *args);
extern PyObject *pythoncom_ReadClassStg(PyObject *self, PyObject *args);
extern PyObject *pythoncom_WriteClassStm(PyObject *self, PyObject *args);
extern PyObject *pythoncom_ReadClassStm(PyObject *self, PyObject *args);
extern PyObject *pythoncom_CreateStreamOnHGlobal(PyObject *self, PyObject *args);
extern PyObject *pythoncom_CreateILockBytesOnHGlobal(PyObject *self, PyObject *args);
extern PyObject *pythoncom_GetRecordFromGuids(PyObject *self, PyObject *args);
extern PyObject *pythoncom_GetRecordFromTypeInfo(PyObject *self, PyObject *args);
extern PyObject *Py_NewSTGMEDIUM(PyObject *self, PyObject *args);
// Typelib related functions
extern PyObject *pythoncom_loadtypelib(PyObject *self, PyObject *args);
extern PyObject *pythoncom_loadregtypelib(PyObject *self, PyObject *args);
extern PyObject *pythoncom_registertypelib(PyObject *self, PyObject *args);
extern PyObject *pythoncom_unregistertypelib(PyObject *self, PyObject *args);
#ifndef MS_WINCE
extern PyObject *pythoncom_querypathofregtypelib(PyObject *self, PyObject *args);
#endif // MS_WINCE
// Type object helpers
PyObject *Py_NewFUNCDESC(PyObject *self, PyObject *args);
PyObject *Py_NewTYPEATTR(PyObject *self, PyObject *args);
PyObject *Py_NewVARDESC(PyObject *self, PyObject *args);
// Error related functions
void GetScodeString(SCODE sc, TCHAR *buf, int bufSize);
LPCTSTR GetScodeRangeString(SCODE sc);
LPCTSTR GetSeverityString(SCODE sc);
LPCTSTR GetFacilityString(SCODE sc);
/* Debug/Test helpers */
extern LONG _PyCom_GetInterfaceCount(void);
extern LONG _PyCom_GetGatewayCount(void);
// Function pointers we load at runtime.
#define CHECK_PFN(fname) if (pfn##fname==NULL) return PyCom_BuildPyException(E_NOTIMPL);
typedef HRESULT (STDAPICALLTYPE *CoWaitForMultipleHandlesfunc)(DWORD dwFlags,
DWORD dwTimeout,
ULONG cHandles,
LPHANDLE pHandles,
LPDWORD lpdwindex
);
static CoWaitForMultipleHandlesfunc pfnCoWaitForMultipleHandles = NULL;
typedef HRESULT (STDAPICALLTYPE *CreateURLMonikerExfunc)(LPMONIKER,LPCWSTR,LPMONIKER *,DWORD);
static CreateURLMonikerExfunc pfnCreateURLMonikerEx = NULL;
// typedefs for the function pointers are in OleAcc.h
LPFNOBJECTFROMLRESULT pfnObjectFromLresult = NULL;
BOOL PyCom_HasDCom()
{
#ifndef MS_WINCE
static BOOL bHaveDCOM = -1;
if (bHaveDCOM==-1) {
HMODULE hMod = GetModuleHandle(_T("ole32.dll"));
if (hMod) {
FARPROC fp = GetProcAddress(hMod, "CoInitializeEx");
bHaveDCOM = (fp!=NULL);
} else
bHaveDCOM = FALSE; // not much we can do!
}
return bHaveDCOM;
#else // no DCOM on WinCE.
return FALSE;
#endif
}
#ifdef _MSC_VER
#pragma optimize ("y", off)
#endif // _MSC_VER
// This optimisation seems to screw things in release builds...
/* MODULE FUNCTIONS: pythoncom */
// @pymethod <o PyIUnknown>|pythoncom|CoCreateInstance|Create a new instance of an OLE automation server.
static PyObject *pythoncom_CoCreateInstance(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
PyObject *obUnk;
DWORD dwClsContext;
PyObject *obiid;
CLSID clsid;
IUnknown *punk;
CLSID iid;
if (!PyArg_ParseTuple(args, "OOiO:CoCreateInstance",
&obCLSID, // @pyparm <o PyIID>|clsid||Class identifier (CLSID) of the object
&obUnk, // @pyparm <o PyIUnknown>|unkOuter||The outer unknown, or None
&dwClsContext,// @pyparm int|context||The create context for the object
&obiid)) // @pyparm <o PyIID>|iid||The IID required from the object
return NULL;
if (!PyWinObject_AsIID(obCLSID, &clsid))
return NULL;
if (!PyWinObject_AsIID(obiid, &iid))
return NULL;
if (!PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&punk, TRUE))
return NULL;
// Make the call.
IUnknown *result = NULL;
PY_INTERFACE_PRECALL;
SCODE sc = CoCreateInstance(clsid, punk, dwClsContext, iid, (void **)&result);
if ( punk )
punk->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(sc))
return PyCom_BuildPyException(sc);
return PyCom_PyObjectFromIUnknown(result, iid);
}
#ifdef _MSC_VER
#pragma optimize ("", on)
#endif // _MSC_VER
#ifndef MS_WINCE
#ifdef _MSC_VER
#pragma optimize ("", off)
#endif // _MSC_VER
// @pymethod <o PyIUnknown>|pythoncom|CoCreateInstanceEx|Create a new instance of an OLE automation server possibly on a remote machine.
static PyObject *pythoncom_CoCreateInstanceEx(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
PyObject *obUnk;
PyObject *obCoServer;
DWORD dwClsContext;
PyObject *obrgiids;
CLSID clsid;
COSERVERINFO serverInfo = {0, NULL, NULL, 0};
COSERVERINFO *pServerInfo = NULL;
IID *iids = NULL;
MULTI_QI *mqi = NULL;
IUnknown *punk = NULL;
PyObject *result = NULL;
ULONG numIIDs = 0;
ULONG i;
Py_ssize_t py_numIIDs;
if (!PyArg_ParseTuple(args, "OOiOO:CoCreateInstanceEx",
&obCLSID, // @pyparm <o PyIID>|clsid||Class identifier (CLSID) of the object
&obUnk, // @pyparm <o PyIUnknown>|unkOuter||The outer unknown, or None
&dwClsContext, // @pyparm int|context||The create context for the object
&obCoServer, // @pyparm (server, authino=None, reserved1=0,reserved2=0)|serverInfo||May be None, or describes the remote server to execute on.
&obrgiids)) // @pyparm [<o PyIID>, ...]|iids||A list of IIDs required from the object
return NULL;
if (!PyWinObject_AsIID(obCLSID, &clsid))
goto done;
if (obCoServer==Py_None)
pServerInfo = NULL;
else {
pServerInfo = &serverInfo;
PyObject *obName, *obAuth = Py_None;
if (!PyArg_ParseTuple(obCoServer, "O|Oii", &obName, &obAuth, &serverInfo.dwReserved1, &serverInfo.dwReserved2)) {
PyErr_Clear();
PyErr_SetString(PyExc_TypeError, "The SERVERINFO is not in the correct format");
goto done;
}
if (obAuth!=Py_None) {
PyErr_SetString(PyExc_TypeError, "authinfo in the SERVERINFO must be None");
goto done;
}
if (!PyWinObject_AsWCHAR(obName, &serverInfo.pwszName, FALSE))
goto done;
}
if (!PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&punk, TRUE))
goto done;
if (!PySequence_Check(obrgiids)) {
PyErr_SetString(PyExc_TypeError, "IID's must be sequence of IID objects");
goto done;
}
py_numIIDs = PySequence_Length(obrgiids);
if (py_numIIDs > ULONG_MAX){
PyErr_Format(PyExc_ValueError, "%u is maximum number of IIDs", ULONG_MAX);
goto done;
}
numIIDs=(ULONG)py_numIIDs;
iids = new IID[numIIDs];
mqi = new MULTI_QI[numIIDs];
if (iids==NULL || mqi==NULL) {
PyErr_SetString(PyExc_MemoryError, "Allocating MULTIQI array");
goto done;
}
for (i=0;i<numIIDs;i++) {
PyObject *me = PySequence_GetItem(obrgiids, i);
if (me==NULL) goto done;
BOOL ok = PyWinObject_AsIID(me, iids+i);
Py_DECREF(me);
if (!ok) goto done;
mqi[i].pIID = iids+i;
mqi[i].pItf = NULL;
mqi[i].hr = 0;
}
// Jump hoops in case the platform doesnt have it.
{ // scoping
HRESULT (STDAPICALLTYPE *mypfn)(REFCLSID, IUnknown *, DWORD, COSERVERINFO *, ULONG, MULTI_QI *);
HMODULE hMod = GetModuleHandle(_T("ole32.dll"));
if (hMod==0) {
PyCom_BuildInternalPyException("Can not load ole32.dll");
goto done;
}
FARPROC fp = GetProcAddress(hMod, "CoCreateInstanceEx");
if (fp==NULL) {
PyCom_BuildPyException(E_NOTIMPL);
goto done;
}
mypfn = (HRESULT (STDAPICALLTYPE *)(REFCLSID, IUnknown *, DWORD, COSERVERINFO *, ULONG, MULTI_QI *))fp;
PY_INTERFACE_PRECALL;
HRESULT hr = (*mypfn)(clsid, punk, dwClsContext, pServerInfo, numIIDs, mqi);
PY_INTERFACE_POSTCALL;
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
goto done;
}
} // end scoping.
result = PyTuple_New(numIIDs);
if (result==NULL) goto done;
for (i=0;i<numIIDs;i++) {
PyObject *obNew;
if (mqi[i].hr==0)
obNew = PyCom_PyObjectFromIUnknown(mqi[i].pItf, *mqi[i].pIID, FALSE);
else {
obNew = Py_None;
Py_INCREF(Py_None);
}
PyTuple_SET_ITEM(result, i, obNew);
}
done:
if (punk) {
PY_INTERFACE_PRECALL;
punk->Release();
PY_INTERFACE_POSTCALL;
}
if (serverInfo.pwszName)
PyWinObject_FreeWCHAR(serverInfo.pwszName);
delete [] iids;
delete [] mqi;
return result;
}
#ifdef _MSC_VER
#pragma optimize ("", on)
#endif // _MSC_VER
// @pymethod |pythoncom|CoInitializeSecurity|Registers security and sets the default security values.
static PyObject *pythoncom_CoInitializeSecurity(PyObject *self, PyObject *args)
{
DWORD cAuthSvc;
SOLE_AUTHENTICATION_SERVICE *pAS = NULL;
DWORD dwAuthnLevel;
DWORD dwImpLevel;
DWORD dwCapabilities;
PSECURITY_DESCRIPTOR pSD, pSD_absolute=NULL;
PyObject *obSD, *obAuthSvc, *obReserved1, *obReserved2, *obAuthInfo;
if (!PyArg_ParseTuple(args, "OOOiiOiO:CoInitializeSecurity",
&obSD, // @pyparm <o PySECURITY_DESCRIPTOR>|sd||Security descriptor containing access permissions for process' objects, can be None
&obAuthSvc, // @pyparm object|authInfo||A value of None tells COM to choose which authentication services to use. An empty list means use no services.
&obReserved1,// @pyparm object|reserved1||Must be None
&dwAuthnLevel, // @pyparm int|authnLevel||One of pythoncom.RPC_C_AUTHN_LEVEL_* values. The default authentication level for proxies. On the server side, COM will fail calls that arrive at a lower level. All calls to AddRef and Release are made at this level.
&dwImpLevel, // @pyparm int|impLevel||One of pythoncom.RPC_C_IMP_LEVEL_* values. The default impersonation level for proxies. This value is not checked on the server side. AddRef and Release calls are made with this impersonation level so even security aware apps should set this carefully. Setting IUnknown security only affects calls to QueryInterface, not AddRef or Release.
&obAuthInfo, // @pyparm object|authInfo||Must be None
&dwCapabilities, // @pyparm int|capabilities||Additional client and/or server-side capabilities. Any set of pythoncom.EOAC_* flags may be passed. Currently only EOAC_MUTUAL_AUTH, EOAC_SECURE_REFS, and EOAC_NONE are defined
&obReserved2)) // @pyparm object|reserved2||Must be None
return NULL;
if (obReserved1 != Py_None || obReserved2 != Py_None || obAuthInfo != Py_None) {
PyErr_SetString(PyExc_TypeError, "Not all of the 'None' arguments are None!");
return NULL;
}
if (!PyWinObject_AsSECURITY_DESCRIPTOR(obSD, &pSD, /*BOOL bNoneOK = */TRUE))
return NULL;
if (obAuthSvc==Py_None)
cAuthSvc = (DWORD)-1;
else if (PySequence_Check(obAuthSvc)) {
cAuthSvc = 0;
} else {
PyErr_SetString(PyExc_TypeError, "obAuthSvc must be None or an empty sequence.");
return NULL;
}
HMODULE hMod = GetModuleHandle(_T("ole32.dll"));
if (hMod==0) return PyCom_BuildInternalPyException("Can not load ole32.dll");
FARPROC fp = GetProcAddress(hMod, "CoInitializeSecurity");
if (fp==NULL) return PyCom_BuildPyException(E_NOTIMPL);
typedef HRESULT (STDAPICALLTYPE *CoInitializeSecurityfunc)
(PSECURITY_DESCRIPTOR, LONG, SOLE_AUTHENTICATION_SERVICE*, void *, DWORD, DWORD, void *, DWORD, void *);
CoInitializeSecurityfunc mypfn=(CoInitializeSecurityfunc)fp;
// Security descriptor must be in absolute form
if (pSD!=NULL)
if (!_MakeAbsoluteSD(pSD, &pSD_absolute))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = (*mypfn)(pSD_absolute, cAuthSvc, pAS, NULL, dwAuthnLevel, dwImpLevel, NULL, dwCapabilities, NULL);
// HRESULT hr = CoInitializeSecurity(pSD, cAuthSvc, pAS, NULL, dwAuthnLevel, dwImpLevel, NULL, dwCapabilities, NULL);
PY_INTERFACE_POSTCALL;
if (pSD_absolute!=NULL)
FreeAbsoluteSD(pSD_absolute);
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
#ifdef _MSC_VER
#pragma optimize ("y", off)
#endif // _MSC_VER
// @pymethod int|pythoncom|CoRegisterClassObject|Registers an EXE class object with OLE so other applications can connect to it.
static PyObject *pythoncom_CoRegisterClassObject(PyObject *self, PyObject *args)
{
DWORD reg;
DWORD context;
DWORD flags;
PyObject *obIID, *obFactory;
IID iid;
if (!PyArg_ParseTuple(args, "OOii:CoRegisterClassObject",
&obIID, // @pyparm <o PyIID>|iid||The IID of the object to register
&obFactory, // @pyparm <o PyIUnknown>|factory||The class factory object. It is the Python programmers responsibility to ensure this object remains alive until the class is unregistered.
&context, // @pyparm int|context||The create context for the server. Must be a combination of the CLSCTX_* flags.
&flags)) // @pyparm int|flags||Create flags.
return NULL;
// @comm The class factory object should be <o PyIClassFactory> object, but as per the COM documentation, only <o PyIUnknown> is checked.
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
IUnknown *pFactory;
if (!PyCom_InterfaceFromPyObject(obFactory, IID_IUnknown, (void **)&pFactory, /*BOOL bNoneOK=*/FALSE))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoRegisterClassObject(iid, pFactory, context, flags, ®);
pFactory->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
// @rdesc The result is a handle which should be revoked using <om pythoncom.CoRevokeClassObject>
return PyInt_FromLong(reg);
}
// @pymethod |pythoncom|CoRevokeClassObject|Informs OLE that a class object, previously registered with the <om pythoncom.CoRegisterClassObject> method, is no longer available for use.
static PyObject *pythoncom_CoRevokeClassObject(PyObject *self, PyObject *args)
{
DWORD reg;
if (!PyArg_ParseTuple(args, "i:CoRevokeClassObject",
®)) // @pyparm int|reg||The value returned from <om pythoncom.CoRegisterClassObject>
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoRevokeClassObject(reg);
PY_INTERFACE_POSTCALL;
if (FAILED(hr)) {
return PyCom_BuildPyException(hr);
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|CoResumeClassObjects|Called by a server that can register multiple class objects to inform the OLE SCM about all registered classes, and permits activation requests for those class objects.
static PyObject *pythoncom_CoResumeClassObjects(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":CoResumeClassObjects"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoResumeClassObjects();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|CoTreatAsClass|Establishes or removes an emulation, in which objects of one class are treated as objects of a different class.
static PyObject *pythoncom_CoTreatAsClass(PyObject *self, PyObject *args)
{
PyObject *obguid1, *obguid2 = NULL;
if (!PyArg_ParseTuple(args, "O|O", &obguid1, &obguid2))
return NULL;
CLSID clsid1, clsid2 = GUID_NULL;
// @pyparm <o PyIID>|clsidold||CLSID of the object to be emulated.
// @pyparm <o PyIID>|clsidnew|CLSID_NULL|CLSID of the object that should emulate the original object. This replaces any existing emulation for clsidOld. Can be ommitted or CLSID_NULL, in which case any existing emulation for clsidOld is removed.
if (!PyWinObject_AsIID(obguid1, &clsid1))
return NULL;
if (obguid2!=NULL && !PyWinObject_AsIID(obguid2, &clsid2))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoTreatAsClass(clsid1, clsid2);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
#endif // MS_WINCE
// @pymethod <o PyIClassFactory>|pythoncom|MakePyFactory|Creates a new <o PyIClassFactory> object wrapping a PythonCOM Class Factory object.
static PyObject *pythoncom_MakePyFactory(PyObject *self, PyObject *args)
{
PyObject *obIID;
if (!PyArg_ParseTuple(args, "O:MakePyFactory",
&obIID)) // @pyparm <o PyIID>|iid||The IID of the object the class factory provides.
return NULL;
IID iid;
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
PY_INTERFACE_PRECALL;
CPyFactory *pFact = new CPyFactory(iid);
PY_INTERFACE_POSTCALL;
if (pFact==NULL)
return PyCom_BuildPyException(E_OUTOFMEMORY);
return PyCom_PyObjectFromIUnknown(pFact, IID_IClassFactory, /*bAddRef =*/FALSE);
}
// @pymethod int|pythoncom|_GetInterfaceCount|Retrieves the number of interface objects currently in existance
static PyObject *pythoncom_GetInterfaceCount(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":_GetInterfaceCount"))
return NULL;
return PyInt_FromLong(_PyCom_GetInterfaceCount());
// @comm If is occasionally a good idea to call this function before your Python program
// terminates. If this function returns non-zero, then you still have PythonCOM objects
// alive in your program (possibly in global variables).
}
// @pymethod int|pythoncom|_GetGatewayCount|Retrieves the number of gateway objects currently in existance
static PyObject *pythoncom_GetGatewayCount(PyObject *self, PyObject *args)
{
// @comm This is the number of Python object that implement COM servers which
// are still alive (ie, serving a client). The only way to reduce this count
// is to have the process which uses these PythonCOM servers release its references.
if (!PyArg_ParseTuple(args, ":_GetGatewayCount"))
return NULL;
return PyInt_FromLong(_PyCom_GetGatewayCount());
}
#ifndef MS_WINCE
// @pymethod <o PyIUnknown>|pythoncom|GetActiveObject|Retrieves an object representing a running object registered with OLE
static PyObject *pythoncom_GetActiveObject(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
// @pyparm CLSID|cls||The IID for the program. As for all CLSID's in Python, a "program.name" or IID format string may be used, or a real <o PyIID> object.
if (!PyArg_ParseTuple(args, "O:GetActiveObject",
&obCLSID))
return NULL;
CLSID clsid;
if (!PyWinObject_AsIID(obCLSID, &clsid))
return NULL;
// Make the call.
IUnknown *result = NULL;
PY_INTERFACE_PRECALL;
SCODE sc = GetActiveObject(clsid, NULL, &result);
PY_INTERFACE_POSTCALL;
if (FAILED(sc))
return PyCom_BuildPyException(sc);
return PyCom_PyObjectFromIUnknown(result, IID_IUnknown);
}
// @pymethod <o PyIDispatch>|pythoncom|Connect|Connect to an already running OLE automation server.
static PyObject *pythoncom_connect(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
// @pyparm CLSID|cls||An identifier for the program. Usually "program.item"
if (!PyArg_ParseTuple(args, "O:Connect",
&obCLSID))
return NULL;
CLSID clsid;
if (!PyWinObject_AsIID(obCLSID, &clsid))
return NULL;
IUnknown *unk = NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = GetActiveObject(clsid, NULL, &unk);
PY_INTERFACE_POSTCALL;
if (FAILED(hr) || unk == NULL)
return PyCom_BuildPyException(hr);
IDispatch *disp = NULL;
SCODE sc;
// local scope for macro PY_INTERFACE_PRECALL local variables
{
PY_INTERFACE_PRECALL;
sc = unk->QueryInterface(IID_IDispatch, (void**)&disp);
unk->Release();
PY_INTERFACE_POSTCALL;
}
if (FAILED(sc) || disp == NULL)
return PyCom_BuildPyException(sc);
return PyCom_PyObjectFromIUnknown(disp, IID_IDispatch);
// @comm This function is equivalent to <om pythoncom.GetActiveObject>(clsid).<om pythoncom.QueryInterace>(pythoncom.IID_IDispatch)
}
#endif // MS_WINCE
// @pymethod <o PyIDispatch>|pythoncom|new|Create a new instance of an OLE automation server.
static PyObject *pythoncom_new(PyObject *self, PyObject *args)
{
PyErr_Clear();
PyObject *progid;
// @pyparm CLSID|cls||An identifier for the program. Usually "program.item"
if (!PyArg_ParseTuple(args, "O", &progid))
return NULL;
// @comm This is just a wrapper for the CoCreateInstance method.
// Specifically, this call is identical to:
// <nl>pythoncom.CoCreateInstance(cls, None, pythoncom.CLSCTX_SERVER, pythoncom.IID_IDispatch)
int clsctx = PyCom_HasDCom() ? CLSCTX_SERVER : CLSCTX_INPROC_SERVER| CLSCTX_LOCAL_SERVER;
PyObject *obIID = PyWinObject_FromIID(IID_IDispatch);
PyObject *newArgs = Py_BuildValue("OOiO", progid, Py_None, clsctx, obIID);
Py_DECREF(obIID);
PyObject *rc = pythoncom_CoCreateInstance(self, newArgs);
Py_DECREF(newArgs);
return rc;
}
#ifndef MS_WINCE
// @pymethod <o PyIID>|pythoncom|CreateGuid|Creates a new, unique GUIID.
static PyObject *pythoncom_createguid(PyObject *self, PyObject *args)
{
PyErr_Clear();
if (PyTuple_Size(args) != 0) {
PyErr_SetString(PyExc_TypeError, "function requires no arguments");
return NULL;
}
GUID guid;
PY_INTERFACE_PRECALL;
CoCreateGuid(&guid);
PY_INTERFACE_POSTCALL;
// @comm Use the CreateGuid function when you need an absolutely unique number that you will use as a persistent identifier in a distributed environment.To a very high degree of certainty, this function returns a unique value – no other invocation, on the same or any other system (networked or not), should return the same value.
return PyWinObject_FromIID(guid);
}
// @pymethod string|pythoncom|ProgIDFromCLSID|Converts a CLSID to a progID.
static PyObject *pythoncom_progidfromclsid(PyObject *self, PyObject *args)
{
PyObject *obCLSID;
// @pyparm IID|clsid||A CLSID (either in a string, or in an <o PyIID> object)
if (!PyArg_ParseTuple(args, "O", &obCLSID))
return NULL;
CLSID clsid;
if (!PyWinObject_AsIID(obCLSID, &clsid))
return NULL;
LPOLESTR progid = NULL;
PY_INTERFACE_PRECALL;
HRESULT sc = ProgIDFromCLSID(clsid, &progid);
PY_INTERFACE_POSTCALL;
if (FAILED(sc))
return PyCom_BuildPyException(sc);
PyObject *ob = MakeOLECHARToObj(progid);
CoTaskMemFree(progid);
return ob;
}
#endif // MS_WINCE
// @pymethod string|pythoncom|GetScodeString|Returns the string for an OLE scode (HRESULT)
static PyObject *pythoncom_GetScodeString(PyObject *self, PyObject *args)
{
SCODE scode;
TCHAR buf[512];
// @pyparm int|scode||The OLE error code for the scode string requested.
if (!PyArg_ParseTuple(args, "k", &scode))
return NULL;
GetScodeString(scode, buf, sizeof(buf)/sizeof(buf[0]));
return PyWinObject_FromTCHAR(buf);
// @comm This will obtain the COM Error message for a given HRESULT.
// Internally, PythonCOM uses this function to obtain the description
// when a <o com_error> COM Exception is raised.
}
// @pymethod string|pythoncom|GetScodeRangeString|Returns the scode range string, given an OLE scode.
static PyObject *pythoncom_GetScodeRangeString(PyObject *self, PyObject *args)
{
SCODE scode;
// @pyparm int|scode||An OLE error code to return the scode range string for.
if (!PyArg_ParseTuple(args, "k", &scode))
return NULL;
return PyWinObject_FromTCHAR(GetScodeRangeString(scode));
}
// @pymethod string|pythoncom|GetSeverityString|Returns the severity string, given an OLE scode.
static PyObject *pythoncom_GetSeverityString(PyObject *self, PyObject *args)
{
SCODE scode;
// @pyparm int|scode||The OLE error code for the severity string requested.
if (!PyArg_ParseTuple(args, "k", &scode))
return NULL;
return PyWinObject_FromTCHAR(GetSeverityString(scode));
}
// @pymethod string|pythoncom|GetFacilityString|Returns the facility string, given an OLE scode.
static PyObject *pythoncom_GetFacilityString(PyObject *self, PyObject *args)
{
SCODE scode;
// @pyparm int|scode||The OLE error code for the facility string requested.
if (!PyArg_ParseTuple(args, "k", &scode))
return NULL;
return PyWinObject_FromTCHAR(GetFacilityString(scode));
}
// @pymethod <o PyIDispatch>|pythoncom|UnwrapObject|Unwraps a Python instance in a gateway object.
static PyObject *pythoncom_UnwrapObject(PyObject *self, PyObject *args)
{
PyObject *ob;
// @pyparm <o PyIUnknown>|ob||The object to unwrap.
if ( !PyArg_ParseTuple(args, "O", &ob ) )
return NULL;
// @comm If the object is not a PythonCOM object, then ValueError is raised.
if ( !PyIBase::is_object(ob, &PyIUnknown::type) ) {
PyErr_SetString(PyExc_ValueError, "argument is not a COM object");
return NULL;
}
// Unwrapper does not need thread state management
// Ie PY_INTERFACE_PRE/POSTCALL;
HRESULT hr;
IInternalUnwrapPythonObject *pUnwrapper;
if (S_OK!=(hr=((PyIUnknown *)ob)->m_obj->QueryInterface(IID_IInternalUnwrapPythonObject, (void **)&pUnwrapper))) {
PyErr_Format(PyExc_ValueError, "argument is not a Python gateway (0x%x)", hr);
return NULL;
}
PyObject *retval;
pUnwrapper->Unwrap(&retval);
pUnwrapper->Release();
if (S_OK!=hr)
return PyCom_BuildPyException(hr);
return retval;
// Use this function to obtain the inverse of the <om WrapObject> method.
// Eg, if you pass to this function the value you received from <om WrapObject>, it
// will return the object you originally passed as the parameter to <om WrapObject>
}
// @pymethod <o PyIUnknown>|pythoncom|WrapObject|Wraps a Python instance in a gateway object.
static PyObject *pythoncom_WrapObject(PyObject *self, PyObject *args)
{
PyObject *ob;
PyObject *obIID = NULL;
IID iid = IID_IDispatch;
PyObject *obIIDInterface = NULL;
IID iidInterface = IID_IDispatch;
// @pyparm object|ob||The object to wrap.
// @pyparm <o PyIID>|gatewayIID|IID_IDispatch|The IID of the gateway object to create (ie, the interface of the server object wrapped by the return value)
// @pyparm <o PyIID>|interfaceIID|IID_IDispatch|The IID of the interface object to create (ie, the interface of the returned object)
if ( !PyArg_ParseTuple(args, "O|OO", &ob, &obIID, &obIIDInterface) )
return NULL;
// @rdesc Note that there are 2 objects created by this call - a gateway (server) object, suitable for
// use by other external COM clients/hosts, as well as the returned Python interface (client) object, which
// maps to the new gateway.
// <nl>There are some unusual cases where the 2 IID parameters will not be identical.
// If you need to do this, you should know exactly what you are doing, and why!
if (obIID && obIID != Py_None) {
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
}
if (obIIDInterface && obIIDInterface != Py_None) {
if (!PyWinObject_AsIID(obIIDInterface, &iidInterface))
return NULL;
}
// Make a gateway of the specific IID we ask for.
// The gateway must exist (ie, we _must_ support PyGIXXX
// XXX - do we need an optional arg for "base object"?
// XXX - If we did, we would unwrap it like thus:
/****
IUnknown *pLook = (IUnknown *)(*ppv);
IInternalUnwrapPythonObject *pTemp;
if (pLook->QueryInterface(IID_IInternalUnwrapPythonObject, (void **)&pTemp)==S_OK) {
// One of our objects, so set the base object if it doesnt already have one
PyGatewayBase *pG = (PyGatewayBase *)pTemp;
// Eeek - just these few next lines need to be thread-safe :-(
PyWin_AcquireGlobalLock();
if (pG->m_pBaseObject==NULL && pG != (PyGatewayBase *)this) {
pG->m_pBaseObject = this;
pG->m_pBaseObject->AddRef();
}
PyWin_ReleaseGlobalLock();
pTemp->Release();
}
******/
IUnknown *pDispatch;
PY_INTERFACE_PRECALL;
HRESULT hr = PyCom_MakeRegisteredGatewayObject(iid, ob, NULL, (void **)&pDispatch);
PY_INTERFACE_POSTCALL;
if ( FAILED(hr) )
return PyCom_BuildPyException(hr);
/* pass the pDispatch reference into this thing */
/* ### this guy should always AddRef() ... */
PyObject *result = PyCom_PyObjectFromIUnknown(pDispatch, iidInterface, FALSE);
if ( !result )
{
PY_INTERFACE_PRECALL;
pDispatch->Release();
PY_INTERFACE_POSTCALL;
return NULL;
}
return result;
}
static PyObject *pythoncom_MakeIID(PyObject *self, PyObject *args)
{
PyErr_Warn(PyExc_PendingDeprecationWarning, "MakeIID is deprecated - please use pywintypes.IID() instead.");
return PyWinMethod_NewIID(self, args);
}
// no autoduck - this is deprecated.
static PyObject *pythoncom_MakeTime(PyObject *self, PyObject *args)
{
PyErr_Warn(PyExc_PendingDeprecationWarning, "MakeTime is deprecated - please use pywintypes.Time() instead.");
return PyWinMethod_NewTime(self, args);
}
#ifndef MS_WINCE
// @pymethod <o PyIMoniker>,int,<o PyIBindCtx>|pythoncom|MkParseDisplayName|Parses a moniker display name into a moniker object. The inverse of <om PyIMoniker.GetDisplayName>
static PyObject *pythoncom_MkParseDisplayName(PyObject *self, PyObject *args)
{
WCHAR *displayName = NULL;
PyObject *obDisplayName;
PyObject *obBindCtx = NULL;
// @pyparm string|displayName||The display name to parse
// @pyparm <o PyIBindCtx>|bindCtx|None|The bind context object to use.
// @comm If a binding context is not provided, then one will be created.
// Any binding context created or passed in will be returned to the
// caller.
if ( !PyArg_ParseTuple(args, "O|O:MkParseDisplayName",
&obDisplayName,
&obBindCtx) )
return NULL;
if (!PyWinObject_AsWCHAR(obDisplayName, &displayName, FALSE))
return NULL;
HRESULT hr;
IBindCtx *pBC;
if ( obBindCtx == NULL || obBindCtx==Py_None)
{
hr = CreateBindCtx(0, &pBC);
if ( FAILED(hr) ) {
PyWinObject_FreeWCHAR(displayName);
return PyCom_BuildPyException(hr);
}
/* pass the pBC ref into obBindCtx */
obBindCtx = PyCom_PyObjectFromIUnknown(pBC, IID_IBindCtx, FALSE);
}
else
{
if ( !PyCom_InterfaceFromPyObject(obBindCtx, IID_IBindCtx, (LPVOID*)&pBC, FALSE) ) {
PyWinObject_FreeWCHAR(displayName);
return NULL;
}
/* we want our own ref to obBindCtx, but not pBC */
Py_INCREF(obBindCtx);
pBC->Release();
}
/* at this point: we own a ref to obBindCtx, but not pBC */
ULONG chEaten;
IMoniker *pmk;
PY_INTERFACE_PRECALL;
hr = MkParseDisplayName(pBC, displayName, &chEaten, &pmk);
PY_INTERFACE_POSTCALL;
PyWinObject_FreeWCHAR(displayName);
if ( FAILED(hr) )
{
Py_DECREF(obBindCtx);
return PyCom_BuildPyException(hr);
}
/* pass ownership of the moniker into the result */
PyObject *obMoniker = PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE);
/* build the result */
PyObject *result = Py_BuildValue("OiO", obMoniker, chEaten, obBindCtx);
/* done with these obs */
Py_XDECREF(obMoniker);
Py_DECREF(obBindCtx);
return result;
}
// @pymethod <o PyIMoniker>|pythoncom|CreatePointerMoniker|Creates a new <o PyIMoniker> object.
static PyObject *pythoncom_CreatePointerMoniker(PyObject *self, PyObject *args)
{
PyObject *obUnk;
// @pyparm <o PyIUnknown>|IUnknown||The interface for the moniker.
if ( !PyArg_ParseTuple(args, "O:CreatePointerMoniker", &obUnk) )
return NULL;
IUnknown *punk;
if ( !PyCom_InterfaceFromPyObject(obUnk, IID_IUnknown, (LPVOID*)&punk, FALSE) )
return NULL;
IMoniker *pmk;
PY_INTERFACE_PRECALL;
HRESULT hr = CreatePointerMoniker(punk, &pmk);
punk->Release();
PY_INTERFACE_POSTCALL;
if ( FAILED(hr) )
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE);
}
// @pymethod <o PyIMoniker>|pythoncom|CreateFileMoniker|Creates a new <o PyIMoniker> object.
static PyObject *pythoncom_CreateFileMoniker(PyObject *self, PyObject *args)
{
PyObject *obName;
// @pyparm string|filename||The name of the file.
if ( !PyArg_ParseTuple(args, "O:CreateFileMoniker", &obName) )
return NULL;
BSTR bstrName;
if (!PyWinObject_AsBstr(obName, &bstrName))
return NULL;
IMoniker *pmk;
PY_INTERFACE_PRECALL;
HRESULT hr = CreateFileMoniker(bstrName, &pmk);
PY_INTERFACE_POSTCALL;
PyWinObject_FreeBstr(bstrName);
if ( FAILED(hr) )
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE);
}
// @pymethod <o PyIMoniker>|pythoncom|CreateItemMoniker|Creates an item moniker
// that identifies an object within a containing object (typically a compound document).
static PyObject *pythoncom_CreateItemMoniker(PyObject *self, PyObject *args)
{
PyObject *obDelim, *obItem;
// @pyparm string|delim||String containing the delimiter (typically "!") used to separate this item's display name from the display name of its containing object.
// @pyparm string|item||String indicating the containing object's name for the object being identified.
if ( !PyArg_ParseTuple(args, "OO:CreateItemMoniker", &obDelim, &obItem) )
return NULL;
BSTR bstrDelim, bstrItem;
if (!PyWinObject_AsBstr(obDelim, &bstrDelim, TRUE))
return NULL;
if (!PyWinObject_AsBstr(obItem, &bstrItem, FALSE)) {
PyWinObject_FreeBstr(bstrDelim);
return NULL;
}
IMoniker *pmk;
PY_INTERFACE_PRECALL;
HRESULT hr = CreateItemMoniker(bstrDelim, bstrItem, &pmk);
PY_INTERFACE_POSTCALL;
PyWinObject_FreeBstr(bstrDelim);
PyWinObject_FreeBstr(bstrItem);
if ( FAILED(hr) )
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pmk, IID_IMoniker, FALSE);
}
// @pymethod <o PyIMoniker>|pythoncom|CreateURLMonikerEx|Create a URL moniker from a full url or partial url and base moniker
// @pyseeapi CreateURLMonikerEx
static PyObject *pythoncom_CreateURLMonikerEx(PyObject *self, PyObject *args)
{
WCHAR *url = NULL;
PyObject *obbase, *oburl, *ret = NULL;
IMoniker *base_moniker = NULL, *output_moniker = NULL;
HRESULT hr;
DWORD flags = URL_MK_UNIFORM;
CHECK_PFN(CreateURLMonikerEx);
if (!PyArg_ParseTuple(args, "OO|k:CreateURLMonikerEx",
&obbase, // @pyparm <o PyIMoniker>|Context||An IMoniker interface to be used as a base with a partial URL, can be None
&oburl, // @pyparm <o PyUNICODE>|URL||Full or partial url for which to create a moniker
&flags)) // @pyparm int|Flags|URL_MK_UNIFORM|URL_MK_UNIFORM or URL_MK_LEGACY
return NULL;
if (!PyWinObject_AsWCHAR(oburl, &url, FALSE))
return NULL;
if (PyCom_InterfaceFromPyObject(obbase, IID_IMoniker, (LPVOID*)&base_moniker, TRUE)){
PY_INTERFACE_PRECALL;
hr = (*pfnCreateURLMonikerEx)(base_moniker, url, &output_moniker, flags);
if (base_moniker)
base_moniker->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
PyCom_BuildPyException(hr);
else
ret=PyCom_PyObjectFromIUnknown(output_moniker, IID_IMoniker, FALSE);
}
PyWinObject_FreeWCHAR(url);
return ret;
}
// @pymethod <o PyIID>|pythoncom|GetClassFile|Supplies the CLSID associated with the given filename.
static PyObject *pythoncom_GetClassFile(PyObject *self, PyObject *args)
{
CLSID clsid;
PyObject *obFileName;
BSTR fname;
// @pyparm string|fileName||The filename for which you are requesting the associated CLSID.
if (!PyArg_ParseTuple(args, "O", &obFileName))
return NULL;
if (!PyCom_BstrFromPyObject(obFileName, &fname, FALSE))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = GetClassFile(fname, &clsid);
PY_INTERFACE_POSTCALL;
SysFreeString(fname);
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyWinObject_FromIID(clsid);
}
#endif // MS_WINCE
// @pymethod |pythoncom|CoInitialize|Initialize the COM libraries for the calling thread.
static PyObject *pythoncom_CoInitialize(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":CoInitialize"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = PyCom_CoInitialize(NULL);
PY_INTERFACE_POSTCALL;
// @rdesc This function will ignore the RPC_E_CHANGED_MODE error, as
// that error indicates someone else beat you to the initialization, and
// did so with a different threading model. This error is ignored as it
// still means COM is ready for use on this thread, and as this function
// does not explicitly specify a threading model the caller probably
// doesn't care what model it is.
// <nl>All other COM errors will raise pythoncom.error as usual. Use
// <om pythoncom.CoInitializeEx> if you also want to handle the RPC_E_CHANGED_MODE
// error.
if (FAILED(hr) && hr != RPC_E_CHANGED_MODE)
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
// @comm Apart from the error handling semantics, this is equivalent
// to <om pythoncom.CoInitializeEx>(pythoncom.COINIT_APARTMENTTHREADED).
// See <om pythoncom.CoInitializeEx> for a description.
}
// @pymethod |pythoncom|CoInitializeEx|Initialize the COM libraries for the calling thread.
static PyObject *pythoncom_CoInitializeEx(PyObject *self, PyObject *args)
{
// @rdesc This function will raise pythoncom.error for all error
// return values, including RPC_E_CHANGED_MODE error. This is
// in contrast to <om pythoncom.CoInitialize> which will hide that
// specific error. If your code is happy to work in a threading model
// other than the one you specified, you must explicitly handle
// (and presumably ignore) this exception.
DWORD val;
if (!PyArg_ParseTuple(args, "l:CoInitializeEx", &val))
// @pyparm int|flags||Flags for the initialization.
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = PyCom_CoInitializeEx(NULL, val);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
// @comm There is no need to call this for the main Python thread, as it is called
// automatically by pythoncom (using sys.coinit_flags as the param, or COINIT_APARTMENTTHREADED
// if sys.coinit_flags does not exist).
// <nl>You must call this manually if you create a thread which wishes to use COM.
}
// @pymethod |pythoncom|CoUninitialize|Uninitialize the COM libraries for the calling thread.
static PyObject *pythoncom_CoUninitialize(PyObject *self, PyObject *args)
{
// comm This function is never called automatically by COM (as this seems the better of
// 2 evils if COM objects are still alive). If your Python program hangs on termination,
// add a call to this function before terminating.
PY_INTERFACE_PRECALL;
PyCom_CoUninitialize();
PY_INTERFACE_POSTCALL;
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|CoFreeUnusedLibraries|Unloads any DLLs that are no longer in use and that, when loaded, were specified to be freed automatically.
static PyObject *pythoncom_CoFreeUnusedLibraries(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":CoFreeUnusedLibraries"))
return NULL;
PY_INTERFACE_PRECALL;
CoFreeUnusedLibraries();
PY_INTERFACE_POSTCALL;
Py_INCREF(Py_None);
return Py_None;
}
#ifndef MS_WINCE
// @pymethod <o PyIRunningObjectTable>|pythoncom|GetRunningObjectTable|Creates a new <o PyIRunningObjectTable> object.
static PyObject *pythoncom_GetRunningObjectTable(PyObject *self, PyObject *args)
{
DWORD reserved = 0;
// @pyparm int|reserved|0|A reserved parameter. Should be zero unless you have inside information that I don't!
if ( !PyArg_ParseTuple(args, "|l:GetRunningObjectTable", &reserved) )
return NULL;
IRunningObjectTable *pROT = NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = GetRunningObjectTable(reserved,&pROT);
PY_INTERFACE_POSTCALL;
if (S_OK!=hr)
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pROT, IID_IRunningObjectTable, FALSE);
}
// @pymethod <o PyIBindCtx>|pythoncom|CreateBindCtx|Creates a new <o PyIBindCtx> object.
static PyObject *pythoncom_CreateBindCtx(PyObject *self, PyObject *args)
{
DWORD reserved = 0;
if ( !PyArg_ParseTuple(args, "|l:CreateBindCtx", &reserved) )
return NULL;
IBindCtx *pBC = NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CreateBindCtx(reserved,&pBC);
PY_INTERFACE_POSTCALL;
if (S_OK!=hr)
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pBC, IID_IBindCtx, FALSE);
}
// @pymethod int|pythoncom|RegisterActiveObject|Register an object as the active object for its class
static PyObject *pythoncom_RegisterActiveObject(PyObject *self, PyObject *args)
{
DWORD dwflags=0, dwkey=0;
HRESULT hr;
CLSID clsid;
PyObject *obclsid;
PyObject *obunk;
IUnknown *punk;
// @pyparm <o PyIUnknown>|obUnknown||The object to register.
// @pyparm <o PyIID>|clsid||The CLSID for the object
// @pyparm int|flags||Flags to use.
if (!PyArg_ParseTuple(args, "OOi:RegisterActiveObject",
&obunk,
&obclsid,
&dwflags)) return NULL;
if (!PyWinObject_AsIID(obclsid, &clsid)) return NULL;
if (!PyCom_InterfaceFromPyInstanceOrObject(obunk, IID_IUnknown, (void **)&punk), FALSE) return NULL;
PY_INTERFACE_PRECALL;
hr = RegisterActiveObject(punk, clsid, dwflags, &dwkey);
punk->Release();
PY_INTERFACE_POSTCALL;
if (S_OK!=hr) return PyCom_BuildPyException(hr);
return PyInt_FromLong(dwkey);
// @rdesc The result is a handle which should be pass to <om pythoncom.RevokeActiveObject>
}
// @pymethod |pythoncom|RevokeActiveObject|Ends an object’s status as active.
static PyObject *pythoncom_RevokeActiveObject(PyObject *self, PyObject *args)
{
DWORD dw_x=0;
HRESULT hr;
// @pyparm int|handle||A handle obtained from <om pythoncom.RegisterActiveObject>
if(!PyArg_ParseTuple(args,"l:RevokeActiveObject", &dw_x))
return NULL;
PY_INTERFACE_PRECALL;
hr = RevokeActiveObject(dw_x, NULL);
PY_INTERFACE_POSTCALL;
if (S_OK!=hr) return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
// Some basic marshalling support
// @pymethod <o PyIStream>|pythoncom|CoMarshalInterThreadInterfaceInStream|Marshals an interface pointer from one thread to another thread in the same process.
static PyObject *pythoncom_CoMarshalInterThreadInterfaceInStream(PyObject *self, PyObject*args)
{
PyObject *obIID, *obUnk;
IID iid;
if ( !PyArg_ParseTuple(args, "OO:CoMarshalInterThreadInterfaceInStream",
&obIID, // @pyparm <o PyIID>|iid||The IID of the interface to marshal.
&obUnk)) // @pyparm <o PyIUnknown>|unk||The interface to marshal.
return NULL;
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
IUnknown *pUnk;
if (!PyCom_InterfaceFromPyInstanceOrObject(obUnk, IID_IUnknown, (void **)&pUnk, FALSE))
return NULL;
IStream *pStream = NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoMarshalInterThreadInterfaceInStream(iid, pUnk, &pStream);
pUnk->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pStream, IID_IStream, /*BOOL bAddRef*/ FALSE);
}
// @pymethod <o PyIUnknown>|pythoncom|CoGetInterfaceAndReleaseStream|Unmarshals a buffer containing an interface pointer and releases the stream when an interface pointer has been marshaled from another thread to the calling thread.
static PyObject *pythoncom_CoGetInterfaceAndReleaseStream(PyObject *self, PyObject*args)
{
PyObject *obStream, *obIID;
if ( !PyArg_ParseTuple(args, "OO:CoGetInterfaceAndReleaseStream",
&obStream, // @pyparm <o PyIStream>|stream||The stream to unmarshal the object from.
&obIID )) // @pyparm <o PyIID>|iid||The IID if the interface to unmarshal.
return NULL;
IID iid;
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
IStream *pStream;
if (!PyCom_InterfaceFromPyObject(obStream, IID_IStream, (void **)&pStream, FALSE))
return NULL;
IUnknown *pUnk;
PY_INTERFACE_PRECALL;
HRESULT hr = CoGetInterfaceAndReleaseStream(pStream, iid, (void **)&pUnk);
// pStream is released by this call - no need for me to do it!
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pUnk, iid, /*BOOL bAddRef*/ FALSE);
}
// @pymethod <o PyIUnknown>|pythoncom|CoCreateFreeThreadedMarshaler|Creates an aggregatable object capable of context-dependent marshaling.
static PyObject *pythoncom_CoCreateFreeThreadedMarshaler(PyObject *self, PyObject*args)
{
PyObject *obUnk;
if ( !PyArg_ParseTuple(args, "O:CoCreateFreeThreadedMarshaler",
&obUnk )) // @pyparm <o PyIUnknown>|unk||The unknown object to marshal.
return NULL;
IUnknown *pUnk;
if (!PyCom_InterfaceFromPyObject(obUnk, IID_IUnknown, (void **)&pUnk, FALSE))
return NULL;
IUnknown *pUnkRet;
PY_INTERFACE_PRECALL;
HRESULT hr = CoCreateFreeThreadedMarshaler(pUnk, &pUnkRet);
pUnk->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pUnkRet, IID_IUnknown, FALSE);
}
// @pymethod |pythoncom|CoMarshalInterface|Marshals an interface into a stream
static PyObject *pythoncom_CoMarshalInterface(PyObject *self, PyObject*args)
{
PyObject *obriid, *obIStream, *obUnk, *ret=NULL;
IID riid;
IStream *pIStream=NULL;
IUnknown *pIUnknown=NULL;
void *pvdestctxt=NULL; // reserved
DWORD destctxt, flags=MSHLFLAGS_NORMAL;
if ( !PyArg_ParseTuple(args, "OOOk|k:CoMarshalInterface",
&obIStream, // @pyparm <o PyIStream>|Stm||An IStream interface into which marshalled interface will be written
&obriid, // @pyparm <o PyIID>|riid||IID of interface to be marshalled
&obUnk, // @pyparm <o PyIUnknown>|Unk||Base IUnknown of the object to be marshalled
&destctxt, // @pyparm int|DestContext||MSHCTX_* flag indicating where object will be unmarshalled
&flags)) // @pyparm int|flags|MSHLFLAGS_NORMAL|MSHLFLAGS_* flag indicating marshalling options
return NULL;
if (PyWinObject_AsIID(obriid, &riid)
&&PyCom_InterfaceFromPyObject(obIStream, IID_IStream, (void **)&pIStream, FALSE)
&&PyCom_InterfaceFromPyObject(obUnk, IID_IUnknown, (void **)&pIUnknown, FALSE)){
PY_INTERFACE_PRECALL;
HRESULT hr = CoMarshalInterface(pIStream, riid, pIUnknown, destctxt, pvdestctxt, flags);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
PyCom_BuildPyException(hr);
else{
Py_INCREF(Py_None);
ret=Py_None;
}
}
PY_INTERFACE_PRECALL;
if (pIUnknown)
pIUnknown->Release();
if (pIStream)
pIStream->Release();
PY_INTERFACE_POSTCALL;
return ret;
}
// @pymethod interface|pythoncom|CoUnmarshalInterface|Unmarshals an interface
static PyObject *pythoncom_CoUnmarshalInterface(PyObject *self, PyObject*args)
{
PyObject *obriid, *obIStream, *ret=NULL;
IID riid;
IStream *pIStream=NULL;
IUnknown *pIUnknown=NULL;
if (!PyArg_ParseTuple(args, "OO:CoUnmarshalInterface",
&obIStream, // @pyparm <o PyIStream>|Stm||Stream containing marshalled interface
&obriid)) // @pyparm <o PyIID>|riid||IID of interface to be unmarshalled
return NULL;
if (PyWinObject_AsIID(obriid, &riid)
&&PyCom_InterfaceFromPyObject(obIStream, IID_IStream, (void **)&pIStream, FALSE)){
PY_INTERFACE_PRECALL;
HRESULT hr = CoUnmarshalInterface(pIStream, riid, (void **)&pIUnknown);
pIStream->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
PyCom_BuildPyException(hr);
else
ret=PyCom_PyObjectFromIUnknown(pIUnknown, riid, FALSE);
}
return ret;
}
// @pymethod |pythoncom|CoReleaseMarshalData|Frees resources used by a marshalled interface
// @comm This is usually only needed when the interface could not be successfully unmarshalled
static PyObject *pythoncom_CoReleaseMarshalData(PyObject *self, PyObject*args)
{
PyObject *obIStream, *ret=NULL;
IStream *pIStream=NULL;
if (!PyArg_ParseTuple(args, "O:CoReleaseMarshalData",
&obIStream)) // @pyparm <o PyIStream>|Stm||Stream containing marshalled interface
return NULL;
if (!PyCom_InterfaceFromPyObject(obIStream, IID_IStream, (void **)&pIStream, FALSE))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CoReleaseMarshalData(pIStream);
pIStream->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
#endif // MS_WINCE
// @pymethod <o PyIUnknown>|pythoncom|CoGetObject|Converts a display name into a moniker that identifies the object named, and then binds to the object identified by the moniker.
static PyObject *pythoncom_CoGetObject(PyObject *self, PyObject*args)
{
PyObject *obName;
PyObject *obBindOpts = Py_None;
PyObject *obIID = Py_None;
if (!PyArg_ParseTuple(args, "O|OO:CoGetObject",
&obName, // @pyparm string|name||
&obBindOpts, // @pyparm None|bindOpts||Must be None
&obIID )) // @pyparm <o PyIID>|iid||The IID if the interface to unmarshal.
return NULL;
if (obBindOpts != Py_None)
return PyErr_Format(PyExc_ValueError, "BindOptions must be None");
IID iid;
if (obIID == Py_None)
iid = IID_IUnknown;
else {
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
}
PyWin_AutoFreeBstr name;
if (!PyWinObject_AsAutoFreeBstr(obName, &name))
return NULL;
IUnknown *pUnk;
PY_INTERFACE_PRECALL;
HRESULT hr = CoGetObject(name, NULL, iid, (void **)&pUnk);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pUnk, iid, /*BOOL bAddRef*/ FALSE);
}
// @pymethod |pythoncom|OleLoad|Loads into memory an object nested within a specified storage object.
static PyObject *pythoncom_OleLoad(PyObject *self, PyObject* args)
{
PyObject *obStorage, *obIID, *obSite;
if ( !PyArg_ParseTuple(args, "OOO:OleLoad",
&obStorage, // @pyparm <o PyIStorage>|storage||The storage object from which to load
&obIID, // @pyparm <o PyIID>|iid||The IID if the interface to load.
&obSite)) // @pyparm <o PyIOleClientSite>|site||The client site for the object.
return NULL;
IID iid;
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
IStorage *pStorage;
if (!PyCom_InterfaceFromPyObject(obStorage, IID_IStorage, (void **)&pStorage, FALSE))
return NULL;
IOleClientSite *pSite;
if (!PyCom_InterfaceFromPyObject(obSite, IID_IOleClientSite, (void **)&pSite, TRUE)) {
pStorage->Release();
return NULL;
}
IUnknown *pUnk;
PY_INTERFACE_PRECALL;
HRESULT hr = OleLoad(pStorage, iid, pSite, (void **)&pUnk);
pStorage->Release();
pSite->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pUnk, iid, /*BOOL bAddRef*/ FALSE);
}
// @pymethod |pythoncom|OleLoadFromStream|Load an object from an IStream.
static PyObject *pythoncom_OleLoadFromStream(PyObject *self, PyObject* args)
{
PyObject *obStream, *obIID;
if ( !PyArg_ParseTuple(args, "OO:OleLoadFromStream",
&obStream, // @pyparm <o PyIStream>|stream||The stream to load the object from.
&obIID )) // @pyparm <o PyIID>|iid||The IID if the interface to load.
return NULL;
IID iid;
if (!PyWinObject_AsIID(obIID, &iid))
return NULL;
IStream *pStream;
if (!PyCom_InterfaceFromPyObject(obStream, IID_IStream, (void **)&pStream, FALSE))
return NULL;
IUnknown *pUnk;
PY_INTERFACE_PRECALL;
HRESULT hr = OleLoadFromStream(pStream, iid, (void **)&pUnk);
pStream->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pUnk, iid, /*BOOL bAddRef*/ FALSE);
}
// @pymethod |pythoncom|OleSaveToStream|Save an object to an IStream.
static PyObject *pythoncom_OleSaveToStream(PyObject *self, PyObject*args)
{
PyObject *obPersist,*obStream;
if ( !PyArg_ParseTuple(args, "OO:OleSaveToStream",
&obPersist, // @pyparm <o PyIPersistStream>|persist||The object to save
&obStream )) // @pyparm <o PyIStream>|stream||The stream to save the object to.
return NULL;
// This parameter is allowed to be None. This follows the COM documentation rather
// than the COM implementation, which is likely to return an error if you do pass
// it a NULL IPersistStream
IPersistStream *pPersist;
if (!PyCom_InterfaceFromPyObject(obPersist, IID_IPersistStream, (void**)&pPersist, FALSE))
return NULL;
IStream *pStream;
if (!PyCom_InterfaceFromPyObject(obStream, IID_IStream, (void **)&pStream, FALSE))
{
PY_INTERFACE_PRECALL;
if(pPersist) pPersist->Release();
PY_INTERFACE_POSTCALL;
return NULL;
}
PY_INTERFACE_PRECALL;
HRESULT hr = OleSaveToStream(pPersist, pStream);
pStream->Release();
if(pPersist) pPersist->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return PyCom_BuildPyException(hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o ICreateTypeLib>|pythoncom|CreateTypeLib|Provides access to a new object instance that supports the ICreateTypeLib interface.
static PyObject *pythoncom_CreateTypeLib(PyObject *self, PyObject *args)
{
long syskind;
PyObject *obfname;
if (!PyArg_ParseTuple(args, "lO", &syskind, &obfname))
return NULL;
BSTR fname;
if (!PyWinObject_AsBstr(obfname, &fname))
return NULL;
ICreateTypeLib *pcti = NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CreateTypeLib((SYSKIND)syskind, fname, &pcti);
PY_INTERFACE_POSTCALL;
PyWinObject_FreeBstr(fname);
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pcti, IID_ICreateTypeLib, FALSE);
}
// @pymethod <o ICreateTypeLib2>|pythoncom|CreateTypeLib2|Provides access to a new object instance that supports the ICreateTypeLib2 interface.
static PyObject *pythoncom_CreateTypeLib2(PyObject *self, PyObject *args)
{
long syskind;
PyObject *obfname;
if (!PyArg_ParseTuple(args, "lO", &syskind, &obfname))
return NULL;
BSTR fname;
if (!PyWinObject_AsBstr(obfname, &fname))
return NULL;
ICreateTypeLib2 *pcti = NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = CreateTypeLib2((SYSKIND)syskind, fname, &pcti);
PY_INTERFACE_POSTCALL;
PyWinObject_FreeBstr(fname);
if (FAILED(hr))
return PyCom_BuildPyException(hr);
return PyCom_PyObjectFromIUnknown(pcti, IID_ICreateTypeLib2, FALSE);
}
// @pymethod int|pythoncom|PumpWaitingMessages|Pumps all waiting messages for the current thread.
// @comm It is sometimes necessary for a COM thread to have a message loop. This function
// can be used with <om win32event.MsgWaitForMultipleObjects> to pump all messages
// when necessary. Please see the COM documentation for more details.
// @rdesc Returns 1 if a WM_QUIT message was received, else 0
static PyObject *pythoncom_PumpWaitingMessages(PyObject *self, PyObject *args)
{
UINT firstMsg = 0, lastMsg = 0;
if (!PyArg_ParseTuple (args, "|ii:PumpWaitingMessages", &firstMsg, &lastMsg))
return NULL;
// @pyseeapi PeekMessage and DispatchMessage
MSG msg;
long result = 0;
// Read all of the messages in this next loop,
// removing each message as we read it.
Py_BEGIN_ALLOW_THREADS
while (PeekMessage(&msg, NULL, firstMsg, lastMsg, PM_REMOVE)) {
// If it's a quit message, we're out of here.
if (msg.message == WM_QUIT) {
result = 1;
break;
}
// Otherwise, dispatch the message.
DispatchMessage(&msg);
} // End of PeekMessage while loop
Py_END_ALLOW_THREADS
return PyInt_FromLong(result);
}
// @pymethod |pythoncom|PumpMessages|Pumps all messages for the current thread until a WM_QUIT message.
static PyObject *pythoncom_PumpMessages(PyObject *self, PyObject *args)
{
MSG msg;
int rc;
Py_BEGIN_ALLOW_THREADS
while ((rc=GetMessage(&msg, 0, 0, 0))==1) {
TranslateMessage(&msg); // needed?
DispatchMessage(&msg);
}
Py_END_ALLOW_THREADS
if (rc==-1)
return PyWin_SetAPIError("GetMessage");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|EnableQuitMessage|Indicates the thread PythonCOM should post a WM_QUIT message to.
static PyObject *pythoncom_EnableQuitMessage(PyObject *self, PyObject *args)
{
extern void PyCom_EnableQuitMessage( DWORD dwThreadId );
DWORD id;
// @pyparm int|threadId||The thread ID.
if (!PyArg_ParseTuple (args, "l:EnableQuitMessage", &id))
return NULL;
PyCom_EnableQuitMessage(id);
Py_INCREF(Py_None);
return Py_None;
}
static BOOL MakeHandleList(PyObject *handleList, HANDLE **ppBuf, DWORD *pNumEntries)
{
if (!PySequence_Check(handleList)) {
PyErr_SetString(PyExc_TypeError, "Handles must be a list of integers");
return FALSE;
}
DWORD numItems = (DWORD)PySequence_Length(handleList);
HANDLE *pItems = (HANDLE *)malloc(sizeof(HANDLE) * numItems);
if (pItems==NULL) {
PyErr_SetString(PyExc_MemoryError,"Allocating array of handles");
return FALSE;
}
for (DWORD i=0;i<numItems;i++) {
PyObject *obItem = PySequence_GetItem(handleList, i);
if (obItem==NULL) {
free(pItems);
return FALSE;
}
if (!PyWinObject_AsHANDLE(obItem,pItems+i)) {
Py_DECREF(obItem);
free(pItems);
PyErr_SetString(PyExc_TypeError, "Handles must be a list of integers");
return FALSE;
}
Py_DECREF(obItem);
}
*ppBuf = pItems;
*pNumEntries = numItems;
return TRUE;
}
// @pymethod int|pythoncom|CoWaitForMultipleHandles|Waits for specified handles to be signaled or for a specified timeout period to elapse.
static PyObject *pythoncom_CoWaitForMultipleHandles(PyObject *self, PyObject *args)
{
DWORD flags, timeout;
PyObject *obHandles;
DWORD numItems;
HANDLE *pItems = NULL;
CHECK_PFN(CoWaitForMultipleHandles);
if (!PyArg_ParseTuple(args, "iiO:CoWaitForMultipleHandles",
&flags, // @pyparm int|Flags||Combination of pythoncom.COWAIT_* values
&timeout, // @pyparm int|Timeout||Timeout in milliseconds
&obHandles)) // @pyparm [<o PyHANDLE>, ...]|Handles||Sequence of handles
return NULL;
if (!MakeHandleList(obHandles, &pItems, &numItems))
return NULL;
DWORD index;
PyObject *rc = NULL;
HRESULT hr;
Py_BEGIN_ALLOW_THREADS
hr = (*pfnCoWaitForMultipleHandles)(flags, timeout, numItems, pItems, &index);
Py_END_ALLOW_THREADS
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
} else
rc = PyInt_FromLong(index);
free(pItems);
return rc;
}
// @pymethod <o PyIDataObject>|pythoncom|OleGetClipboard|Retrieves a data object that you can use to access the contents of the clipboard.
static PyObject *pythoncom_OleGetClipboard(PyObject *, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":OleGetClipboard"))
return NULL;
IDataObject *pd = NULL;
HRESULT hr;
Py_BEGIN_ALLOW_THREADS
hr = ::OleGetClipboard(&pd);
Py_END_ALLOW_THREADS
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
return PyCom_PyObjectFromIUnknown(pd, IID_IDataObject, FALSE);
}
// @pymethod |pythoncom|OleSetClipboard|Places a pointer to a specific data object onto the clipboard. This makes the data object accessible to the OleGetClipboard function.
static PyObject *pythoncom_OleSetClipboard(PyObject *, PyObject *args)
{
PyObject *obd;
// @pyparm <o PyIDataObject>|dataObj||The data object to place on the clipboard.
// This parameter can be None in which case the clipboard is emptied.
if (!PyArg_ParseTuple(args, "O:OleSetClipboard", &obd))
return NULL;
IDataObject *pd;
if (!PyCom_InterfaceFromPyObject(obd, IID_IDataObject, (void**)&pd, TRUE))
return NULL;
HRESULT hr;
Py_BEGIN_ALLOW_THREADS
hr = ::OleSetClipboard(pd);
Py_END_ALLOW_THREADS
if (pd)
pd->Release();
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod true/false|pythoncom|OleIsCurrentClipboard|Determines whether the data object pointer previously placed on the clipboard by the OleSetClipboard function is still on the clipboard.
static PyObject *pythoncom_OleIsCurrentClipboard(PyObject *, PyObject *args)
{
PyObject *obd;
if (!PyArg_ParseTuple(args, "O:OleIsCurrentClipboard", &obd))
return NULL;
// @pyparm <o PyIDataObject>|dataObj||The data object to check
IDataObject *pd;
if (!PyCom_InterfaceFromPyObject(obd, IID_IDataObject, (void**)&pd, FALSE))
return NULL;
HRESULT hr;
Py_BEGIN_ALLOW_THREADS
hr = ::OleIsCurrentClipboard(pd);
Py_END_ALLOW_THREADS
pd->Release();
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
PyObject *ret = hr==S_OK ? Py_True: Py_False;
Py_INCREF(ret);
return ret;
}
// @pymethod |pythoncom|OleFlushClipboard|Carries out the clipboard shutdown sequence. It also releases the IDataObject pointer that was placed on the clipboard by the <om pythoncom.OleSetClipboard> function.
static PyObject *pythoncom_OleFlushClipboard(PyObject *, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":OleFlushClipboard"))
return NULL;
HRESULT hr;
Py_BEGIN_ALLOW_THREADS
hr = ::OleFlushClipboard();
Py_END_ALLOW_THREADS
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|RegisterDragDrop|Registers the specified window as
// one that can be the target of an OLE drag-and-drop operation and
// specifies the <o PyIDropTarget> instance to use for drop operations.
static PyObject *pythoncom_RegisterDragDrop(PyObject *, PyObject *args)
{
PyObject *obd;
HWND hwnd;
PyObject *obhwnd;
if (!PyArg_ParseTuple(args, "OO:RegisterDragDrop", &obhwnd, &obd))
return NULL;
if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd))
return NULL;
// @pyparm <o PyHANDLE>|hwnd||Handle to a window
// @pyparm <o PyIDropTarget>|dropTarget||Object that implements the IDropTarget interface
IDropTarget *dt;
if (!PyCom_InterfaceFromPyObject(obd, IID_IDropTarget, (void**)&dt, FALSE))
return NULL;
HRESULT hr;
Py_BEGIN_ALLOW_THREADS
hr = ::RegisterDragDrop(hwnd, dt);
Py_END_ALLOW_THREADS
dt->Release();
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|RevokeDragDrop|Revokes the registration of the
// specified application window as a potential target for OLE drag-and-drop
// operations.
static PyObject *pythoncom_RevokeDragDrop(PyObject *, PyObject *args)
{
HWND hwnd;
PyObject *obhwnd;
// @pyparm <o PyHANDLE>|hwnd||Handle to a window registered as an OLE drop target.
if (!PyArg_ParseTuple(args, "O:RevokeDragDrop", &obhwnd))
return NULL;
if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hwnd))
return NULL;
HRESULT hr;
Py_BEGIN_ALLOW_THREADS
hr = ::RevokeDragDrop(hwnd);
Py_END_ALLOW_THREADS
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |pythoncom|DoDragDrop|Carries out an OLE drag and drop operation.
static PyObject *pythoncom_DoDragDrop(PyObject *, PyObject *args)
{
PyObject *obdo, *obds;
DWORD effects;
if (!PyArg_ParseTuple(args, "OOl:DoDragDrop", &obdo, &obds, &effects))
return NULL;
IDropSource *ds;
if (!PyCom_InterfaceFromPyObject(obds, IID_IDropSource, (void**)&ds, FALSE))
return NULL;
IDataObject *dob;
if (!PyCom_InterfaceFromPyObject(obdo, IID_IDataObject, (void**)&dob, FALSE)) {
ds->Release();
return NULL;
}
HRESULT hr;
DWORD retEffect = 0;
Py_BEGIN_ALLOW_THREADS
hr = ::DoDragDrop(dob, ds, effects, &retEffect);
Py_END_ALLOW_THREADS
ds->Release();
dob->Release();
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
return PyInt_FromLong(retEffect);
}
// @pymethod |pythoncom|OleInitialize|Calls OleInitialized - this should rarely
// be needed, although some clipboard operations insist this is called rather
// than <om pythoncom.CoInitialize>
static PyObject *pythoncom_OleInitialize(PyObject *, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":OleInitialize"))
return NULL;
HRESULT hr;
Py_BEGIN_ALLOW_THREADS
hr = ::OleInitialize(NULL);
Py_END_ALLOW_THREADS
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o PyIUnknown>|pythoncom|ObjectFromLresult|Retrieves a requested
// interface pointer for an object based on a previously generated object reference.
static PyObject *pythoncom_ObjectFromLresult(PyObject *self, PyObject *args)
{
PyObject *oblresult;
PyObject *obIID = NULL;
PyObject *obwparam;
// @pyparm int|lresult||
// @pyparm <o PyIID>|iid||The IID to query
// @pyparm int|wparm||
LRESULT lresult;
WPARAM wparam;
IID iid;
if (!PyArg_ParseTuple(args, "OOO", &oblresult, &obIID, &obwparam))
return NULL;
if (!PyWinLong_AsULONG_PTR(oblresult, (ULONG_PTR *)&lresult))
return NULL;
if (!PyWinLong_AsULONG_PTR(obwparam, (ULONG_PTR *)&wparam))
return NULL;
if (obIID && !PyWinObject_AsIID(obIID, &iid))
return NULL;
// GIL protects us from races here.
if (pfnObjectFromLresult==NULL) {
HMODULE hmod = LoadLibrary(_T("oleacc.dll"));
if (hmod)
pfnObjectFromLresult = (LPFNOBJECTFROMLRESULT)
GetProcAddress(hmod, "ObjectFromLresult");
}
if (pfnObjectFromLresult==NULL)
return PyErr_Format(PyExc_NotImplementedError,
"Not available on this platform");
HRESULT hr;
void *ret = 0;
Py_BEGIN_ALLOW_THREADS
hr = (*pfnObjectFromLresult)(lresult, iid, wparam, &ret);
Py_END_ALLOW_THREADS
if (FAILED(hr)) {
PyCom_BuildPyException(hr);
return NULL;
}
// docs for ObjectFromLresult don't mention reference counting, but
// it does say that you can't call this twice on the same object, and
// it has a signature that implies normal reference counting. So
// we assume this call has already added a reference to the result.
return PyCom_PyObjectFromIUnknown((IUnknown *)ret, iid, FALSE);
}
// @pymethod <o PyIUnknown>|pythoncom|ObjectFromAddress|Returns a COM object given its address in memory.
// @rdesc This method is useful for applications which return objects via non-standard
// mechanisms - eg, Windows Explorer allows you to send a specific message to the
// explorer window and the result will be the address of an object Explorer implements.
// This method allows you to recover the object from that address.
static PyObject *pythoncom_ObjectFromAddress(PyObject *self, PyObject *args)
{
IID iid = IID_IUnknown;
void *addr;
PyObject *obAddr;
PyObject *obIID = NULL;
// @pyparm int|address||The address which holds a COM object
// @pyparm <o PyIID>|iid|IUnknown|The IID to query
if (!PyArg_ParseTuple(args, "O|O", &obAddr, &obIID))
return NULL;
if (!PyWinLong_AsVoidPtr(obAddr, &addr))
return NULL;
if (obIID && !PyWinObject_AsIID(obIID, &iid))
return NULL;
HRESULT hr;
IUnknown *ret = 0;
PyThreadState *_save = PyEval_SaveThread();
PYWINTYPES_TRY
{
hr = ((IUnknown *)addr)->QueryInterface(iid, (void **)&ret);
PyEval_RestoreThread(_save);
}
PYWINTYPES_EXCEPT
{
PyEval_RestoreThread(_save);
return PyErr_Format(PyExc_ValueError, "Address is not a valid COM object (win32 exception attempting to retrieve it!)");
}
if (FAILED(hr) || ret==0) {
PyCom_BuildPyException(hr);
return NULL;
}
// We've added a reference via the QI above.
return PyCom_PyObjectFromIUnknown(ret, iid, FALSE);
}
/* List of module functions */
// @module pythoncom|A module, encapsulating the OLE automation API
static struct PyMethodDef pythoncom_methods[]=
{
{ "_GetInterfaceCount", pythoncom_GetInterfaceCount, 1}, // @pymeth _GetInterfaceCount|Retrieves the number of interface objects currently in existance
{ "_GetGatewayCount", pythoncom_GetGatewayCount, 1}, // @pymeth _GetInterfaceCount|Retrieves the number of gateway objects currently in existance
#ifndef MS_WINCE
{ "CoCreateFreeThreadedMarshaler", pythoncom_CoCreateFreeThreadedMarshaler, 1},// @pymeth CoCreateFreeThreadedMarshaler|Creates an aggregatable object capable of context-dependent marshaling.
{ "CoCreateInstanceEx", pythoncom_CoCreateInstanceEx, 1 }, // @pymeth CoCreateInstanceEx|Create a new instance of an OLE automation server possibly on a remote machine.
#endif // MS_WINCE
{ "CoCreateInstance", pythoncom_CoCreateInstance, 1 }, // @pymeth CoCreateInstance|Create a new instance of an OLE automation server.
{ "CoFreeUnusedLibraries", pythoncom_CoFreeUnusedLibraries, 1}, // @pymeth CoFreeUnusedLibraries|Unloads any DLLs that are no longer in use and that, when loaded, were specified to be freed automatically.
{ "CoInitialize", pythoncom_CoInitialize, 1 }, // @pymeth CoInitialize|Initialize the COM libraries for the calling thread.
{ "CoInitializeEx", pythoncom_CoInitializeEx, 1 }, // @pymeth CoInitializeEx|Initialize the COM libraries for the calling thread.
#ifndef MS_WINCE
{ "CoInitializeSecurity",pythoncom_CoInitializeSecurity, 1}, // @pymeth CoInitializeSecurity|Registers security and sets the default security values.
{ "CoGetInterfaceAndReleaseStream", pythoncom_CoGetInterfaceAndReleaseStream, 1}, // @pymeth CoGetInterfaceAndReleaseStream|Unmarshals a buffer containing an interface pointer and releases the stream when an interface pointer has been marshaled from another thread to the calling thread.
{ "CoMarshalInterThreadInterfaceInStream", pythoncom_CoMarshalInterThreadInterfaceInStream, 1}, // @pymeth CoMarshalInterThreadInterfaceInStream|Marshals an interface pointer from one thread to another thread in the same process.
{ "CoMarshalInterface", pythoncom_CoMarshalInterface, 1}, // @pymeth CoMarshalInterface|Marshals an interface into a stream
{ "CoUnmarshalInterface", pythoncom_CoUnmarshalInterface, 1}, // @pymeth CoUnmarshalInterface|Unmarshals an interface
{ "CoReleaseMarshalData", pythoncom_CoReleaseMarshalData, 1}, // @pymeth CoReleaseMarshalData|Frees resources used by a marshalled interface
#endif // MS_WINCE
{ "CoGetObject", pythoncom_CoGetObject, 1}, // @pymeth CoGetObject|Converts a display name into a moniker that identifies the object named, and then binds to the object identified by the moniker.
{ "CoUninitialize", pythoncom_CoUninitialize, 1 }, // @pymeth CoUninitialize|Uninitialize the COM libraries.
#ifndef MS_WINCE
{ "CoRegisterClassObject",pythoncom_CoRegisterClassObject, 1 },// @pymeth CoRegisterClassObject|Registers an EXE class object with OLE so other applications can connect to it.
{ "CoResumeClassObjects", pythoncom_CoResumeClassObjects, 1}, // @pymeth CoResumeClassObjects|Called by a server that can register multiple class objects to inform the OLE SCM about all registered classes, and permits activation requests for those class objects.
{ "CoRevokeClassObject",pythoncom_CoRevokeClassObject, 1 },// @pymeth CoRevokeClassObject|Informs OLE that a class object, previously registered with the <om pythoncom.CoRegisterClassObject> method, is no longer available for use.
{ "CoTreatAsClass", pythoncom_CoTreatAsClass, 1}, // @pymeth CoTreatAsClass|Establishes or removes an emulation, in which objects of one class are treated as objects of a different class.
{ "CoWaitForMultipleHandles", pythoncom_CoWaitForMultipleHandles, 1}, // @pymeth CoWaitForMultipleHandles|Waits for specified handles to be signaled or for a specified timeout period to elapse.
{ "Connect", pythoncom_connect, 1 }, // @pymeth Connect|Connects to a running instance of an OLE automation server.
{ "connect", pythoncom_connect, 1 },
{ "CreateGuid", pythoncom_createguid, 1 }, // @pymeth CreateGuid|Creates a new, unique GUIID.
{ "CreateBindCtx", pythoncom_CreateBindCtx, 1 }, // @pymeth CreateBindCtx|Obtains a <o PyIBindCtx> object.
{ "CreateFileMoniker", pythoncom_CreateFileMoniker, 1 }, // @pymeth CreateFileMoniker|Creates a file moniker given a file name.
{ "CreateItemMoniker", pythoncom_CreateItemMoniker, 1 }, // @pymeth CreateItemMoniker|Creates an item moniker that identifies an object within a containing object (typically a compound document).
{ "CreatePointerMoniker", pythoncom_CreatePointerMoniker, 1 }, // @pymeth CreatePointerMoniker|Creates a pointer moniker based on a pointer to an object.
{ "CreateURLMonikerEx", pythoncom_CreateURLMonikerEx, 1 }, // @pymeth CreateURLMoniker|Create a URL moniker from a full url or partial url and base moniker
{ "CreateTypeLib", pythoncom_CreateTypeLib, 1}, // @pymeth CreateTypeLib|Provides access to a new object instance that supports the ICreateTypeLib interface.
{ "CreateTypeLib2", pythoncom_CreateTypeLib2, 1}, // @pymeth CreateTypeLib2|Provides access to a new object instance that supports the ICreateTypeLib2 interface.
#endif // MS_WINCE
{ "CreateStreamOnHGlobal", pythoncom_CreateStreamOnHGlobal, 1 }, // @pymeth CreateStreamOnHGlobal|Creates an in-memory stream storage object
{ "CreateILockBytesOnHGlobal", pythoncom_CreateILockBytesOnHGlobal, 1 }, // @pymeth CreateILockBytesOnHGlobal|Creates an ILockBytes interface based on global memory
{ "EnableQuitMessage", pythoncom_EnableQuitMessage, 1 }, // @pymeth EnableQuitMessage|Indicates the thread PythonCOM should post a WM_QUIT message to.
{ "FUNCDESC", Py_NewFUNCDESC, 1}, // @pymeth FUNCDESC|Returns a new <o FUNCDESC> object.
#ifndef MS_WINCE
{ "GetActiveObject", pythoncom_GetActiveObject, 1 }, // @pymeth GetActiveObject|Retrieves an object representing a running object registered with OLE
{ "GetClassFile", pythoncom_GetClassFile, 1 }, // @pymeth GetClassFile|Supplies the CLSID associated with the given filename.
#endif // MS_WINCE
{ "GetFacilityString", pythoncom_GetFacilityString, 1 }, // @pymeth GetFacilityString|Returns the facility string, given an OLE scode.
{ "GetRecordFromGuids", pythoncom_GetRecordFromGuids, 1}, // @pymeth GetRecordFromGuids|Creates a new record object from the given GUIDs
{ "GetRecordFromTypeInfo", pythoncom_GetRecordFromTypeInfo, 1}, // @pymeth GetRecordFromTypeInfo|Creates a <o PyRecord> object from a <o PyITypeInfo> interface
#ifndef MS_WINCE
{ "GetRunningObjectTable", pythoncom_GetRunningObjectTable, 1 }, // @pymeth GetRunningObjectTable|Obtains a <o PyIRunningObjectTable> object.
#endif // MS_WINCE
{ "GetScodeString", pythoncom_GetScodeString, 1 }, // @pymeth GetScodeString|Returns the string for an OLE scode.
{ "GetScodeRangeString", pythoncom_GetScodeRangeString, 1 }, // @pymeth GetScodeRangeString|Returns the scode range string, given an OLE scode.
{ "GetSeverityString", pythoncom_GetSeverityString, 1 }, // @pymeth GetSeverityString|Returns the severity string, given an OLE scode.
{ "IsGatewayRegistered", pythoncom_IsGatewayRegistered, 1}, // @pymeth IsGatewayRegistered|Returns 1 if the given IID has a registered gateway object.
{ "LoadRegTypeLib", pythoncom_loadregtypelib, 1 }, // @pymeth LoadRegTypeLib|Loads a registered type library by CLSID
{ "LoadTypeLib", pythoncom_loadtypelib, 1 }, // @pymeth LoadTypeLib|Loads a type library by name
{ "MakeIID", pythoncom_MakeIID, 1 },
{ "MakeTime", pythoncom_MakeTime, 1 },
{ "MakePyFactory", pythoncom_MakePyFactory, 1 }, // @pymeth MakePyFactory|Creates a new <o PyIClassFactory> object wrapping a PythonCOM Class Factory object.
#ifndef MS_WINCE
{ "MkParseDisplayName", pythoncom_MkParseDisplayName, 1 }, // @pymeth MkParseDisplayName|Parses a moniker display name into a moniker object. The inverse of IMoniker::GetDisplayName.
#endif // MS_WINCE
{ "new", pythoncom_new, 1 },
{ "New", pythoncom_new, 1 }, // @pymeth New|Create a new instance of an OLE automation server.
{ "ObjectFromAddress", pythoncom_ObjectFromAddress, 1 }, // @pymeth ObjectFromAddress|Returns a COM object given its address in memory.
{ "ObjectFromLresult", pythoncom_ObjectFromLresult, 1 }, // @pymeth ObjectFromLresult|Retrieves a requested interface pointer for an object based on a previously generated object reference.
{ "OleInitialize", pythoncom_OleInitialize, 1}, // @pymeth OleInitialize|
{ "OleGetClipboard", pythoncom_OleGetClipboard, 1}, // @pymeth OleGetClipboard|Retrieves a data object that you can use to access the contents of the clipboard.
{ "OleFlushClipboard", pythoncom_OleFlushClipboard, 1}, // @pymeth OleFlushClipboard|Carries out the clipboard shutdown sequence. It also releases the IDataObject pointer that was placed on the clipboard by the <om pythoncom.OleSetClipboard> function.
{ "OleIsCurrentClipboard",pythoncom_OleIsCurrentClipboard, 1}, // @pymeth OleIsCurrentClipboard|Determines whether the data object pointer previously placed on the clipboard by the OleSetClipboard function is still on the clipboard.
{ "OleSetClipboard", pythoncom_OleSetClipboard, 1}, // @pymeth OleSetClipboard|Places a pointer to a specific data object onto the clipboard. This makes the data object accessible to the OleGetClipboard function.
{ "OleLoadFromStream", pythoncom_OleLoadFromStream, 1}, // @pymeth OleLoadFromStream|Load an object from an IStream.
{ "OleSaveToStream", pythoncom_OleSaveToStream, 1}, // @pymeth OleSaveToStream|Save an object to an IStream.
{ "OleLoad", pythoncom_OleLoad, 1 }, // @pymeth OleLoad|Loads into memory an object nested within a specified storage object.
#ifndef MS_WINCE
{ "ProgIDFromCLSID", pythoncom_progidfromclsid, 1 }, // @pymeth ProgIDFromCLSID|Converts a CLSID string to a progID.
#endif // MS_WINCE
{ "PumpWaitingMessages", pythoncom_PumpWaitingMessages, 1}, // @pymeth PumpWaitingMessages|Pumps all waiting messages for the current thread.
{ "PumpMessages", pythoncom_PumpMessages, 1}, // @pymeth PumpMessages|Pumps all messages for the current thread until a WM_QUIT message.
#ifndef MS_WINCE
{ "QueryPathOfRegTypeLib",pythoncom_querypathofregtypelib, 1}, // @pymeth QueryPathOfRegTypeLib|Retrieves the path of a registered type library
#endif // MS_WINCE
{ "ReadClassStg", pythoncom_ReadClassStg, 1}, // @pymeth ReadClassStg|Reads a CLSID from a storage object
{ "ReadClassStm", pythoncom_ReadClassStm, 1}, // @pymeth ReadClassStm|Reads a CLSID from a <o PyIStream> object
{ "RegisterTypeLib", pythoncom_registertypelib, 1}, // @pymeth RegisterTypeLib|Adds information about a type library to the system registry.
{ "UnRegisterTypeLib", pythoncom_unregistertypelib, 1}, // @pymeth UnRegisterTypeLib|Removes a type library from the system registry.
#ifndef MS_WINCE
{ "RegisterActiveObject",pythoncom_RegisterActiveObject, 1 }, // @pymeth RegisterActiveObject|Register an object as the active object for its class
{ "RevokeActiveObject", pythoncom_RevokeActiveObject, 1 }, // @pymeth RevokeActiveObject|Ends an object’s status as active.
{ "RegisterDragDrop", pythoncom_RegisterDragDrop, 1}, // @pymeth RegisterDragDrop|Registers the specified window as one that can be the target of an OLE drag-and-drop operation.
{ "RevokeDragDrop", pythoncom_RevokeDragDrop, 1}, // @pymeth RevokeDragDrop|Revokes the specified window as the target of an OLE drag-and-drop operation.
{ "DoDragDrop", pythoncom_DoDragDrop, 1}, // @pymeth DoDragDrop|Carries out an OLE drag and drop operation.
#endif // MS_WINCE
{ "StgCreateDocfile", pythoncom_StgCreateDocfile, 1 }, // @pymeth StgCreateDocfile|Creates a new compound file storage object using the OLE-provided compound file implementation for the <o PyIStorage> interface.
{ "StgCreateDocfileOnILockBytes", pythoncom_StgCreateDocfileOnILockBytes, 1 }, // @pymeth StgCreateDocfileOnILockBytes|Creates a new compound file storage object using the OLE-provided compound file implementation for the <o PyIStorage> interface.
#ifndef MS_WINCE
{ "StgIsStorageFile", pythoncom_StgIsStorageFile, 1 }, // @pymeth StgIsStorageFile|Indicates whether a particular disk file contains a storage object.
#endif // MS_WINCE
{ "STGMEDIUM", Py_NewSTGMEDIUM, 1}, // @pymeth STGMEDIUM|Creates a new <o PySTGMEDIUM> object suitable for the <o PyIDataObject> interface.
{ "StgOpenStorage", pythoncom_StgOpenStorage, 1 }, // @pymeth StgOpenStorage|Opens an existing root storage object in the file system.
{ "StgOpenStorageEx", pythoncom_StgOpenStorageEx, 1 }, // @pymeth StgOpenStorageEx|Access IStorage and IPropertySetStorage interfaces for normal files
{ "TYPEATTR", Py_NewTYPEATTR, 1}, // @pymeth TYPEATTR|Returns a new <o TYPEATTR> object.
{ "VARDESC", Py_NewVARDESC, 1}, // @pymeth VARDESC|Returns a new <o VARDESC> object.
{ "WrapObject", pythoncom_WrapObject, 1 }, // @pymeth WrapObject|Wraps an object in a gateway.
{ "WriteClassStg", pythoncom_WriteClassStg, 1}, // @pymeth WriteClassStg|Stores a CLSID from a storage object
{ "WriteClassStm", pythoncom_WriteClassStm, 1}, // @pymeth WriteClassStm|Sets the CLSID of a stream
{ "UnwrapObject", pythoncom_UnwrapObject, 1 }, // @pymeth UnwrapObject|Unwraps a Python instance in a gateway object.
{ "FmtIdToPropStgName", pythoncom_FmtIdToPropStgName, 1}, //@pymeth FmtIdToPropStgName|Convert a FMTID to its stream name
{ "PropStgNameToFmtId", pythoncom_PropStgNameToFmtId, 1}, //@pymeth PropStgNameToFmtId|Convert property set name to FMTID
{ NULL, NULL }
};
int AddConstant(PyObject *dict, const char *key, long value)
{
PyObject *oval = PyInt_FromLong(value);
if (!oval)
{
return 1;
}
int rc = PyDict_SetItemString(dict, (char*)key, oval);
Py_DECREF(oval);
return rc;
}
#define ADD_CONSTANT(tok) AddConstant(dict, #tok, tok)
static char *modName = "pythoncom";
extern BOOL initunivgw(PyObject *parentDict);
/* Module initialisation */
PYWIN_MODULE_INIT_FUNC(pythoncom)
{
// The DLL Load inited the module.
// All we do here is init COM itself. Done here
// so other clients get a chance to beat us to it!
// Support a special sys.coinit_flags attribute to control us.
DWORD coinit_flags = COINIT_APARTMENTTHREADED;
PyObject *obFlags = PySys_GetObject("coinit_flags");
// No reference added to obFlags.
if (obFlags) {
if (PyInt_Check(obFlags))
coinit_flags = PyInt_AsLong(obFlags);
} else
PyErr_Clear(); // Error raised by no coinit_flags attribute.
HRESULT hr = PyCom_CoInitializeEx(NULL, coinit_flags);
if (hr==E_NOTIMPL) // Special return val from PyCom_Co.. indicates not DCOM.
hr = PyCom_CoInitialize(NULL);
// If HR fails, we really dont care - the import should work. User can
// manually CoInit() to see!
PYWIN_MODULE_INIT_PREPARE(pythoncom, pythoncom_methods,
"A module, encapsulating the OLE automation API");
// ensure the framework has valid state to work with.
// XXX - more error checking?
PyCom_RegisterCoreSupport();
PyDict_SetItemString(dict, "TypeIIDs", g_obPyCom_MapIIDToType);
PyDict_SetItemString(dict, "ServerInterfaces", g_obPyCom_MapGatewayIIDToName);
PyDict_SetItemString(dict, "InterfaceNames", g_obPyCom_MapInterfaceNameToIID);
if (PyType_Ready(&PyOleEmptyType) == -1
||PyType_Ready(&PyOleMissingType) == -1
||PyType_Ready(&PyOleArgNotFoundType) == -1)
PYWIN_MODULE_INIT_RETURN_ERROR;
g_obEmpty = new PyOleEmpty;
PyDict_SetItemString(dict, "Empty", g_obEmpty);
g_obMissing = new PyOleMissing;
PyDict_SetItemString(dict, "Missing", g_obMissing);
g_obArgNotFound = new PyOleArgNotFound;
PyDict_SetItemString(dict, "ArgNotFound", g_obArgNotFound);
// Add some symbolic constants to the module
// pycom_Error = PyString_FromString("pythoncom.error");
if (PyWinExc_COMError==NULL)
{
// This is created by PyWin_Globals_Ensure
PyErr_SetString(PyExc_MemoryError, "can't define ole_error");
PYWIN_MODULE_INIT_RETURN_ERROR;
}
PyObject *pycom_Error = PyWinExc_COMError;
if (PyDict_SetItemString(dict, "ole_error", PyWinExc_COMError) != 0)
PYWIN_MODULE_INIT_RETURN_ERROR;
if (PyDict_SetItemString(dict, "error", pycom_Error) != 0)
PYWIN_MODULE_INIT_RETURN_ERROR;
// Add the same constant, but with a "new name"
if (PyDict_SetItemString(dict, "com_error", PyWinExc_COMError) != 0)
PYWIN_MODULE_INIT_RETURN_ERROR;
PyCom_InternalError = PyErr_NewException("pythoncom.internal_error", NULL, NULL);
if (PyDict_SetItemString(dict, "internal_error", PyCom_InternalError) != 0)
PYWIN_MODULE_INIT_RETURN_ERROR;
// Add the IIDs
if (PyCom_RegisterCoreIIDs(dict) != 0)
PYWIN_MODULE_INIT_RETURN_ERROR;
// Initialize various non-interface types
if (PyType_Ready(&PyFUNCDESC::Type) == -1 ||
PyType_Ready(&PySTGMEDIUM::Type) == -1 ||
PyType_Ready(&PyTYPEATTR::Type) == -1 ||
PyType_Ready(&PyVARDESC::Type) == -1 ||
PyType_Ready(&PyRecord::Type) == -1)
PYWIN_MODULE_INIT_RETURN_ERROR;
// Setup our sub-modules
if (!initunivgw(dict))
PYWIN_MODULE_INIT_RETURN_ERROR;
// Load function pointers.
HMODULE hModOle32 = GetModuleHandle(_T("ole32.dll"));
if (hModOle32)
pfnCoWaitForMultipleHandles = (CoWaitForMultipleHandlesfunc)GetProcAddress(hModOle32, "CoWaitForMultipleHandles");
HMODULE hModurlmon = GetModuleHandle(_T("urlmon.dll"));
if (hModurlmon == NULL)
hModurlmon = LoadLibrary(_T("urlmon.dll"));
if (hModurlmon)
pfnCreateURLMonikerEx = (CreateURLMonikerExfunc)GetProcAddress(hModurlmon, "CreateURLMonikerEx");
// Symbolic constants.
ADD_CONSTANT(ACTIVEOBJECT_STRONG);
ADD_CONSTANT(ACTIVEOBJECT_WEAK);
ADD_CONSTANT(CLSCTX_ALL);
ADD_CONSTANT(CLSCTX_INPROC);
ADD_CONSTANT(CLSCTX_SERVER);
ADD_CONSTANT(CLSCTX_INPROC_SERVER);
ADD_CONSTANT(CLSCTX_INPROC_HANDLER);
ADD_CONSTANT(CLSCTX_LOCAL_SERVER);
ADD_CONSTANT(CLSCTX_REMOTE_SERVER);
// COINIT values
ADD_CONSTANT(COINIT_APARTMENTTHREADED);
#ifdef _WIN32_DCOM
ADD_CONSTANT(COINIT_MULTITHREADED);
ADD_CONSTANT(COINIT_DISABLE_OLE1DDE);
ADD_CONSTANT(COINIT_SPEED_OVER_MEMORY);
#endif
// CLIPBOARD
ADD_CONSTANT(DATADIR_GET);
ADD_CONSTANT(DATADIR_SET);
ADD_CONSTANT(TYMED_HGLOBAL);
ADD_CONSTANT(TYMED_FILE);
ADD_CONSTANT(TYMED_ISTREAM);
ADD_CONSTANT(TYMED_ISTORAGE);
ADD_CONSTANT(TYMED_GDI);
ADD_CONSTANT(TYMED_MFPICT);
ADD_CONSTANT(TYMED_ENHMF);
ADD_CONSTANT(TYMED_NULL);
ADD_CONSTANT(DVASPECT_CONTENT);
ADD_CONSTANT(DVASPECT_THUMBNAIL);
ADD_CONSTANT(DVASPECT_ICON);
ADD_CONSTANT(DVASPECT_DOCPRINT);
// DISPATCH
ADD_CONSTANT(DISPATCH_PROPERTYGET);
ADD_CONSTANT(DISPATCH_PROPERTYPUT);
ADD_CONSTANT(DISPATCH_PROPERTYPUTREF);
ADD_CONSTANT(DISPATCH_METHOD);
// DISPID
ADD_CONSTANT(DISPID_CONSTRUCTOR);
ADD_CONSTANT(DISPID_DESTRUCTOR);
ADD_CONSTANT(DISPID_COLLECT);
ADD_CONSTANT(DISPID_VALUE);
ADD_CONSTANT(DISPID_UNKNOWN);
ADD_CONSTANT(DISPID_PROPERTYPUT);
ADD_CONSTANT(DISPID_NEWENUM);
ADD_CONSTANT(DISPID_EVALUATE);
#ifndef NO_PYCOM_IDISPATCHEX
ADD_CONSTANT(DISPID_STARTENUM);
ADD_CONSTANT(DISPID_UNKNOWN);
#endif
#ifdef DISPID_THIS
ADD_CONSTANT(DISPID_THIS);
#endif
// EXTCON
ADD_CONSTANT(EXTCONN_STRONG);
ADD_CONSTANT(EXTCONN_WEAK);
ADD_CONSTANT(EXTCONN_CALLABLE);
// FUNCFLAGS
ADD_CONSTANT(FUNCFLAG_FRESTRICTED);
ADD_CONSTANT(FUNCFLAG_FSOURCE);
ADD_CONSTANT(FUNCFLAG_FBINDABLE);
ADD_CONSTANT(FUNCFLAG_FREQUESTEDIT);
ADD_CONSTANT(FUNCFLAG_FDISPLAYBIND);
ADD_CONSTANT(FUNCFLAG_FDEFAULTBIND);
ADD_CONSTANT(FUNCFLAG_FHIDDEN);
ADD_CONSTANT(FUNCFLAG_FUSESGETLASTERROR);
// FUNCKIND
ADD_CONSTANT(FUNC_VIRTUAL);
ADD_CONSTANT(FUNC_PUREVIRTUAL);
ADD_CONSTANT(FUNC_NONVIRTUAL);
ADD_CONSTANT(FUNC_STATIC);
ADD_CONSTANT(FUNC_DISPATCH);
// IMPLTYPEFLAGS
ADD_CONSTANT(IMPLTYPEFLAG_FDEFAULT);
ADD_CONSTANT(IMPLTYPEFLAG_FSOURCE);
ADD_CONSTANT(IMPLTYPEFLAG_FRESTRICTED);
// IDLFLAGS
ADD_CONSTANT(IDLFLAG_NONE);
ADD_CONSTANT(IDLFLAG_FIN);
ADD_CONSTANT(IDLFLAG_FOUT);
ADD_CONSTANT(IDLFLAG_FLCID);
ADD_CONSTANT(IDLFLAG_FRETVAL);
// Moniker types.
ADD_CONSTANT(MKSYS_NONE);
ADD_CONSTANT(MKSYS_GENERICCOMPOSITE);
ADD_CONSTANT(MKSYS_FILEMONIKER);
ADD_CONSTANT(MKSYS_ANTIMONIKER);
ADD_CONSTANT(MKSYS_ITEMMONIKER);
ADD_CONSTANT(MKSYS_POINTERMONIKER);
ADD_CONSTANT(MKSYS_CLASSMONIKER);
// PARAMFLAGS
ADD_CONSTANT(PARAMFLAG_NONE);
ADD_CONSTANT(PARAMFLAG_FIN);
ADD_CONSTANT(PARAMFLAG_FOUT);
ADD_CONSTANT(PARAMFLAG_FLCID);
ADD_CONSTANT(PARAMFLAG_FRETVAL);
ADD_CONSTANT(PARAMFLAG_FOPT);
ADD_CONSTANT(PARAMFLAG_FHASDEFAULT);
// STREAMSEEK
ADD_CONSTANT(STREAM_SEEK_SET);
ADD_CONSTANT(STREAM_SEEK_CUR);
ADD_CONSTANT(STREAM_SEEK_END);
// INVOKEKIND
ADD_CONSTANT(INVOKE_FUNC);
ADD_CONSTANT(INVOKE_PROPERTYGET);
ADD_CONSTANT(INVOKE_PROPERTYPUT);
ADD_CONSTANT(INVOKE_PROPERTYPUTREF);
ADD_CONSTANT(REGCLS_SINGLEUSE);
ADD_CONSTANT(REGCLS_MULTIPLEUSE);
ADD_CONSTANT(REGCLS_MULTI_SEPARATE);
ADD_CONSTANT(REGCLS_SUSPENDED);
// ROT
ADD_CONSTANT(ROTFLAGS_REGISTRATIONKEEPSALIVE);
ADD_CONSTANT(ROTFLAGS_ALLOWANYCLIENT);
// RPC
// Authentication Level used with CoInitializeSecurity
ADD_CONSTANT(RPC_C_AUTHN_LEVEL_DEFAULT); // RPC_C_AUTHN_LEVEL_DEFAULT|Lets DCOM negotiate the authentication level automatically. (Win2k or later)
ADD_CONSTANT(RPC_C_AUTHN_LEVEL_NONE); // RPC_C_AUTHN_LEVEL_NONE|Performs no authentication.
ADD_CONSTANT(RPC_C_AUTHN_LEVEL_CONNECT); // RPC_C_AUTHN_LEVEL_CONNECT|Authenticates only when the client establishes a relationship with the server. Datagram transports always use RPC_AUTHN_LEVEL_PKT instead.
ADD_CONSTANT(RPC_C_AUTHN_LEVEL_CALL); // RPC_C_AUTHN_LEVEL_CALL|Authenticates only at the beginning of each remote procedure call when the server receives the request. Datagram transports use RPC_C_AUTHN_LEVEL_PKT instead.
ADD_CONSTANT(RPC_C_AUTHN_LEVEL_PKT); // RPC_C_AUTHN_LEVEL_PKT|Authenticates that all data received is from the expected client.
ADD_CONSTANT(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY); // RPC_C_AUTHN_LEVEL_PKT_INTEGRITY|Authenticates and verifies that none of the data transferred between client and server has been modified.
ADD_CONSTANT(RPC_C_AUTHN_LEVEL_PKT_PRIVACY); // RPC_C_AUTHN_LEVEL_PKT_PRIVACY|Authenticates all previous levels and encrypts the argument value of each remote procedure call.
// Impersonation level used with CoInitializeSecurity
ADD_CONSTANT(RPC_C_IMP_LEVEL_DEFAULT); // RPC_C_IMP_LEVEL_DEFAULT|Use default impersonation level (Win2k or later)
ADD_CONSTANT(RPC_C_IMP_LEVEL_ANONYMOUS); // RPC_C_IMP_LEVEL_ANONYMOUS|(Not supported in this release.) The client is anonymous to the server. The server process cannot obtain identification information about the client and it cannot impersonate the client.
ADD_CONSTANT(RPC_C_IMP_LEVEL_IDENTIFY); // RPC_C_IMP_LEVEL_IDENTIFY|The server can obtain the client’s identity. The server can impersonate the client for ACL checking, but cannot access system objects as the client. This information is obtained when the connection is established, not on every call.<nl>Note GetUserName will fail while impersonating at identify level. The workaround is to impersonate, OpenThreadToken, revert, call GetTokenInformation, and finally, call LookupAccountSid.
ADD_CONSTANT(RPC_C_IMP_LEVEL_IMPERSONATE); // RPC_C_IMP_LEVEL_IMPERSONATE|The server process can impersonate the client's security context while acting on behalf of the client. This information is obtained when the connection is established, not on every call.
ADD_CONSTANT(RPC_C_IMP_LEVEL_DELEGATE); // RPC_C_IMP_LEVEL_DELEGATE|(Not supported in this release.) The server process can impersonate the client's security context while acting on behalf of the client. The server process can also make outgoing calls to other servers while acting on behalf of the client. This information is obtained when the connection is established, not on every call.
// Authentication capabilities used with CoInitializeSecurity (EOLE_AUTHENTICATION_CAPABILITIES enum)
ADD_CONSTANT(EOAC_NONE);
ADD_CONSTANT(EOAC_MUTUAL_AUTH);
ADD_CONSTANT(EOAC_SECURE_REFS);
ADD_CONSTANT(EOAC_ACCESS_CONTROL);
ADD_CONSTANT(EOAC_APPID);
ADD_CONSTANT(EOAC_DYNAMIC);
ADD_CONSTANT(EOAC_STATIC_CLOAKING);
ADD_CONSTANT(EOAC_DYNAMIC_CLOAKING);
ADD_CONSTANT(EOAC_ANY_AUTHORITY);
ADD_CONSTANT(EOAC_MAKE_FULLSIC);
ADD_CONSTANT(EOAC_REQUIRE_FULLSIC);
ADD_CONSTANT(EOAC_AUTO_IMPERSONATE);
ADD_CONSTANT(EOAC_DEFAULT);
ADD_CONSTANT(EOAC_DISABLE_AAA);
ADD_CONSTANT(EOAC_NO_CUSTOM_MARSHAL);
// STDOLE
ADD_CONSTANT(STDOLE_MAJORVERNUM);
ADD_CONSTANT(STDOLE_MINORVERNUM);
ADD_CONSTANT(STDOLE_LCID);
ADD_CONSTANT(STDOLE2_MAJORVERNUM);
ADD_CONSTANT(STDOLE2_MINORVERNUM);
ADD_CONSTANT(STDOLE2_LCID);
// SYSKIND
ADD_CONSTANT(SYS_WIN16);
ADD_CONSTANT(SYS_WIN32);
ADD_CONSTANT(SYS_MAC);
// TYPEFLAGS
ADD_CONSTANT(TYPEFLAG_FAPPOBJECT);
ADD_CONSTANT(TYPEFLAG_FCANCREATE);
ADD_CONSTANT(TYPEFLAG_FLICENSED);
ADD_CONSTANT(TYPEFLAG_FPREDECLID);
ADD_CONSTANT(TYPEFLAG_FHIDDEN);
ADD_CONSTANT(TYPEFLAG_FCONTROL);
ADD_CONSTANT(TYPEFLAG_FDUAL);
ADD_CONSTANT(TYPEFLAG_FNONEXTENSIBLE);
ADD_CONSTANT(TYPEFLAG_FOLEAUTOMATION);
ADD_CONSTANT(TYPEFLAG_FRESTRICTED);
ADD_CONSTANT(TYPEFLAG_FAGGREGATABLE);
ADD_CONSTANT(TYPEFLAG_FREPLACEABLE);
ADD_CONSTANT(TYPEFLAG_FDISPATCHABLE);
ADD_CONSTANT(TYPEFLAG_FREVERSEBIND);
// TYPEKIND
ADD_CONSTANT(TKIND_ENUM);
ADD_CONSTANT(TKIND_RECORD);
ADD_CONSTANT(TKIND_MODULE);
ADD_CONSTANT(TKIND_INTERFACE);
ADD_CONSTANT(TKIND_DISPATCH);
ADD_CONSTANT(TKIND_COCLASS);
ADD_CONSTANT(TKIND_ALIAS);
ADD_CONSTANT(TKIND_UNION);
// VARFLAGS
ADD_CONSTANT(VARFLAG_FREADONLY);
// VARKIND
ADD_CONSTANT(VAR_PERINSTANCE);
ADD_CONSTANT(VAR_STATIC);
ADD_CONSTANT(VAR_CONST);
ADD_CONSTANT(VAR_DISPATCH);
// VARTYPE
ADD_CONSTANT(VT_EMPTY);
ADD_CONSTANT(VT_NULL);
ADD_CONSTANT(VT_I2);
ADD_CONSTANT(VT_I4);
ADD_CONSTANT(VT_R4);
ADD_CONSTANT(VT_R8);
ADD_CONSTANT(VT_CY);
ADD_CONSTANT(VT_DATE);
ADD_CONSTANT(VT_BSTR);
ADD_CONSTANT(VT_DISPATCH);
ADD_CONSTANT(VT_ERROR);
ADD_CONSTANT(VT_BOOL);
ADD_CONSTANT(VT_VARIANT);
ADD_CONSTANT(VT_UNKNOWN);
ADD_CONSTANT(VT_DECIMAL);
ADD_CONSTANT(VT_I1);
ADD_CONSTANT(VT_UI1);
ADD_CONSTANT(VT_UI2);
ADD_CONSTANT(VT_UI4);
ADD_CONSTANT(VT_I8);
ADD_CONSTANT(VT_UI8);
ADD_CONSTANT(VT_INT);
ADD_CONSTANT(VT_UINT);
ADD_CONSTANT(VT_VOID);
ADD_CONSTANT(VT_HRESULT);
ADD_CONSTANT(VT_PTR);
ADD_CONSTANT(VT_SAFEARRAY);
ADD_CONSTANT(VT_CARRAY);
ADD_CONSTANT(VT_USERDEFINED);
ADD_CONSTANT(VT_LPSTR);
ADD_CONSTANT(VT_LPWSTR);
ADD_CONSTANT(VT_RECORD);
ADD_CONSTANT(VT_FILETIME);
ADD_CONSTANT(VT_BLOB);
ADD_CONSTANT(VT_STREAM);
ADD_CONSTANT(VT_STORAGE);
ADD_CONSTANT(VT_STREAMED_OBJECT);
ADD_CONSTANT(VT_STORED_OBJECT);
ADD_CONSTANT(VT_BLOB_OBJECT);
ADD_CONSTANT(VT_CF);
ADD_CONSTANT(VT_CLSID);
ADD_CONSTANT(VT_BSTR_BLOB);
ADD_CONSTANT(VT_VECTOR);
ADD_CONSTANT(VT_ARRAY);
ADD_CONSTANT(VT_BYREF);
ADD_CONSTANT(VT_RESERVED);
ADD_CONSTANT(VT_ILLEGAL);
ADD_CONSTANT(VT_ILLEGALMASKED);
ADD_CONSTANT(VT_TYPEMASK);
// DestContext for CoMarshalInterface (MSHCTX enum)
ADD_CONSTANT(MSHCTX_LOCAL);
ADD_CONSTANT(MSHCTX_NOSHAREDMEM);
ADD_CONSTANT(MSHCTX_DIFFERENTMACHINE);
ADD_CONSTANT(MSHCTX_INPROC);
// Marshalling flags used with CoMarshalInterface (MSHLFLAGS enum)
ADD_CONSTANT(MSHLFLAGS_NORMAL);
ADD_CONSTANT(MSHLFLAGS_TABLESTRONG);
ADD_CONSTANT(MSHLFLAGS_TABLEWEAK);
ADD_CONSTANT(MSHLFLAGS_NOPING);
// Flags for CreateUrlMoniker
ADD_CONSTANT(URL_MK_UNIFORM);
ADD_CONSTANT(URL_MK_LEGACY);
// Flags for CoWaitForMultipleHandles
ADD_CONSTANT(COWAIT_WAITALL);
ADD_CONSTANT(COWAIT_ALERTABLE);
#ifndef NO_PYCOM_IDISPATCHEX
ADD_CONSTANT(fdexNameCaseSensitive); // Request that the name lookup be done in a case-sensitive manner. May be ignored by object that does not support case-sensitive lookup.
ADD_CONSTANT(fdexNameEnsure); // Request that the member be created if it does not already exist. The new member should be created with the value VT_EMPTY.
ADD_CONSTANT(fdexNameImplicit); // Indicates that the caller is searching object(s) for a member of a particular name, when the base object is not explicitly specified.
ADD_CONSTANT(fdexNameCaseInsensitive); // Request that the name lookup be done in a case-insensitive manner. May be ignored by object that does not support case-insensitive lookup.
ADD_CONSTANT(fdexPropCanGet); // The member can be obtained using DISPATCH_PROPERTYGET.
ADD_CONSTANT(fdexPropCannotGet); // The member cannot be obtained using DISPATCH_PROPERTYGET.
ADD_CONSTANT(fdexPropCanPut); // The member can be set using DISPATCH_PROPERTYPUT.
ADD_CONSTANT(fdexPropCannotPut); // The member cannot be set using DISPATCH_PROPERTYPUT.
ADD_CONSTANT(fdexPropCanPutRef); // The member can be set using DISPATCH_PROPERTYPUTREF.
ADD_CONSTANT(fdexPropCannotPutRef); // The member cannot be set using DISPATCH_PROPERTYPUTREF.
ADD_CONSTANT(fdexPropNoSideEffects); // The member does not have any side effects. For example, a debugger could safely get/set/call this member without changing the state of the script being debugged.
ADD_CONSTANT(fdexPropDynamicType); // The member is dynamic and can change during the lifetime of the object.
ADD_CONSTANT(fdexPropCanCall); // The member can be called as a method using DISPATCH_METHOD.
ADD_CONSTANT(fdexPropCannotCall); // The member cannot be called as a method using DISPATCH_METHOD.
ADD_CONSTANT(fdexPropCanConstruct); // The member can be called as a constructor using DISPATCH_CONSTRUCT.
ADD_CONSTANT(fdexPropCannotConstruct); // The member cannot be called as a constructor using DISPATCH_CONSTRUCT.
ADD_CONSTANT(fdexPropCanSourceEvents); // The member can fire events.
ADD_CONSTANT(fdexPropCannotSourceEvents); // The member cannot fire events.
#endif // NO_PYCOM_IDISPATCHEX
// Expose the frozen flag, as Python itself doesnt!!
// @prop int|frozen|1 if the host is a frozen program, else 0
AddConstant(dict, "frozen", Py_FrozenFlag );
// And finally some gross hacks relating to DCOM
// Im really not sure what a better option is!
//
// If these #error pragma's fire it means this needs revisiting for
// an upgrade to the MSVC header files!
if (PyCom_HasDCom()) {
# if ((CLSCTX_ALL != (CLSCTX_INPROC_SERVER| CLSCTX_INPROC_HANDLER|CLSCTX_LOCAL_SERVER| CLSCTX_REMOTE_SERVER)) || \
(CLSCTX_SERVER != (CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER|CLSCTX_REMOTE_SERVER)))
# error DCOM constants are not in synch.
# endif
ADD_CONSTANT(CLSCTX_ALL);
ADD_CONSTANT(CLSCTX_SERVER);
AddConstant(dict, "dcom", 1 );
} else {
AddConstant(dict, "CLSCTX_ALL", CLSCTX_INPROC_SERVER| CLSCTX_INPROC_HANDLER| CLSCTX_LOCAL_SERVER );
AddConstant(dict, "CLSCTX_SERVER", CLSCTX_INPROC_SERVER| CLSCTX_LOCAL_SERVER );
AddConstant(dict, "dcom", 0 );
}
AddConstant(dict, "__future_currency__", 0);
PyObject *obfmtid=NULL;
obfmtid=PyWinObject_FromIID(FMTID_DocSummaryInformation);
PyDict_SetItemString(dict,"FMTID_DocSummaryInformation",obfmtid);
Py_DECREF(obfmtid);
obfmtid=PyWinObject_FromIID(FMTID_SummaryInformation);
PyDict_SetItemString(dict,"FMTID_SummaryInformation",obfmtid);
Py_DECREF(obfmtid);
obfmtid=PyWinObject_FromIID(FMTID_UserDefinedProperties);
PyDict_SetItemString(dict,"FMTID_UserDefinedProperties",obfmtid);
Py_DECREF(obfmtid);
// obfmtid=PyWinObject_FromIID(FMTID_MediaFileSummaryInfo);
// PyDict_SetItemString(dict,"FMTID_MediaFileSummaryInfo",obfmtid);
// Py_DECREF(obfmtid);
// @prop int|dcom|1 if the system is DCOM aware, else 0. Only Win95 without DCOM extensions should return 0
// ### ALL THE @PROPERTY TAGS MUST COME AFTER THE LAST @PROP TAG!!
// @property int|pythoncom|frozen|1 if the host is a frozen program, else 0
// @property int|pythoncom|dcom|1 if the system is DCOM aware, else 0. Only Win95 without DCOM extensions should return 0
PYWIN_MODULE_INIT_RETURN_SUCCESS;
}
|
[
"denver@sleepydragon.org"
] |
denver@sleepydragon.org
|
55995aeb48ad970642db50003a20a0b3b4918d5b
|
c45ed46065d8b78dac0dd7df1c95b944f34d1033
|
/TC-SRM-567-div1-1000/oysq.cpp
|
9ce257fe231a6a09783dc6cbca5f2e0060064870
|
[] |
no_license
|
yzq986/cntt2016-hw1
|
ed65a6b7ad3dfe86a4ff01df05b8fc4b7329685e
|
12e799467888a0b3c99ae117cce84e8842d92337
|
refs/heads/master
| 2021-01-17T11:27:32.270012
| 2017-01-26T03:23:22
| 2017-01-26T03:23:22
| 84,036,200
| 0
| 0
| null | 2017-03-06T06:04:12
| 2017-03-06T06:04:12
| null |
UTF-8
|
C++
| false
| false
| 1,806
|
cpp
|
// BEGIN CUT HERE
// END CUT HERE
#line 5 "Mountains.cpp"
#include <bits/stdc++.h>
using namespace std;
#define SZ(x) (int)(x).size()
#define pb push_back
#define mp make_pair
#define fi first
#define se second
typedef vector<int> VI;
typedef vector<string> VS;
typedef vector<double> VD;
typedef long long ll;
typedef pair<int,int> pii;
template<class T>inline void chkmax(T &x, const T &y) {if(x < y) x = y;}
template<class T>inline void chkmin(T &x, const T &y) {if(x > y) x = y;}
const int N = 10;
const int W = 50;
const int MOD = 1000000009;
int n, w;
bool vis[N + 9][W + 9];// vis[i][j] = true 表示第i座山在第j列可以看到
std::vector<int> h;// 每个山顶的高度
std::map<std::vector<int>, int> f[N + 9];// f[i][v] 表示倒着放到第i座山时状态为v的方案数
int dp(int x, const std::vector<int> &a) {// x表示当前处理第i座山,a表示每列的高度
if(x == -1) return 1;
if(f[x].count(a)) return f[x][a];// 记忆化搜索
int &ret = f[x][a];
std::vector<int> na;
for(int i = 0; i < w; ++i) {// 枚举山顶的列坐标
bool flag = true;
for(int j = 0; j < w; ++j)
if((h[x] - abs(j - i) <= a[j]) == vis[x][j]) {// 判断是否满足题意
flag = false;
break;
}
if(flag) {
na = a;
for(int j = 0; j < w; ++j)
chkmax(na[j], h[x] - abs(j - i));
(ret += dp(x - 1, na)) %= MOD;
}
}
return ret;
}
struct Mountains {
int countPlacements(vector <int> _h, vector <string> v) {
h = _h, n = SZ(h), w = SZ(v[0]);
for(int i = 0; i < n; ++i) f[i].clear();
for(int i = 0; i < n; ++i)
for(int j = 0; j < w; ++j)
if(v[i][j] == 'X')
vis[i][j] = true;
else
vis[i][j] = false;
std::vector<int> t;
for(int i = 0; i < w; ++i) t.pb(0);// 初始每列的高度为0
return dp(n - 1, t);
}
};
|
[
"owaski123@gmail.com"
] |
owaski123@gmail.com
|
0a0893e0d653780a1c0a7ac24d780cd30093a535
|
f37a800cd831b948949ecc054c5be2aac87b4331
|
/lab6-sound/tinyos/support/cpp/ali/ACP/main.cpp
|
e4df1e401597a08f4175046af2e200a9bfe01a34
|
[] |
no_license
|
ChenchengLiang/Practical-Course-on-WSNs-Lab-WS16-17
|
e1f3018900cecaa49731163b3f3ff79a50321c5b
|
c7f2573ad558c514d6d6985cd78c6131e74db04d
|
refs/heads/master
| 2020-03-31T10:40:51.605436
| 2018-10-08T20:48:24
| 2018-10-08T20:48:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,571
|
cpp
|
/** Copyright (c) 2010, University of Szeged
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* - Neither the name of University of Szeged nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Author: Ali Baharev
*/
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <sstream>
#include <list>
#include <vector>
#include <cassert>
using namespace std;
namespace {
const int N_FIELDS = 10;
typedef unsigned short uint16;
typedef unsigned int uint32;
const uint32 TICKS_PER_SEC = 32768;
const uint32 SAMPLING_RATE = 160;
const uint32 TOLERANCE = 4;
struct dat {
uint32 time;
uint16 counter;
uint16 ax;
uint16 ay;
uint16 az;
uint16 wx;
uint16 wy;
uint16 wz;
uint16 volt;
uint16 temp;
};
const char header[] = "Time,sequence_number,Accel_X,Accel_Y,Accel_Z,Gyro_X,Gyro_Y,Gyro_Z,Volt,Temp";
vector<list<dat>*> data;
typedef list<dat>::const_iterator cli;
typedef list<dat>::reverse_iterator rli;
}
void exit(const string& msg) {
cout << "Error: " << msg << "!" << endl;
exit(1);
}
const string int2string(const int i) {
ostringstream os;
os << i << flush;
return os.str();
}
const string time2str(uint32 t) {
ostringstream os;
uint32 hour, min, sec, milli;
hour = t/(3600*TICKS_PER_SEC);
t = t%(3600*TICKS_PER_SEC);
min = t/(60*TICKS_PER_SEC);
t = t%(60*TICKS_PER_SEC);
sec = t/TICKS_PER_SEC;
t = t%TICKS_PER_SEC;
milli = t/(TICKS_PER_SEC/1000.0);
os << setfill('0') << setw(2) << hour << ":";
os << setfill('0') << setw(2) << min << ":";
os << setfill('0') << setw(2) << sec << ".";
os << setfill('0') << setw(3) << milli<< flush;
return os.str();
}
bool str2ticks(uint32& ticks, const uint32 max) {
uint32 hour, min, sec;
string sh;
string sm;
string ss;
getline(cin, sh, ':');
getline(cin, sm, ':');
getline(cin, ss);
hour = atoi(sh.c_str());
min = atoi(sm.c_str());
sec = atoi(ss.c_str());
if ((hour<0 || hour>99) || (min<0 || min>59) || (sec<0 || sec>59)) {
cout << "Error: incorrect format for time string" << endl;
ticks = 0;
return true;
}
ticks = (3600*TICKS_PER_SEC)*hour + (60*TICKS_PER_SEC)*min + TICKS_PER_SEC*sec;
if (ticks > max) {
cout << "Error: the entered time is greater that the length!" << endl;
return true;
}
return false;
}
void check_data_consistency(const dat& b, uint32 lines, uint32 prevTime, uint16 prevCnt) {
uint16 cnt = b.counter;
if (!((cnt-prevCnt == 1) || (cnt==0 && prevCnt==0xFFFF))) {
cout << "Warning: line " << lines << flush;
cout << ", missing " << (cnt-prevCnt-1) << " samples" << endl;
}
uint32 expected = prevTime + SAMPLING_RATE;
int dt = b.time - expected;
if (abs(dt) > TOLERANCE) {
cout << "Warning: line " << lines << flush;
cout << ", " << dt << " ticks error" << endl;
}
}
void allocate_container(list<dat>*& samples, const dat& b, uint32& t0, uint32 lines) {
cout << "Found a re-boot on line " << lines << endl;
samples = new list<dat>();
data.push_back(samples);
t0 = b.time;
}
void print_info() {
const int n = static_cast<int> (data.size());
cout << n << " measurements" << endl;
for (int i=0; i<n; ++i) {
list<dat>* samples = data.at(i);
rli rbeg(samples->rbegin());
cout << "Length of #" << (i+1) << " is "<< time2str(rbeg->time) << endl;
}
}
void grab_content(const char* filename) {
FILE* in = fopen(filename, "r");
if (!in) {
exit("failed to open input file");
}
cout << "Reading file " << filename << endl;
//==========================================================================
char first_line[sizeof(header)];
fgets(first_line, sizeof(first_line), in);
if (string(header)!=first_line) {
exit("wrong file format");
}
//==========================================================================
const int m = static_cast<int> (data.size());
for (int i=0; i<m; ++i) {
delete data.at(i);
}
data.clear();
//==========================================================================
const char* fmt = "%u,%hu,%hu,%hu,%hu,%hu,%hu,%hu,%hu,%hu";
uint32 lines = 1;
dat b;
int n;
uint16 prevCnt = 1;
uint32 prevTime = 0;
list<dat>* samples = 0;
uint32 t0 = 0;
//==========================================================================
while ( (!ferror(in)) && (!feof(in)) ) {
n = fscanf(in,fmt,&b.time,&b.counter,&b.ax,&b.ay,&b.az,&b.wx, &b.wy, &b.wz, &b.volt,&b.temp);
++lines;
if (n!= N_FIELDS) {
cout << "Conversion failed on line " << lines << endl;
break;
}
if (b.time==0 && b.counter==0) {
cout << "Warning: found a line with zeros, at " << lines;
cout << ", reading stopped!" << endl;
break;
}
if (b.counter == 1 && prevCnt != 0) {
allocate_container(samples, b, t0, lines);
}
else {
check_data_consistency(b, lines, prevTime, prevCnt);
}
prevTime = b.time;
prevCnt = b.counter;
b.time -= t0;
samples->push_back(b);
}
cout << "Read " << lines << endl;
fclose(in);
in = 0;
}
void dump_data(const char* filename, int index, uint32 start, uint32 end) {
const list<dat>* const samples = data.at(index-1);
cli i(samples->begin());
while (i!=samples->end() && i->time < start) {
++i;
}
ostringstream os;
os << filename << '_' << index << '_' << start << '_' << end << flush;
ofstream out(os.str().c_str());
if (!out) {
exit("failed to create output file");
}
out << "#" << header << ",RotMat[9]" << endl;
uint32 lines = 0;
while (i!=samples->end() && i->time <= end) {
dat b = *i;
// b.counter removed, currently not supported in TestShimmer
out << b.time << ',' << b.ax << ',' << b.ay << ',' << b.az;
out << ',' << b.wx << ',' << b.wy << ',' << b.wz << ',' << b.volt << ',' << b.temp ;
out << ',' << 1 << ',' << 0 << ',' << 0;
out << ',' << 0 << ',' << 1 << ',' << 0;
out << ',' << 0 << ',' << 0 << ',' << 1;
out << endl;
++i;
++lines;
}
out.close();
cout << lines << " lines written" << endl;
}
int main(int argc, char* argv[]) {
if (argc!=2) {
exit("specify input file");
}
const char* filename = argv[1];
grab_content(filename);
print_info();
while (true) {
print_info();
cout << "Select measurement (or -1 to quit): " << flush;
int n = 0;
cin >> n;
if (n==-1) {
break;
}
else if (n < 1 || n > static_cast<int> (data.size())) {
cout << "Error: " << n << " is out of range (" << flush;
cout << 1 << ", " << data.size() << ")" << endl;
continue;
}
const uint32 ticks = data.at(n-1)->rbegin()->time;
cout << "Length of #" << n << " is "<< flush;
cout << time2str(ticks) << endl;
cout << "Enter start in hh:mm:ss format" << endl;
uint32 start;
if (str2ticks(start, ticks))
continue;
cout << "Enter end in hh:mm:ss format" << endl;
uint32 end;
if (str2ticks(end, ticks))
continue;
if (start >= end) {
cout << "Error: start must be before end!" << endl;
continue;
}
cout << "Cropping from " << time2str(start) << " to " << time2str(end) << endl;
cout << "Check the time strings, are they OK? [y,n]" << endl;
char c = cin.get();
if (c!='y')
continue;
cout << "Writing cropped file" << endl;
dump_data(filename, n, start, end);
}
cout << "Terminated ..." << endl;
return 0;
}
|
[
"lcckkkhaha@163.com"
] |
lcckkkhaha@163.com
|
e4a9c8ca91f878dc313aee2aad48a546408124a7
|
e926db4dab0237aaae30a539b5f69ad37b195091
|
/scale_puzzle/src/scale_puzzle/scale_puzzle.ino
|
5c0c60e108742a4fd7256aae18f04fe23cae34eb
|
[] |
no_license
|
ubilab-escape/prototype
|
6b4fca4f3d1820278a3d7847f3ef2daed9c7af0f
|
a673625ef53867bb029d6ddc2312c830b2f05bfa
|
refs/heads/master
| 2020-08-26T20:52:12.852255
| 2020-02-29T21:34:13
| 2020-02-29T21:34:13
| 217,144,860
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,400
|
ino
|
#include <Arduino.h>
#include <ESP8266WiFi.h>
/* define keepalive settings before PubSubClient.h */
#define MQTT_KEEPALIVE 10
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "HX711.h"
#include "scale_puzzle.h"
#include "wifi_pw.h"
/* uncomment to activate debug mode */
//#define DEBUG
/* State machine variables */
ScalePuzzle_HandlerType ScaleStruct;
/* Scale variables */
HX711 scale;
const long scale_divider = 7000;
const int LOADCELL_DOUT_PIN = 13;
const int LOADCELL_SCK_PIN = 12;
const int LED_GREEN = 0;
const int LED_RED = 5;
/* WiFi, Mqtt variables */
WiFiClient espClient;
PubSubClient client(espClient);
StaticJsonDocument<300> rxdoc;
/* MQTT Topics */
const char* Safe_activate_topic = "5/safe/control";
const char* Mqtt_topic = "6/puzzle/scale";
const char* Mqtt_terminal = "6/puzzle/terminal";
/* MQTT Messages */
const char* Msg_inactive = "{\"method\": \"status\", \"state\": \"inactive\"}";
const char* Msg_active = "{\"method\": \"status\", \"state\": \"active\"}";
const char* Msg_solved = "{\"method\":\"status\",\"state\":\"solved\"}";
const char* Msg_green = "{\"method\":\"trigger\",\"state\":\"on\",\"data\":\"2:0\"}"; // Constant green
const char* Msg_red = "{\"method\":\"trigger\",\"state\":\"on\",\"data\":\"1:3\"}"; // Blinking red
const char* Msg_orange = "{\"method\":\"trigger\",\"state\":\"on\",\"data\":\"4:3\"}"; // Blinking orange
/* Arduino main functions */
void setup() {
#ifdef DEBUG
Serial.begin(115200);
delay(3000);
Serial.println();
#endif
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale(scale_divider);
}
void loop() {
/* scale puzzle state machine */
switch (ScaleStruct.state) {
case INIT:
InitScalePuzzleStructure();
debug_print(String(ScaleStruct.state));
ScaleStruct.state = WIFI_SETUP;
wifi_set_sleep_type(NONE_SLEEP_T);
break;
case WIFI_SETUP:
if (wifi_setup() != false) {
delay(500);
ScaleStruct.connection_check_counter = 0;
debug_print(String(ScaleStruct.state));
ScaleStruct.state = MQTT_SETUP;
}
break;
case MQTT_SETUP:
if (mqtt_setup() != false) {
delay(500);
debug_print(String(ScaleStruct.state));
ScaleStruct.state = MQTT_CONNECT;
}
break;
case MQTT_CONNECT:
if (mqtt_connect() != false) {
delay(500);
ScaleStruct.mqtt_connected = true;
debug_print(String(ScaleStruct.state));
ScaleStruct.state = PUZZLE_START;
}
break;
case PUZZLE_START:
ReInitScalePuzzleStructure();
debug_print(String(ScaleStruct.state));
ScaleStruct.state = SCALE_CALIBRATION;
break;
case SCALE_CALIBRATION:
if (calibration_setup() != false) {
debug_print(String(ScaleStruct.state));
if (client.publish(Mqtt_topic, Msg_inactive, true) != false) {
ScaleStruct.state = WAIT_FOR_BEGIN;
}
}
break;
case WAIT_FOR_BEGIN:
if (ScaleStruct.puzzle_start != false) {
debug_print(String(ScaleStruct.state));
ScaleStruct.state = SCALE_GREEN;
}
break;
case SCALE_GREEN:
if (is_scale_unbalanced() != false) {
debug_print(String(ScaleStruct.state));
if (client.publish(Mqtt_topic, Msg_active, true) != false) {
ScaleStruct.state = SCALE_RED;
}
}
break;
case SCALE_RED:
if (is_scale_balanced() != false) {
debug_print(String(ScaleStruct.state));
if (client.publish(Mqtt_topic, Msg_inactive, true) != false) {
ScaleStruct.state = SCALE_GREEN;
}
}
break;
case PUZZLE_SOLVED:
if (client.publish(Mqtt_topic, Msg_solved, true) != false) {
set_safe_color(LED_STATE_GREEN);
ScaleStruct.puzzle_solved = false;
debug_print(String(ScaleStruct.state));
ScaleStruct.state = WAIT_FOR_RESTART;
}
break;
case WAIT_FOR_RESTART:
if (ScaleStruct.puzzle_restart != false) {
debug_print(String(ScaleStruct.state));
ScaleStruct.state = RESTART;
}
break;
case MQTT_LOST:
if (mqtt_connect() != false) {
debug_print(String(ScaleStruct.state));
ScaleStruct.state = ScaleStruct.reconnect_state;
} else {
ScaleStruct.mqtt_connected = false;
}
break;
case WIFI_LOST:
WiFi.disconnect();
debug_print(String(ScaleStruct.state));
ScaleStruct.state = INIT;
break;
case ERROR_STATE:
WiFi.disconnect();
debug_print(String(ScaleStruct.state));
ScaleStruct.state = INIT;
break;
case RESTART:
debug_print(String(ScaleStruct.state));
ScaleStruct.state = PUZZLE_START;
break;
default:
break;
}
/* puzzle solved trigger or skip puzzle trigger arrived */
if ((ScaleStruct.puzzle_solved != false) && (ScaleStruct.puzzle_restart == false)) {
ScaleStruct.state = PUZZLE_SOLVED;
}
/* restart trigger arrived */
if ((ScaleStruct.puzzle_solved == false) && (ScaleStruct.puzzle_restart != false)) {
ScaleStruct.puzzle_restart = false;
ScaleStruct.state = RESTART;
}
/* restart if both triggers are sent */
if ((ScaleStruct.puzzle_solved != false) && (ScaleStruct.puzzle_restart != false)) {
ScaleStruct.state = RESTART;
ScaleStruct.puzzle_solved = false;
ScaleStruct.puzzle_restart = false;
}
/* run mqtt handling */
if (ScaleStruct.mqtt_connected != false) {
client.loop();
}
delay(100);
/* run wifi and mqtt checks approx. every 5s */
if (ScaleStruct.connection_check_counter > 49) {
if ((ScaleStruct.state > WIFI_SETUP) &&
(ScaleStruct.state < WIFI_LOST) &&
(WiFi.status() != WL_CONNECTED)) {
ScaleStruct.state = WIFI_LOST;
debug_print("WIFI LOST");
}
if ((ScaleStruct.state > MQTT_CONNECT) &&
(ScaleStruct.state < MQTT_LOST) &&
(client.state() != 0)){
ScaleStruct.reconnect_state = ScaleStruct.state;
ScaleStruct.state = MQTT_LOST;
}
ScaleStruct.connection_check_counter = 0;
}
ScaleStruct.connection_check_counter += 1;
}
/* State Machine functions */
/*****************************************************************************************
FUNCTION INFO
NAME:
InitScalePuzzleStructure
DESCRIPTION:
Initialization function to initialize the Scale Puzzle Structure.
To call at every startup of the device.
*****************************************************************************************/
void InitScalePuzzleStructure(void) {
ScaleStruct.state = INIT;
ScaleStruct.mqtt_connected = false;
ScaleStruct.connection_check_counter = 0;
ScaleStruct.scale_failure = 0;
ReInitScalePuzzleStructure();
}
/*****************************************************************************************
FUNCTION INFO
NAME:
ReInitScalePuzzleStructure
DESCRIPTION:
Initialization function to reinitialize the Scale Puzzle Structure.
To call at every restart of the puzzle.
*****************************************************************************************/
void ReInitScalePuzzleStructure(void) {
ScaleStruct.reconnect_state = ERROR_STATE;
ScaleStruct.led_state = LED_STATE_GREEN;
ScaleStruct.puzzle_start = false;
ScaleStruct.led_control = false;
ScaleStruct.puzzle_solved = false;
ScaleStruct.puzzle_restart = false;
}
/*****************************************************************************************
FUNCTION INFO
NAME:
wifi_setup
DESCRIPTION:
Connect to the given WiFi. For the password create a file named wifi_pw.h and define
a variable "const char* PASSWORD" containing the password.
*****************************************************************************************/
bool wifi_setup(void) {
bool wifi_finished = false;
const char* ssid = "ubilab_wifi";
const char* pw = PASSWORD;
WiFi.begin(ssid, pw);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
#ifdef DEBUG
Serial.print(".");
#endif
if (WiFi.status() == WL_CONNECTED) {
wifi_finished = true;
delay(500);
debug_print(String("Connection status: " + String(WiFi.status())));
delay(500);
debug_print("Connected, IP address: ");
debug_print(WiFi.localIP().toString());
} else {
delay(500);
}
}
return wifi_finished;
}
/*****************************************************************************************
FUNCTION INFO
NAME:
mqtt_setup
DESCRIPTION:
Submits the MQTT connection with the specified IP address and MQTT server port to the
MQTT client.
Submits the callback function with a given set of messages to the MQTT client.
*****************************************************************************************/
bool mqtt_setup(void) {
bool mqtt_setup_finished = false;
const IPAddress mqttServerIP(10,0,0,2);
uint16_t mqtt_server_port = 1883;
client.setServer(mqttServerIP, mqtt_server_port);
client.setCallback(mqtt_callback);
delay(100);
debug_print("Keepalive setting:");
debug_print(String(MQTT_KEEPALIVE));
mqtt_setup_finished = true;
return mqtt_setup_finished;
}
/*****************************************************************************************
FUNCTION INFO
NAME:
mqtt_connect
DESCRIPTION:
Creates a new client ID and connects to the MQTT server.
Creates subscriptions to the specified MQTT topics.
If no connection is possible, wait 2 seconds before the next try.
*****************************************************************************************/
bool mqtt_connect(void) {
bool reconnect_finished = false;
debug_print("Attempting MQTT connection...");
/* Create a random client ID */
String clientId = "ESP8266Scale-";
clientId += String(random(0xffff), HEX);
/* Attempt to connect */
if (client.connect(clientId.c_str())) {
debug_print("connected");
/* Subscribe */
client.subscribe(Mqtt_topic);
client.subscribe(Mqtt_terminal);
reconnect_finished = true;
} else {
debug_print("failed, rc=");
debug_print(String(client.state()));
debug_print("try again in 5 seconds");
/* Wait 2 seconds before retrying */
delay(2000);
}
return reconnect_finished;
}
/*****************************************************************************************
FUNCTION INFO
NAME:
calibration_setup
DESCRIPTION:
Tare the scale to the current weight and wait until the scale is ready.
*****************************************************************************************/
bool calibration_setup(void) {
bool calibration_finished = false;
scale.tare();
debug_print("Beginning:");
#ifdef DEBUG
pinMode(LED_RED, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
#endif
while (!scale.is_ready()) {
Serial.println("Scale is not ready");
delay(100);
}
calibration_finished = true;
return calibration_finished;
}
/*****************************************************************************************
FUNCTION INFO
NAME:
is_scale_unbalanced
DESCRIPTION:
Measure the weight on the scale and if a wrong weight is measured, change the color
of the safe to red. The measuring process is debounced.
*****************************************************************************************/
bool is_scale_unbalanced(void) {
bool unbalanced = false;
static int red_count = 0;
if (scale_measure_floppy_disks() == 0) {
red_count = 0;
} else {
red_count++;
if (red_count == RED_DELAY) {
debug_led(LED_RED);
set_safe_color(LED_STATE_RED);
red_count = 0;
unbalanced = true;
}
}
return unbalanced;
}
/*****************************************************************************************
FUNCTION INFO
NAME:
is_scale_balanced
DESCRIPTION:
Measure the weight on the scale and if the initially tared weight is measured, change
the color of the safe to green. The measuring process is debounced.
*****************************************************************************************/
bool is_scale_balanced(void) {
bool balanced = false;
static int old_reading = 4;
static int new_reading = 4;
static int green_count = 0;
/* measure the current weight */
int reading = scale_measure_floppy_disks();
/* compare the last measured value with the current value */
old_reading = new_reading;
new_reading = reading;
if (old_reading == new_reading) {
if (new_reading == 0) {
green_count++;
if (green_count == GREEN_DELAY) {
debug_led(LED_GREEN);
set_safe_color(LED_STATE_GREEN);
green_count = 0;
balanced = true;
}
} else {
green_count = 0;
}
} else {
green_count = 0;
}
return balanced;
}
/* Utility Functions */
/*****************************************************************************************
FUNCTION INFO
NAME:
mqtt_callback
DESCRIPTION:
Evaluates the received MQTT messages. The following messages are processed:
Topic: 6/puzzle/scale
Messages: trigger on || starts the puzzle
trigger off || restarts the puzzle
trigger off skipped || skips the puzzle and starts puzzle solved handling
Topic: 6/puzzle/terminal
Message: status active || sets the puzzle to solved
*****************************************************************************************/
void mqtt_callback(char* topic, byte* message, unsigned int length) {
debug_print("Message arrived on topic: ");
debug_print(topic);
debug_print(". Message: ");
String messageTemp;
for (unsigned int i = 0; i < length; i++) {
messageTemp += (char)message[i];
}
debug_print(messageTemp);
deserializeJson(rxdoc, message);
const char* method1 = rxdoc["method"];
const char* state1 = rxdoc["state"];
const char* data1 = rxdoc["data"];
/* If a message is received on the topic 6/puzzle/scale, check the message. */
if (String(topic).equals(Mqtt_topic) != false) {
if (String(method1).equals("trigger") != false) {
if (String(state1).equals("on") != false) {
debug_print("Start Puzzle");
ScaleStruct.puzzle_start = true;
ScaleStruct.led_control = true;
} else if (String(state1).equals("off") != false){
if (String(data1).equals("skipped") != false) {
debug_print("Puzzle Skipped");
ScaleStruct.puzzle_solved = true;
} else {
debug_print("Restart Puzzle");
ScaleStruct.puzzle_restart = true;
}
}
}
}
/* If a message is received on the topic 6/puzzle/terminal, check the message. */
if (String(topic).equals(Mqtt_terminal) != false) {
if (String(method1).equals("status") != false) {
if (String(state1).equals("active") != false) {
debug_print("Puzzle Solved");
ScaleStruct.puzzle_solved = true;
}
}
}
}
/*****************************************************************************************
FUNCTION INFO
NAME:
scale_measure_floppy_disks
DESCRIPTION:
Measures the weight on the scale. The scale is tared to a certain amount of floppy
disks. The amount of floppy disks is returned.
If the scale is not reacting for a specific time go to the error state.
*****************************************************************************************/
int scale_measure_floppy_disks() {
int measure = 0;
if (scale.is_ready()) {
measure = round(scale.get_units(10));
ScaleStruct.scale_failure = 0;
debug_print("Value for known weight is: ");
debug_print(String(measure));
} else {
debug_print("HX711 not found.");
ScaleStruct.scale_failure = ScaleStruct.scale_failure + 1;
if (ScaleStruct.scale_failure > 20) {
ScaleStruct.state = ERROR_STATE;
}
delay(500);
}
return measure;
}
/*****************************************************************************************
FUNCTION INFO
NAME:
set_safe_color
DESCRIPTION:
Sends a MQTT message to the safe with a specific color. The colors green, red and
orange are possible.
*****************************************************************************************/
void set_safe_color(led_state_t color_state){
const char* color_message;
if (ScaleStruct.led_control != false) {
if ((ScaleStruct.led_state != color_state)) {
switch (color_state) {
case LED_STATE_GREEN:
color_message = Msg_green;
break;
case LED_STATE_ORANGE:
color_message = Msg_orange;
break;
case LED_STATE_RED:
color_message = Msg_red;
break;
default:
color_message = Msg_green;
break;
}
if (client.publish(Safe_activate_topic, color_message, false) != false) {
ScaleStruct.led_state = color_state;
}
}
}
}
/*****************************************************************************************
FUNCTION INFO
NAME:
debug_print
DESCRIPTION:
Debug function to print messages via serial connection.
*****************************************************************************************/
void debug_print(String print_string) {
#ifdef DEBUG
Serial.println(print_string);
#endif
}
/*****************************************************************************************
FUNCTION INFO
NAME:
debug_led
DESCRIPTION:
Debug function to connect LEDs to show the current scale status.
*****************************************************************************************/
void debug_led(int led_color) {
#ifdef DEBUG
if (led_color == LED_RED) {
digitalWrite(LED_RED, HIGH);
digitalWrite(LED_GREEN, LOW);
}
if (led_color == LED_GREEN) {
digitalWrite(LED_RED, LOW);
digitalWrite(LED_GREEN, HIGH);
}
#endif
}
|
[
"niklas.steinwachs@gmail.com"
] |
niklas.steinwachs@gmail.com
|
defe98cf16efd53719fd8430f90528824ef85856
|
fafce52a38479e8391173f58d76896afcba07847
|
/uppdev/YPuzzle/TinyXML/tinyxml.h
|
0024ae903bccd754478dc1cd8ced715361f6f7ed
|
[] |
no_license
|
Sly14/upp-mirror
|
253acac2ec86ad3a3f825679a871391810631e61
|
ed9bc6028a6eed422b7daa21139a5e7cbb5f1fb7
|
refs/heads/master
| 2020-05-17T08:25:56.142366
| 2015-08-24T18:08:09
| 2015-08-24T18:08:09
| 41,750,819
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 51,669
|
h
|
/*
www.sourceforge.net/projects/tinyxml
Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef TINYXML_INCLUDED
#define TINYXML_INCLUDED
#ifdef _MSC_VER
#pragma warning( disable : 4530 )
#pragma warning( disable : 4786 )
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
// Help out windows:
#if defined( _DEBUG ) && !defined( DEBUG )
#define DEBUG
#endif
#if defined( DEBUG ) && defined( _MSC_VER )
#include <windows.h>
#define TIXML_LOG OutputDebugString
#else
#define TIXML_LOG printf
#endif
#ifdef TIXML_USE_STL
#include <string>
#include <iostream>
#define TIXML_STRING std::string
#define TIXML_ISTREAM std::istream
#define TIXML_OSTREAM std::ostream
#else
#include "tinystr.h"
#define TIXML_STRING TiXmlString
#define TIXML_OSTREAM TiXmlOutStream
#endif
class TiXmlDocument;
class TiXmlElement;
class TiXmlComment;
class TiXmlUnknown;
class TiXmlAttribute;
class TiXmlText;
class TiXmlDeclaration;
class TiXmlParsingData;
const int TIXML_MAJOR_VERSION = 2;
const int TIXML_MINOR_VERSION = 3;
const int TIXML_PATCH_VERSION = 4;
/* Internal structure for tracking location of items
in the XML file.
*/
struct TiXmlCursor
{
TiXmlCursor() { Clear(); }
void Clear() { row = col = -1; }
int row; // 0 based.
int col; // 0 based.
};
// Only used by Attribute::Query functions
enum
{
TIXML_SUCCESS,
TIXML_NO_ATTRIBUTE,
TIXML_WRONG_TYPE
};
// Used by the parsing routines.
enum TiXmlEncoding
{
TIXML_ENCODING_UNKNOWN,
TIXML_ENCODING_UTF8,
TIXML_ENCODING_LEGACY
};
const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN;
/** TiXmlBase is a base class for every class in TinyXml.
It does little except to establish that TinyXml classes
can be printed and provide some utility functions.
In XML, the document and elements can contain
other elements and other types of nodes.
@verbatim
A Document can contain: Element (container or leaf)
Comment (leaf)
Unknown (leaf)
Declaration( leaf )
An Element can contain: Element (container or leaf)
Text (leaf)
Attributes (not on tree)
Comment (leaf)
Unknown (leaf)
A Decleration contains: Attributes (not on tree)
@endverbatim
*/
class TiXmlBase
{
friend class TiXmlNode;
friend class TiXmlElement;
friend class TiXmlDocument;
public:
TiXmlBase() : userData(0) {}
virtual ~TiXmlBase() {}
/** All TinyXml classes can print themselves to a filestream.
This is a formatted print, and will insert tabs and newlines.
(For an unformatted stream, use the << operator.)
*/
virtual void Print( FILE* cfile, int depth ) const = 0;
/** The world does not agree on whether white space should be kept or
not. In order to make everyone happy, these global, static functions
are provided to set whether or not TinyXml will condense all white space
into a single space or not. The default is to condense. Note changing this
values is not thread safe.
*/
static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; }
/// Return the current white space setting.
static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; }
/** Return the position, in the original source file, of this node or attribute.
The row and column are 1-based. (That is the first row and first column is
1,1). If the returns values are 0 or less, then the parser does not have
a row and column value.
Generally, the row and column value will be set when the TiXmlDocument::Load(),
TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set
when the DOM was created from operator>>.
The values reflect the initial load. Once the DOM is modified programmatically
(by adding or changing nodes and attributes) the new values will NOT update to
reflect changes in the document.
There is a minor performance cost to computing the row and column. Computation
can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value.
@sa TiXmlDocument::SetTabSize()
*/
int Row() const { return location.row + 1; }
int Column() const { return location.col + 1; } ///< See Row()
void SetUserData( void* user ) { userData = user; }
void* GetUserData() { return userData; }
// Table that returs, for a given lead byte, the total number of bytes
// in the UTF-8 sequence.
static const int utf8ByteTable[256];
virtual const char* Parse( const char* p,
TiXmlParsingData* data,
TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0;
enum
{
TIXML_NO_ERROR = 0,
TIXML_ERROR,
TIXML_ERROR_OPENING_FILE,
TIXML_ERROR_OUT_OF_MEMORY,
TIXML_ERROR_PARSING_ELEMENT,
TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME,
TIXML_ERROR_READING_ELEMENT_VALUE,
TIXML_ERROR_READING_ATTRIBUTES,
TIXML_ERROR_PARSING_EMPTY,
TIXML_ERROR_READING_END_TAG,
TIXML_ERROR_PARSING_UNKNOWN,
TIXML_ERROR_PARSING_COMMENT,
TIXML_ERROR_PARSING_DECLARATION,
TIXML_ERROR_DOCUMENT_EMPTY,
TIXML_ERROR_EMBEDDED_NULL,
TIXML_ERROR_STRING_COUNT
};
protected:
// See STL_STRING_BUG
// Utility class to overcome a bug.
class StringToBuffer
{
public:
StringToBuffer( const TIXML_STRING& str );
~StringToBuffer();
char* buffer;
};
static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding );
inline static bool IsWhiteSpace( char c )
{
return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' );
}
virtual void StreamOut (TIXML_OSTREAM *) const = 0;
#ifdef TIXML_USE_STL
static bool StreamWhiteSpace( TIXML_ISTREAM * in, TIXML_STRING * tag );
static bool StreamTo( TIXML_ISTREAM * in, int character, TIXML_STRING * tag );
#endif
/* Reads an XML name into the string provided. Returns
a pointer just past the last character of the name,
or 0 if the function has an error.
*/
static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding );
/* Reads text. Returns a pointer past the given end tag.
Wickedly complex options, but it keeps the (sensitive) code in one place.
*/
static const char* ReadText( const char* in, // where to start
TIXML_STRING* text, // the string read
bool ignoreWhiteSpace, // whether to keep the white space
const char* endTag, // what ends this text
bool ignoreCase, // whether to ignore case in the end tag
TiXmlEncoding encoding ); // the current encoding
// If an entity has been found, transform it into a character.
static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding );
// Get a character, while interpreting entities.
// The length can be from 0 to 4 bytes.
inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding )
{
assert( p );
if ( encoding == TIXML_ENCODING_UTF8 )
{
*length = utf8ByteTable[ *((unsigned char*)p) ];
assert( *length >= 0 && *length < 5 );
}
else
{
*length = 1;
}
if ( *length == 1 )
{
if ( *p == '&' )
return GetEntity( p, _value, length, encoding );
*_value = *p;
return p+1;
}
else if ( *length )
{
strncpy( _value, p, *length );
return p + (*length);
}
else
{
// Not valid text.
return 0;
}
}
// Puts a string to a stream, expanding entities as it goes.
// Note this should not contian the '<', '>', etc, or they will be transformed into entities!
static void PutString( const TIXML_STRING& str, TIXML_OSTREAM* out );
static void PutString( const TIXML_STRING& str, TIXML_STRING* out );
// Return true if the next characters in the stream are any of the endTag sequences.
// Ignore case only works for english, and should only be relied on when comparing
// to Engilish words: StringEqual( p, "version", true ) is fine.
static bool StringEqual( const char* p,
const char* endTag,
bool ignoreCase,
TiXmlEncoding encoding );
static const char* errorString[ TIXML_ERROR_STRING_COUNT ];
TiXmlCursor location;
/// Field containing a generic user pointer
void* userData;
// None of these methods are reliable for any language except English.
// Good for approximation, not great for accuracy.
static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding );
static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding );
inline static int ToLower( int v, TiXmlEncoding encoding )
{
if ( encoding == TIXML_ENCODING_UTF8 )
{
if ( v < 128 ) return tolower( v );
return v;
}
else
{
return tolower( v );
}
}
static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
private:
TiXmlBase( const TiXmlBase& ); // not implemented.
void operator=( const TiXmlBase& base ); // not allowed.
struct Entity
{
const char* str;
unsigned int strLength;
char chr;
};
enum
{
NUM_ENTITY = 5,
MAX_ENTITY_LENGTH = 6
};
static Entity entity[ NUM_ENTITY ];
static bool condenseWhiteSpace;
};
/** The parent class for everything in the Document Object Model.
(Except for attributes).
Nodes have siblings, a parent, and children. A node can be
in a document, or stand on its own. The type of a TiXmlNode
can be queried, and it can be cast to its more defined type.
*/
class TiXmlNode : public TiXmlBase
{
friend class TiXmlDocument;
friend class TiXmlElement;
public:
#ifdef TIXML_USE_STL
/** An input stream operator, for every class. Tolerant of newlines and
formatting, but doesn't expect them.
*/
friend std::istream& operator >> (std::istream& in, TiXmlNode& base);
/** An output stream operator, for every class. Note that this outputs
without any newlines or formatting, as opposed to Print(), which
includes tabs and new lines.
The operator<< and operator>> are not completely symmetric. Writing
a node to a stream is very well defined. You'll get a nice stream
of output, without any extra whitespace or newlines.
But reading is not as well defined. (As it always is.) If you create
a TiXmlElement (for example) and read that from an input stream,
the text needs to define an element or junk will result. This is
true of all input streams, but it's worth keeping in mind.
A TiXmlDocument will read nodes until it reads a root element, and
all the children of that root element.
*/
friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base);
/// Appends the XML node or attribute to a std::string.
friend std::string& operator<< (std::string& out, const TiXmlNode& base );
#else
// Used internally, not part of the public API.
friend TIXML_OSTREAM& operator<< (TIXML_OSTREAM& out, const TiXmlNode& base);
#endif
/** The types of XML nodes supported by TinyXml. (All the
unsupported types are picked up by UNKNOWN.)
*/
enum NodeType
{
DOCUMENT,
ELEMENT,
COMMENT,
UNKNOWN,
TEXT,
DECLARATION,
TYPECOUNT
};
virtual ~TiXmlNode();
/** The meaning of 'value' changes for the specific type of
TiXmlNode.
@verbatim
Document: filename of the xml file
Element: name of the element
Comment: the comment text
Unknown: the tag contents
Text: the text string
@endverbatim
The subclasses will wrap this function.
*/
const char * Value() const { return value.c_str (); }
/** Changes the value of the node. Defined as:
@verbatim
Document: filename of the xml file
Element: name of the element
Comment: the comment text
Unknown: the tag contents
Text: the text string
@endverbatim
*/
void SetValue(const char * _value) { value = _value;}
#ifdef TIXML_USE_STL
/// STL std::string form.
void SetValue( const std::string& _value )
{
StringToBuffer buf( _value );
SetValue( buf.buffer ? buf.buffer : "" );
}
#endif
/// Delete all the children of this node. Does not affect 'this'.
void Clear();
/// One step up the DOM.
TiXmlNode* Parent() { return parent; }
const TiXmlNode* Parent() const { return parent; }
const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children.
TiXmlNode* FirstChild() { return firstChild; }
const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found.
TiXmlNode* FirstChild( const char * value ); ///< The first child of this node with the matching 'value'. Will be null if none found.
///Arlen Albert Keshabian addons: gets the element a path points to
virtual TiXmlNode *NodeFromPath(const char *sPath, char chSeparator = '.') const;
virtual TiXmlElement *ElementFromPath(const char *sPath, char chSeparator = '.') const
{
TiXmlNode *l_pNode = NodeFromPath(sPath, chSeparator);
return (l_pNode) ? l_pNode->ToElement() : NULL;
}
#ifdef TIXML_USE_STL
virtual TiXmlNode *NodeFromPath( const std::string& sPath, char chSeparator = '.') const {return NodeFromPath(sPath.c_str(), chSeparator);}
virtual TiXmlElement *ElementFromPath( const std::string& sPath, char chSeparator = '.') const {return ElementFromPath(sPath.c_str(), chSeparator);}
#endif
//////////////////////////////////////////////////////////////////////////
const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children.
TiXmlNode* LastChild() { return lastChild; }
const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children.
TiXmlNode* LastChild( const char * value );
#ifdef TIXML_USE_STL
const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form.
TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form.
const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form.
TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form.
#endif
/** An alternate way to walk the children of a node.
One way to iterate over nodes is:
@verbatim
for( child = parent->FirstChild(); child; child = child->NextSibling() )
@endverbatim
IterateChildren does the same thing with the syntax:
@verbatim
child = 0;
while( child = parent->IterateChildren( child ) )
@endverbatim
IterateChildren takes the previous child as input and finds
the next one. If the previous child is null, it returns the
first. IterateChildren will return null when done.
*/
const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const;
TiXmlNode* IterateChildren( TiXmlNode* previous );
/// This flavor of IterateChildren searches for children with a particular 'value'
const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const;
TiXmlNode* IterateChildren( const char * value, TiXmlNode* previous );
#ifdef TIXML_USE_STL
const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
TiXmlNode* IterateChildren( const std::string& _value, TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
#endif
/** Add a new node related to this. Adds a child past the LastChild.
Returns a pointer to the new object or NULL if an error occured.
*/
TiXmlNode* InsertEndChild( const TiXmlNode& addThis );
/** Add a new node related to this. Adds a child past the LastChild.
NOTE: the node to be added is passed by pointer, and will be
henceforth owned (and deleted) by tinyXml. This method is efficient
and avoids an extra copy, but should be used with care as it
uses a different memory model than the other insert functions.
@sa InsertEndChild
*/
TiXmlNode* LinkEndChild( TiXmlNode* addThis );
/** Add a new node related to this. Adds a child before the specified child.
Returns a pointer to the new object or NULL if an error occured.
*/
TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis );
/** Add a new node related to this. Adds a child after the specified child.
Returns a pointer to the new object or NULL if an error occured.
*/
TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis );
/** Replace a child of this node.
Returns a pointer to the new object or NULL if an error occured.
*/
TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis );
/// Delete a child of this node.
bool RemoveChild( TiXmlNode* removeThis );
/// Navigate to a sibling node.
const TiXmlNode* PreviousSibling() const { return prev; }
TiXmlNode* PreviousSibling() { return prev; }
/// Navigate to a sibling node.
const TiXmlNode* PreviousSibling( const char * ) const;
TiXmlNode* PreviousSibling( const char * );
#ifdef TIXML_USE_STL
const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form.
TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form.
#endif
/// Navigate to a sibling node.
const TiXmlNode* NextSibling() const { return next; }
TiXmlNode* NextSibling() { return next; }
/// Navigate to a sibling node with the given 'value'.
const TiXmlNode* NextSibling( const char * ) const;
TiXmlNode* NextSibling( const char * );
/** Convenience function to get through elements.
Calls NextSibling and ToElement. Will skip all non-Element
nodes. Returns 0 if there is not another element.
*/
const TiXmlElement* NextSiblingElement() const;
TiXmlElement* NextSiblingElement();
/** Convenience function to get through elements.
Calls NextSibling and ToElement. Will skip all non-Element
nodes. Returns 0 if there is not another element.
*/
const TiXmlElement* NextSiblingElement( const char * ) const;
TiXmlElement* NextSiblingElement( const char * );
#ifdef TIXML_USE_STL
const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
#endif
/// Convenience function to get through elements.
const TiXmlElement* FirstChildElement() const;
TiXmlElement* FirstChildElement();
/// Convenience function to get through elements.
const TiXmlElement* FirstChildElement( const char * value ) const;
TiXmlElement* FirstChildElement( const char * value );
#ifdef TIXML_USE_STL
const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
#endif
/** Query the type (as an enumerated value, above) of this node.
The possible types are: DOCUMENT, ELEMENT, COMMENT,
UNKNOWN, TEXT, and DECLARATION.
*/
virtual int Type() const { return type; }
/** Return a pointer to the Document this node lives in.
Returns null if not in a document.
*/
const TiXmlDocument* GetDocument() const;
TiXmlDocument* GetDocument();
/// Returns true if this node has no children.
bool NoChildren() const { return !firstChild; }
const TiXmlDocument* ToDocument() const { return ( this && type == DOCUMENT ) ? (const TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
const TiXmlElement* ToElement() const { return ( this && type == ELEMENT ) ? (const TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
const TiXmlComment* ToComment() const { return ( this && type == COMMENT ) ? (const TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
const TiXmlUnknown* ToUnknown() const { return ( this && type == UNKNOWN ) ? (const TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
const TiXmlText* ToText() const { return ( this && type == TEXT ) ? (const TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
const TiXmlDeclaration* ToDeclaration() const { return ( this && type == DECLARATION ) ? (const TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
TiXmlDocument* ToDocument() { return ( this && type == DOCUMENT ) ? (TiXmlDocument*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
TiXmlElement* ToElement() { return ( this && type == ELEMENT ) ? (TiXmlElement*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
TiXmlComment* ToComment() { return ( this && type == COMMENT ) ? (TiXmlComment*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
TiXmlUnknown* ToUnknown() { return ( this && type == UNKNOWN ) ? (TiXmlUnknown*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
TiXmlText* ToText() { return ( this && type == TEXT ) ? (TiXmlText*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
TiXmlDeclaration* ToDeclaration() { return ( this && type == DECLARATION ) ? (TiXmlDeclaration*) this : 0; } ///< Cast to a more defined type. Will return null not of the requested type.
/** Create an exact duplicate of this node and return it. The memory must be deleted
by the caller.
*/
virtual TiXmlNode* Clone() const = 0;
protected:
TiXmlNode( NodeType _type );
// Copy to the allocated object. Shared functionality between Clone, Copy constructor,
// and the assignment operator.
void CopyTo( TiXmlNode* target ) const;
#ifdef TIXML_USE_STL
// The real work of the input operator.
virtual void StreamIn( TIXML_ISTREAM* in, TIXML_STRING* tag ) = 0;
#endif
// Figure out what is at *p, and parse it. Returns null if it is not an xml node.
TiXmlNode* Identify( const char* start, TiXmlEncoding encoding );
// Internal Value function returning a TIXML_STRING
const TIXML_STRING& SValue() const { return value ; }
TiXmlNode* parent;
NodeType type;
TiXmlNode* firstChild;
TiXmlNode* lastChild;
TIXML_STRING value;
TiXmlNode* prev;
TiXmlNode* next;
private:
TiXmlNode( const TiXmlNode& ); // not implemented.
void operator=( const TiXmlNode& base ); // not allowed.
};
/** An attribute is a name-value pair. Elements have an arbitrary
number of attributes, each with a unique name.
@note The attributes are not TiXmlNodes, since they are not
part of the tinyXML document object model. There are other
suggested ways to look at this problem.
*/
class TiXmlAttribute : public TiXmlBase
{
friend class TiXmlAttributeSet;
public:
/// Construct an empty attribute.
TiXmlAttribute() : TiXmlBase()
{
document = 0;
prev = next = 0;
}
#ifdef TIXML_USE_STL
/// std::string constructor.
TiXmlAttribute( const std::string& _name, const std::string& _value )
{
name = _name;
value = _value;
document = 0;
prev = next = 0;
}
#endif
/// Construct an attribute with a name and value.
TiXmlAttribute( const char * _name, const char * _value )
{
name = _name;
value = _value;
document = 0;
prev = next = 0;
}
const char* Name() const { return name.c_str (); } ///< Return the name of this attribute.
const char* Value() const { return value.c_str (); } ///< Return the value of this attribute.
const int IntValue() const; ///< Return the value of this attribute, converted to an integer.
const double DoubleValue() const; ///< Return the value of this attribute, converted to a double.
/** QueryIntValue examines the value string. It is an alternative to the
IntValue() method with richer error checking.
If the value is an integer, it is stored in 'value' and
the call returns TIXML_SUCCESS. If it is not
an integer, it returns TIXML_WRONG_TYPE.
A specialized but useful call. Note that for success it returns 0,
which is the opposite of almost all other TinyXml calls.
*/
int QueryIntValue( int* value ) const;
/// QueryDoubleValue examines the value string. See QueryIntValue().
int QueryDoubleValue( double* value ) const;
void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute.
void SetValue( const char* _value ) { value = _value; } ///< Set the value.
void SetIntValue( int value ); ///< Set the value from an integer.
void SetDoubleValue( double value ); ///< Set the value from a double.
#ifdef TIXML_USE_STL
/// STL std::string form.
void SetName( const std::string& _name )
{
StringToBuffer buf( _name );
SetName ( buf.buffer ? buf.buffer : "error" );
}
/// STL std::string form.
void SetValue( const std::string& _value )
{
StringToBuffer buf( _value );
SetValue( buf.buffer ? buf.buffer : "error" );
}
#endif
/// Get the next sibling attribute in the DOM. Returns null at end.
const TiXmlAttribute* Next() const;
TiXmlAttribute* Next();
/// Get the previous sibling attribute in the DOM. Returns null at beginning.
const TiXmlAttribute* Previous() const;
TiXmlAttribute* Previous();
bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; }
bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; }
bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; }
/* Attribute parsing starts: first letter of the name
returns: the next char after the value end quote
*/
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
// Prints this Attribute to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
virtual void StreamOut( TIXML_OSTREAM * out ) const;
// [internal use]
// Set the document pointer so the attribute can report errors.
void SetDocument( TiXmlDocument* doc ) { document = doc; }
private:
TiXmlAttribute( const TiXmlAttribute& ); // not implemented.
void operator=( const TiXmlAttribute& base ); // not allowed.
TiXmlDocument* document; // A pointer back to a document, for error reporting.
TIXML_STRING name;
TIXML_STRING value;
TiXmlAttribute* prev;
TiXmlAttribute* next;
};
/* A class used to manage a group of attributes.
It is only used internally, both by the ELEMENT and the DECLARATION.
The set can be changed transparent to the Element and Declaration
classes that use it, but NOT transparent to the Attribute
which has to implement a next() and previous() method. Which makes
it a bit problematic and prevents the use of STL.
This version is implemented with circular lists because:
- I like circular lists
- it demonstrates some independence from the (typical) doubly linked list.
*/
class TiXmlAttributeSet
{
public:
TiXmlAttributeSet();
~TiXmlAttributeSet();
void Add( TiXmlAttribute* attribute );
void Remove( TiXmlAttribute* attribute );
const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
const TiXmlAttribute* Find( const char * name ) const;
TiXmlAttribute* Find( const char * name );
private:
//*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element),
//*ME: this class must be also use a hidden/disabled copy-constructor !!!
TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed
void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute)
TiXmlAttribute sentinel;
};
/** The element is a container class. It has a value, the element name,
and can contain other elements, text, comments, and unknowns.
Elements also contain an arbitrary number of attributes.
*/
class TiXmlElement : public TiXmlNode
{
public:
/// Construct an element.
TiXmlElement (const char * in_value);
#ifdef TIXML_USE_STL
/// std::string constructor.
TiXmlElement( const std::string& _value );
#endif
TiXmlElement( const TiXmlElement& );
void operator=( const TiXmlElement& base );
virtual ~TiXmlElement();
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none exists.
*/
const char* Attribute( const char* name ) const;
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none exists.
If the attribute exists and can be converted to an integer,
the integer value will be put in the return 'i', if 'i'
is non-null.
*/
const char* Attribute( const char* name, int* i ) const;
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none exists.
If the attribute exists and can be converted to an double,
the double value will be put in the return 'd', if 'd'
is non-null.
*/
const char* Attribute( const char* name, double* d ) const;
/** QueryIntAttribute examines the attribute - it is an alternative to the
Attribute() method with richer error checking.
If the attribute is an integer, it is stored in 'value' and
the call returns TIXML_SUCCESS. If it is not
an integer, it returns TIXML_WRONG_TYPE. If the attribute
does not exist, then TIXML_NO_ATTRIBUTE is returned.
*/
int QueryIntAttribute( const char* name, int* value ) const;
/// QueryDoubleAttribute examines the attribute - see QueryIntAttribute().
int QueryDoubleAttribute( const char* name, double* value ) const;
/// QueryFloatAttribute examines the attribute - see QueryIntAttribute().
int QueryDoubleAttribute( const char* name, float* value ) const {
double d;
int result = QueryDoubleAttribute( name, &d );
*value = (float)d;
return result;
}
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
*/
void SetAttribute( const char* name, const char * value );
#ifdef TIXML_USE_STL
const char* Attribute( const std::string& name ) const { return Attribute( name.c_str() ); }
const char* Attribute( const std::string& name, int* i ) const { return Attribute( name.c_str(), i ); }
const char* Attribute( const std::string& name, double* d ) const { return Attribute( name.c_str(), d ); }
int QueryIntAttribute( const std::string& name, int* value ) const { return QueryIntAttribute( name.c_str(), value ); }
int QueryDoubleAttribute( const std::string& name, double* value ) const { return QueryDoubleAttribute( name.c_str(), value ); }
/// STL std::string form.
void SetAttribute( const std::string& name, const std::string& _value )
{
StringToBuffer n( name );
StringToBuffer v( _value );
if ( n.buffer && v.buffer )
SetAttribute (n.buffer, v.buffer );
}
///< STL std::string form.
void SetAttribute( const std::string& name, int _value )
{
StringToBuffer n( name );
if ( n.buffer )
SetAttribute (n.buffer, _value);
}
#endif
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
*/
void SetAttribute( const char * name, int value );
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
*/
void SetDoubleAttribute( const char * name, double value );
/** Deletes an attribute with the given name.
*/
void RemoveAttribute( const char * name );
#ifdef TIXML_USE_STL
void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form.
#endif
const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element.
TiXmlAttribute* FirstAttribute() { return attributeSet.First(); }
const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element.
TiXmlAttribute* LastAttribute() { return attributeSet.Last(); }
/// Creates a new Element and returns it - the returned element is a copy.
virtual TiXmlNode* Clone() const;
// Print the Element to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
/* Attribtue parsing starts: next char past '<'
returns: next char past '>'
*/
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
protected:
void CopyTo( TiXmlElement* target ) const;
void ClearThis(); // like clear, but initializes 'this' object as well
// Used to be public [internal use]
#ifdef TIXML_USE_STL
virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
#endif
virtual void StreamOut( TIXML_OSTREAM * out ) const;
/* [internal use]
Reads the "value" of the element -- another element, or text.
This should terminate with the current end tag.
*/
const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding );
private:
TiXmlAttributeSet attributeSet;
};
/** An XML comment.
*/
class TiXmlComment : public TiXmlNode
{
public:
/// Constructs an empty comment.
TiXmlComment() : TiXmlNode( TiXmlNode::COMMENT ) {}
TiXmlComment( const TiXmlComment& );
void operator=( const TiXmlComment& base );
virtual ~TiXmlComment() {}
/// Returns a copy of this Comment.
virtual TiXmlNode* Clone() const;
/// Write this Comment to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
/* Attribtue parsing starts: at the ! of the !--
returns: next char past '>'
*/
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
protected:
void CopyTo( TiXmlComment* target ) const;
// used to be public
#ifdef TIXML_USE_STL
virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
#endif
virtual void StreamOut( TIXML_OSTREAM * out ) const;
private:
};
/** XML text. Contained in an element.
*/
class TiXmlText : public TiXmlNode
{
friend class TiXmlElement;
public:
/// Constructor.
TiXmlText (const char * initValue) : TiXmlNode (TiXmlNode::TEXT)
{
SetValue( initValue );
}
virtual ~TiXmlText() {}
#ifdef TIXML_USE_STL
/// Constructor.
TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TEXT)
{
SetValue( initValue );
}
#endif
TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TEXT ) { copy.CopyTo( this ); }
void operator=( const TiXmlText& base ) { base.CopyTo( this ); }
/// Write this text object to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
protected :
/// [internal use] Creates a new Element and returns it.
virtual TiXmlNode* Clone() const;
void CopyTo( TiXmlText* target ) const;
virtual void StreamOut ( TIXML_OSTREAM * out ) const;
bool Blank() const; // returns true if all white space and new lines
// [internal use]
#ifdef TIXML_USE_STL
virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
#endif
private:
};
/** In correct XML the declaration is the first entry in the file.
@verbatim
<?xml version="1.0" standalone="yes"?>
@endverbatim
TinyXml will happily read or write files without a declaration,
however. There are 3 possible attributes to the declaration:
version, encoding, and standalone.
Note: In this version of the code, the attributes are
handled as special cases, not generic attributes, simply
because there can only be at most 3 and they are always the same.
*/
class TiXmlDeclaration : public TiXmlNode
{
public:
/// Construct an empty declaration.
TiXmlDeclaration() : TiXmlNode( TiXmlNode::DECLARATION ) {}
#ifdef TIXML_USE_STL
/// Constructor.
TiXmlDeclaration( const std::string& _version,
const std::string& _encoding,
const std::string& _standalone );
#endif
/// Construct.
TiXmlDeclaration( const char* _version,
const char* _encoding,
const char* _standalone );
TiXmlDeclaration( const TiXmlDeclaration& copy );
void operator=( const TiXmlDeclaration& copy );
virtual ~TiXmlDeclaration() {}
/// Version. Will return an empty string if none was found.
const char *Version() const { return version.c_str (); }
/// Encoding. Will return an empty string if none was found.
const char *Encoding() const { return encoding.c_str (); }
/// Is this a standalone document?
const char *Standalone() const { return standalone.c_str (); }
/// Creates a copy of this Declaration and returns it.
virtual TiXmlNode* Clone() const;
/// Print this declaration to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
protected:
void CopyTo( TiXmlDeclaration* target ) const;
// used to be public
#ifdef TIXML_USE_STL
virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
#endif
virtual void StreamOut ( TIXML_OSTREAM * out) const;
private:
TIXML_STRING version;
TIXML_STRING encoding;
TIXML_STRING standalone;
};
/** Any tag that tinyXml doesn't recognize is saved as an
unknown. It is a tag of text, but should not be modified.
It will be written back to the XML, unchanged, when the file
is saved.
DTD tags get thrown into TiXmlUnknowns.
*/
class TiXmlUnknown : public TiXmlNode
{
public:
TiXmlUnknown() : TiXmlNode( TiXmlNode::UNKNOWN ) {}
virtual ~TiXmlUnknown() {}
TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::UNKNOWN ) { copy.CopyTo( this ); }
void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); }
/// Creates a copy of this Unknown and returns it.
virtual TiXmlNode* Clone() const;
/// Print this Unknown to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
protected:
void CopyTo( TiXmlUnknown* target ) const;
#ifdef TIXML_USE_STL
virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
#endif
virtual void StreamOut ( TIXML_OSTREAM * out ) const;
private:
};
/** Always the top level node. A document binds together all the
XML pieces. It can be saved, loaded, and printed to the screen.
The 'value' of a document node is the xml file name.
*/
class TiXmlDocument : public TiXmlNode
{
public:
/// Create an empty document, that has no name.
TiXmlDocument();
/// Create a document with a name. The name of the document is also the filename of the xml.
TiXmlDocument( const char * documentName );
#ifdef TIXML_USE_STL
/// Constructor.
TiXmlDocument( const std::string& documentName );
#endif
TiXmlDocument( const TiXmlDocument& copy );
void operator=( const TiXmlDocument& copy );
virtual ~TiXmlDocument() {}
/** Load a file using the current document value.
Returns true if successful. Will delete any existing
document data before loading.
*/
bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the current document value. Returns true if successful.
bool SaveFile() const;
/// Load a file using the given filename. Returns true if successful.
bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the given filename. Returns true if successful.
bool SaveFile( const char * filename ) const;
#ifdef TIXML_USE_STL
bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version.
{
StringToBuffer f( filename );
return ( f.buffer && LoadFile( f.buffer, encoding ));
}
bool SaveFile( const std::string& filename ) const ///< STL std::string version.
{
StringToBuffer f( filename );
return ( f.buffer && SaveFile( f.buffer ));
}
#endif
/** Parse the given null terminated block of xml data. Passing in an encoding to this
method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml
to use that encoding, regardless of what TinyXml might otherwise try to detect.
*/
virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/** Get the root element -- the only top level element -- of the document.
In well formed XML, there should only be one. TinyXml is tolerant of
multiple elements at the document level.
*/
const TiXmlElement* RootElement() const { return FirstChildElement(); }
TiXmlElement* RootElement() { return FirstChildElement(); }
/** If an error occurs, Error will be set to true. Also,
- The ErrorId() will contain the integer identifier of the error (not generally useful)
- The ErrorDesc() method will return the name of the error. (very useful)
- The ErrorRow() and ErrorCol() will return the location of the error (if known)
*/
bool Error() const { return error; }
/// Contains a textual (english) description of the error if one occurs.
const char * ErrorDesc() const { return errorDesc.c_str (); }
/** Generally, you probably want the error string ( ErrorDesc() ). But if you
prefer the ErrorId, this function will fetch it.
*/
const int ErrorId() const { return errorId; }
/** Returns the location (if known) of the error. The first column is column 1,
and the first row is row 1. A value of 0 means the row and column wasn't applicable
(memory errors, for example, have no row/column) or the parser lost the error. (An
error in the error reporting, in that case.)
@sa SetTabSize, Row, Column
*/
int ErrorRow() { return errorLocation.row+1; }
int ErrorCol() { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow()
/** By calling this method, with a tab size
greater than 0, the row and column of each node and attribute is stored
when the file is loaded. Very useful for tracking the DOM back in to
the source file.
The tab size is required for calculating the location of nodes. If not
set, the default of 4 is used. The tabsize is set per document. Setting
the tabsize to 0 disables row/column tracking.
Note that row and column tracking is not supported when using operator>>.
The tab size needs to be enabled before the parse or load. Correct usage:
@verbatim
TiXmlDocument doc;
doc.SetTabSize( 8 );
doc.Load( "myfile.xml" );
@endverbatim
@sa Row, Column
*/
void SetTabSize( int _tabsize ) { tabsize = _tabsize; }
int TabSize() const { return tabsize; }
/** If you have handled the error, it can be reset with this call. The error
state is automatically cleared if you Parse a new XML block.
*/
void ClearError() { error = false;
errorId = 0;
errorDesc = "";
errorLocation.row = errorLocation.col = 0;
//errorLocation.last = 0;
}
/** Dump the document to standard out. */
void Print() const { Print( stdout, 0 ); }
/// Print this Document to a FILE stream.
virtual void Print( FILE* cfile, int depth = 0 ) const;
// [internal use]
void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding );
protected :
virtual void StreamOut ( TIXML_OSTREAM * out) const;
// [internal use]
virtual TiXmlNode* Clone() const;
#ifdef TIXML_USE_STL
virtual void StreamIn( TIXML_ISTREAM * in, TIXML_STRING * tag );
#endif
private:
void CopyTo( TiXmlDocument* target ) const;
bool error;
int errorId;
TIXML_STRING errorDesc;
int tabsize;
TiXmlCursor errorLocation;
};
/**
A TiXmlHandle is a class that wraps a node pointer with null checks; this is
an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml
DOM structure. It is a separate utility class.
Take an example:
@verbatim
<Document>
<Element attributeA = "valueA">
<Child attributeB = "value1" />
<Child attributeB = "value2" />
</Element>
<Document>
@endverbatim
Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
easy to write a *lot* of code that looks like:
@verbatim
TiXmlElement* root = document.FirstChildElement( "Document" );
if ( root )
{
TiXmlElement* element = root->FirstChildElement( "Element" );
if ( element )
{
TiXmlElement* child = element->FirstChildElement( "Child" );
if ( child )
{
TiXmlElement* child2 = child->NextSiblingElement( "Child" );
if ( child2 )
{
// Finally do something useful.
@endverbatim
And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity
of such code. A TiXmlHandle checks for null pointers so it is perfectly safe
and correct to use:
@verbatim
TiXmlHandle docHandle( &document );
TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).Element();
if ( child2 )
{
// do something useful
@endverbatim
Which is MUCH more concise and useful.
It is also safe to copy handles - internally they are nothing more than node pointers.
@verbatim
TiXmlHandle handleCopy = handle;
@endverbatim
What they should not be used for is iteration:
@verbatim
int i=0;
while ( true )
{
TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).Element();
if ( !child )
break;
// do something
++i;
}
@endverbatim
It seems reasonable, but it is in fact two embedded while loops. The Child method is
a linear walk to find the element, so this code would iterate much more than it needs
to. Instead, prefer:
@verbatim
TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).Element();
for( child; child; child=child->NextSiblingElement() )
{
// do something
}
@endverbatim
*/
class TiXmlHandle
{
public:
/// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
TiXmlHandle( TiXmlNode* node ) { this->node = node; }
/// Copy constructor
TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; }
TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; }
/// Return a handle to the first child node.
TiXmlHandle FirstChild() const;
/// Return a handle to the first child node with the given name.
TiXmlHandle FirstChild( const char * value ) const;
/// Return a handle to the first child element.
TiXmlHandle FirstChildElement() const;
/// Return a handle to the first child element with the given name.
TiXmlHandle FirstChildElement( const char * value ) const;
/** Return a handle to the "index" child with the given name.
The first child is 0, the second 1, etc.
*/
TiXmlHandle Child( const char* value, int index ) const;
/** Return a handle to the "index" child.
The first child is 0, the second 1, etc.
*/
TiXmlHandle Child( int index ) const;
/** Return a handle to the "index" child element with the given name.
The first child element is 0, the second 1, etc. Note that only TiXmlElements
are indexed: other types are not counted.
*/
TiXmlHandle ChildElement( const char* value, int index ) const;
/** Return a handle to the "index" child element.
The first child element is 0, the second 1, etc. Note that only TiXmlElements
are indexed: other types are not counted.
*/
TiXmlHandle ChildElement( int index ) const;
#ifdef TIXML_USE_STL
TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); }
TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); }
TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); }
TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); }
#endif
/// Return the handle as a TiXmlNode. This may return null.
TiXmlNode* Node() const { return node; }
/// Return the handle as a TiXmlElement. This may return null.
TiXmlElement* Element() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); }
/// Return the handle as a TiXmlText. This may return null.
TiXmlText* Text() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); }
/// Return the handle as a TiXmlUnknown. This may return null;
TiXmlUnknown* Unknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); }
private:
TiXmlNode* node;
};
#ifdef _MSC_VER
#pragma warning( default : 4530 )
#pragma warning( default : 4786 )
#endif
#endif
|
[
"cxl@ntllib.org"
] |
cxl@ntllib.org
|
35eaf2cfd43f19409e8bbd5e0df9d689e9f85a2a
|
b59daf97e55cb798de6daeb31a6872d7586bd500
|
/src/nstd/execution/let_value.cpp
|
215b4e97edff38333a7762215723498ecf23ee65
|
[] |
no_license
|
kirkshoop/kuhllib
|
29a7348cd92ec67564a01bf5a4ebd3ce262a206d
|
8ac4f14d37db3d93e09dd2756a36bf7937c2faa2
|
refs/heads/main
| 2023-08-10T22:40:50.933000
| 2021-10-02T16:09:55
| 2021-10-02T16:09:55
| 412,868,756
| 2
| 0
| null | 2021-10-02T17:39:59
| 2021-10-02T17:39:58
| null |
UTF-8
|
C++
| false
| false
| 1,939
|
cpp
|
// nstd/execution/let_value.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// Copyright (C) 2021 Dietmar Kuehl http://www.dietmar-kuehl.de
//
// 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 "nstd/execution/let_value.hpp"
// ----------------------------------------------------------------------------
namespace nstd::execution {
int let_value_dummy = 0;
}
|
[
"dietmar.kuehl@me.com"
] |
dietmar.kuehl@me.com
|
cf2a06f81eb7045b31dd1a84c6a824280a9ec8aa
|
ea72aac3344f9474a0ba52c90ed35e24321b025d
|
/PathFinding/PathFinding/PathFinding.cpp
|
ee86e175b6437840cdb4904cdd62c789f72b837e
|
[] |
no_license
|
nlelouche/ia-2009
|
3bd7f1e42280001024eaf7433462b2949858b1c2
|
44c07567c3b74044e59313532b5829f3a3466a32
|
refs/heads/master
| 2020-05-17T02:21:02.137224
| 2009-03-31T01:12:44
| 2009-03-31T01:12:44
| 32,657,337
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,208
|
cpp
|
#include "PathFinding.h"
//--------------------------------------------------------------
PathFind::PathFind(int * _map[],int _rows,int _cols)
:
m_pkPath(NULL),
m_pkClosedNodes(NULL),
m_pkOpenNodes(NULL),
m_CurrentNode(NULL),
m_pkiPathIT(0),
m_pkOpenNodesIT(0),
m_pkClosedNodesIT(0)
{
// Copiamos el mapa pasado a un mapa fijo.
for (int i = 0; i > LARGO_MAPA; i++){
m_Map[i] = (int)_map[i];
}
/***/
}
//--------------------------------------------------------------
PathFind::~PathFind(){
/***/
}
//--------------------------------------------------------------
void PathFind::OpenNodes(Node * _node){
// m_pkOpenNodes.insert(_node); // Insertar nodo en la lista
/***/
}
//--------------------------------------------------------------
void PathFind::CloseNode(Node * _node){
/***/
}
//--------------------------------------------------------------
bool PathFind::ExistOpenNodes(){
/***/
return false;
}
//--------------------------------------------------------------
bool PathFind::IsExitNode(Node *_node){
/***/
return false;
}
//--------------------------------------------------------------
Node * PathFind::LessValueNode(){
/***/
return m_CurrentNode;
}
//--------------------------------------------------------------
list<Node*> PathFind::GenerarCamino(){
/***/
return m_pkPath;
}
//--------------------------------------------------------------
bool PathFind::IsEndingNode(Node * _node){
return false;
}
//--------------------------------------------------------------
void PathFind::CalculateMap(Node * _initialNode, Node * _endingNode){
// Copiamos Posicion X,Y de nodos inicial y destino.
//m_InitialPosition.Initial_X = _initial.Initial_X;
//m_InitialPosition.Initial_Y = _initial.Initial_Y;
//m_EndingPosition.Ending_X = _ending.Ending_X;
//m_EndingPosition.Ending_Y = _ending.Ending_Y;
OpenNodes(_initialNode);
while (ExistOpenNodes()){
m_CurrentNode = LessValueNode();
if (IsEndingNode(m_CurrentNode)){
//GenerarCamino();
}
else {
CloseNode(m_CurrentNode);
OpenNodes(m_CurrentNode);
}
}
}
//--------------------------------------------------------------
|
[
"calaverax@bb2752b8-1d7e-11de-9d52-39b120432c5d"
] |
calaverax@bb2752b8-1d7e-11de-9d52-39b120432c5d
|
c515a27617525d746053e17e71df5d783b320aab
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_repos_function_689_httpd-2.2.14.cpp
|
059621ec5096a4c8c5911be99ef7fb26a21a0b32
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 111
|
cpp
|
static int bio_filter_out_gets(BIO *bio, char *buf, int size)
{
/* this is never called */
return -1;
}
|
[
"993273596@qq.com"
] |
993273596@qq.com
|
6cab9ee2dad26a02dae02de57035067263fd4566
|
41279e0ed19e26cc0fcaafa229604d1094aed6a8
|
/include/networking/ServerStartException.hpp
|
f772241d67296e4ca574cea40b6c1e9c1c1c293f
|
[] |
no_license
|
ChuxiongMa/TextAdventure
|
20a180747414ede1a8b0e85869809f955b067b11
|
4f217106de6908909f17408c16df822ed9543284
|
refs/heads/master
| 2016-08-13T02:01:58.490646
| 2016-02-21T23:26:48
| 2016-02-21T23:26:48
| 52,233,748
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 395
|
hpp
|
#ifndef SERVER_START_EXCEPTION_H
#define SERVER_START_EXCEPTION_H
#include <exception>
#include <string>
using exception = std::exception;
using string = std::string;
namespace networking {
class ServerStartException : public exception {
string reason;
public:
ServerStartException();
ServerStartException(string);
virtual const char* what() const throw();
};
}
#endif
|
[
"cma68@sfu.ca"
] |
cma68@sfu.ca
|
0f9f0ead55a6b801d35b58d56eb57f2de6bcb09a
|
4c1d515719425db127ba5285b5be4f03af10d5a1
|
/URI-Judge/URI_1111.cpp
|
feb270b9bb96d652571c2d090fdfed91da0c8e01
|
[] |
no_license
|
matheusmtta/Competitive-Programming
|
26e51741332aed223b9231da33749940f5a1b977
|
e254b80090cc75bc213aad0a7957875842e90f1a
|
refs/heads/master
| 2023-04-28T18:08:51.417470
| 2023-04-24T21:09:00
| 2023-04-24T21:09:00
| 223,605,672
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,974
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define INF (int)0x3f3f3f3f
#define MP make_pair
#define PB push_back
typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
const int MAX = 15;
int n;
map <pair<int, int>, vector<int>> mtx;
map <pair<int, int>, int> dist;
map <pair<int, int>, int> visited;
//NORTH: ( 1, 0)
//SOUTH: (-1, 0)
//WEST: ( 0,-1)
//EAST: ( 0, 1)
map <int, pair <int, int>> mov;
int BFS(pair<int, int> source, int x1, int y1){
queue <pair<int,int>> walk;
dist[source] = 0;
visited[source] = 1;
walk.push(source);
while (!walk.empty()){
pair <int, int> v = walk.front();
walk.pop();
if (v.first == x1 && v.second == y1) return dist[v];
for (int i = 0; i < 4; i++){
pair <int, int> tmp;
tmp.first = v.first + mov[i].first;
tmp.second = v.second + mov[i].second;
if (mtx[v][i] == 1 && visited[tmp] == 0){
visited[tmp] = 1;
dist[tmp] = dist[v] + 1;
walk.push(tmp);
}
}
}
return -1;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
mov[0] = MP(0, 1);
mov[1] = MP(0, -1);
mov[2] = MP(-1, 0);
mov[3] = MP( 1, 0);
while (true){
cin >> n;
if (n == 0) return 0;
for (int y = n-1; y >= 0; y--){
for (int x = 0; x < n; x++){
//cout << "(" << x << " " << y << "): ";
for (int k = 0; k < 4; k++){
int z; cin >> z;
//cout << z << " ";
mtx[MP(x, y)].push_back(z);
visited[MP(x, y)] = 0;
dist[MP(x, y)] = -1;
}
//cout << endl;
}
}
int q; cin >> q;
while (q--){
int x0, y0, x1, y1;
cin >> x0 >> y0 >> x1 >> y1;
int ans = BFS(MP(x0, y0), x1, y1);
if(ans == -1) cout << "Impossible" << endl;
else cout << ans << endl;
for (int y = n-1; y >= 0; y--){
for (int x = 0; x < n; x++){
visited[MP(x, y)] = 0;
dist[MP(x, y)] = -1;
}
}
}
cout << endl;
mtx.clear();
}
return 0;
}
|
[
"matheusaquino199@gmail.com"
] |
matheusaquino199@gmail.com
|
2182894dc402d1ceaeb4508f476495cd88830f87
|
d4c720f93631097ee048940d669e0859e85eabcf
|
/third_party/webrtc_overrides/p2p/base/ice_connection.h
|
9082894cdcb42672cdeb2877b36f56a634df64bb
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause"
] |
permissive
|
otcshare/chromium-src
|
26a7372773b53b236784c51677c566dc0ad839e4
|
3b920d87437d9293f654de1f22d3ea341e7a8b55
|
refs/heads/webnn
| 2023-03-21T03:20:15.377034
| 2023-01-25T21:19:44
| 2023-01-25T21:19:44
| 209,262,645
| 18
| 21
|
BSD-3-Clause
| 2023-03-23T06:20:07
| 2019-09-18T08:52:07
| null |
UTF-8
|
C++
| false
| false
| 3,138
|
h
|
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_WEBRTC_OVERRIDES_P2P_BASE_ICE_CONNECTION_H_
#define THIRD_PARTY_WEBRTC_OVERRIDES_P2P_BASE_ICE_CONNECTION_H_
#include <string>
#include <vector>
#include "third_party/webrtc/api/array_view.h"
#include "third_party/webrtc/api/candidate.h"
#include "third_party/webrtc/p2p/base/connection.h"
#include "third_party/webrtc/rtc_base/system/rtc_export.h"
namespace blink {
// Represents an ICE connection comprising of a local candidate, a remote
// candidate, and some state information about the connection.
class RTC_EXPORT IceConnection {
public:
struct RttSample {
int64_t timestamp;
int value;
};
enum class WriteState {
STATE_WRITABLE = 0, // we have received ping responses recently
STATE_WRITE_UNRELIABLE = 1, // we have had a few ping failures
STATE_WRITE_INIT = 2, // we have yet to receive a ping response
STATE_WRITE_TIMEOUT = 3, // we have had a large number of ping failures
};
explicit IceConnection(const cricket::Connection* connection);
IceConnection(const IceConnection&) = default;
~IceConnection() = default;
// The connection ID.
uint32_t id() const { return id_; }
// The local candidate for this connection.
const cricket::Candidate& local_candidate() const { return local_candidate_; }
// The remote candidate for this connection.
const cricket::Candidate& remote_candidate() const {
return remote_candidate_;
}
// Whether the connection is in a connected state.
bool connected() const { return connected_; }
// Whether the connection is currently active for the transport.
bool selected() const { return selected_; }
// Write state of the connection.
WriteState write_state() const { return write_state_; }
// Last time we sent a ping to the other side.
int64_t last_ping_sent() const { return last_ping_sent_; }
// Last time we received a ping from the other side.
int64_t last_ping_received() const { return last_ping_received_; }
// Last time we received date from the other side.
int64_t last_data_received() const { return last_data_received_; }
// Last time we received a response to a ping from the other side.
int64_t last_ping_response_received() const {
return last_ping_response_received_;
}
// The number of pings sent.
int num_pings_sent() const { return num_pings_sent_; }
// Samples of round trip times.
const rtc::ArrayView<const RttSample> rtt_samples() const {
return rtt_samples_;
}
private:
uint32_t id_;
cricket::Candidate local_candidate_;
cricket::Candidate remote_candidate_;
// Connection state information.
bool connected_;
bool selected_;
WriteState write_state_;
int64_t last_ping_sent_;
int64_t last_ping_received_;
int64_t last_data_received_;
int64_t last_ping_response_received_;
int num_pings_sent_;
std::vector<RttSample> rtt_samples_;
};
} // namespace blink
#endif // THIRD_PARTY_WEBRTC_OVERRIDES_P2P_BASE_ICE_CONNECTION_H_
|
[
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] |
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
|
6292c448cb2d02c252c06d1c449d9574ed567697
|
81041c13fcb8d0d9cbd46b018d72c77dd0400429
|
/exception/cFileExce.h
|
10ea0614817ac583ca52e5e6cfdddcc7da511358
|
[] |
no_license
|
degawang/degawong
|
0c49feb10941ed915fa6cfe3677b85d3baf8fb36
|
64e20912fc3e8c4dae58a14b097cc8ec1b052365
|
refs/heads/master
| 2021-09-17T19:32:48.017411
| 2018-07-04T14:33:05
| 2018-07-04T14:33:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 575
|
h
|
#pragma once
#include "cDegaException.h"
namespace degawong {
class cFileExce :
public cDegaException {
public:
cFileExce();
cFileExce(std::string _fileReason)
: exceReason(_fileReason) {};
~cFileExce();
public:
friend std::istream& operator >> (std::istream& is, cFileExce &exce) {
is >> exce.exceReason;
return is;
};
friend std::ostream& operator << (std::ostream& os, const cFileExce &exce) {
os << exce.what() << std::endl;
return os;
};
public:
inline
std::string what() const {
return exceReason;
}
private:
std::string exceReason;
};
}
|
[
"degawong@hotmail.com"
] |
degawong@hotmail.com
|
b4bacf770bbde397468dac64964b28fbbf6a94f4
|
b8499de1a793500b47f36e85828f997e3954e570
|
/v2_3/build/Android/Preview/app/src/main/include/Fuse.NodeGroupBase.h
|
eb078dfd79ac290e0c6d5d63a1ea4472d3bb8d97
|
[] |
no_license
|
shrivaibhav/boysinbits
|
37ccb707340a14f31bd57ea92b7b7ddc4859e989
|
04bb707691587b253abaac064317715adb9a9fe5
|
refs/heads/master
| 2020-03-24T05:22:21.998732
| 2018-07-26T20:06:00
| 2018-07-26T20:06:00
| 142,485,250
| 0
| 0
| null | 2018-07-26T20:03:22
| 2018-07-26T19:30:12
|
C++
|
UTF-8
|
C++
| false
| false
| 3,019
|
h
|
// This file was generated based on 'C:/Users/hp laptop/AppData/Local/Fusetools/Packages/Fuse.Nodes/1.9.0/NodeGroup.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Behavior.h>
#include <Fuse.Binding.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ISourceLocation.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.TemplateSourceImpl.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
namespace g{namespace Fuse{struct Node;}}
namespace g{namespace Fuse{struct NodeGroupBase;}}
namespace g{namespace Uno{namespace Collections{struct RootableList;}}}
namespace g{namespace Uno{namespace UX{struct Resource;}}}
namespace g{namespace Uno{namespace UX{struct Template;}}}
namespace g{
namespace Fuse{
// public abstract class NodeGroupBase :16
// {
::g::Fuse::Node_type* NodeGroupBase_typeof();
void NodeGroupBase__ctor_3_fn(NodeGroupBase* __this, int32_t* flags);
void NodeGroupBase__AddContent_fn(NodeGroupBase* __this);
void NodeGroupBase__FindTemplate_fn(NodeGroupBase* __this, uString* key, ::g::Uno::UX::Template** __retval);
void NodeGroupBase__get_NodeCount_fn(NodeGroupBase* __this, int32_t* __retval);
void NodeGroupBase__get_Nodes_fn(NodeGroupBase* __this, uObject** __retval);
void NodeGroupBase__OnNodeAdded_fn(NodeGroupBase* __this, ::g::Fuse::Node* n);
void NodeGroupBase__OnNodeRemoved_fn(NodeGroupBase* __this, ::g::Fuse::Node* n);
void NodeGroupBase__OnResourceAdded_fn(NodeGroupBase* __this, ::g::Uno::UX::Resource* r);
void NodeGroupBase__OnResourceRemoved_fn(NodeGroupBase* __this, ::g::Uno::UX::Resource* r);
void NodeGroupBase__OnRooted_fn(NodeGroupBase* __this);
void NodeGroupBase__OnUnrooted_fn(NodeGroupBase* __this);
void NodeGroupBase__RemoveContent_fn(NodeGroupBase* __this);
void NodeGroupBase__get_Resources_fn(NodeGroupBase* __this, uObject** __retval);
void NodeGroupBase__get_Templates_fn(NodeGroupBase* __this, uObject** __retval);
void NodeGroupBase__get_UseContent_fn(NodeGroupBase* __this, bool* __retval);
void NodeGroupBase__set_UseContent_fn(NodeGroupBase* __this, bool* value);
struct NodeGroupBase : ::g::Fuse::Behavior
{
uStrong< ::g::Uno::Collections::RootableList*> _nodes;
::g::Fuse::TemplateSourceImpl _templates;
bool _useTemplates;
bool _useContent;
uStrong< ::g::Uno::Collections::RootableList*> _resources;
bool _contentAdded;
uStrong<uArray*> _addedNodes;
void ctor_3(int32_t flags);
void AddContent();
::g::Uno::UX::Template* FindTemplate(uString* key);
int32_t NodeCount();
uObject* Nodes();
void OnNodeAdded(::g::Fuse::Node* n);
void OnNodeRemoved(::g::Fuse::Node* n);
void OnResourceAdded(::g::Uno::UX::Resource* r);
void OnResourceRemoved(::g::Uno::UX::Resource* r);
void RemoveContent();
uObject* Resources();
uObject* Templates();
bool UseContent();
void UseContent(bool value);
};
// }
}} // ::g::Fuse
|
[
"shubhamanandoist@gmail.com"
] |
shubhamanandoist@gmail.com
|
bc4a731ca349b014dc306381f35e48f211c6a2fa
|
af0ecafb5428bd556d49575da2a72f6f80d3d14b
|
/CodeJamCrawler/dataset/11_1078_45.cpp
|
020ee7d9a02bb81a8af136f96009f5cbecb77ce6
|
[] |
no_license
|
gbrlas/AVSP
|
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
|
e259090bf282694676b2568023745f9ffb6d73fd
|
refs/heads/master
| 2021-06-16T22:25:41.585830
| 2017-06-09T06:32:01
| 2017-06-09T06:32:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,416
|
cpp
|
//
//
package main
import (
"io/ioutil"
"strconv"
"strings"
"fmt"
"bufio"
"os"
"sort"
)
var out = "Case #%d: [%s]\n"
type comb []string
func (me *comb) combine(s1, s2 string) string {
tmp := []string{s1, s2}
tm := make([]string, 2)
sort.SortStrings(tmp)
for _, v := range *me {
tm = strings.Split(v, "", -1)[0:2]
sort.SortStrings(tm)
if strings.Join(tmp, "") == strings.Join(tm, "") {
//fmt.Println(tm, tmp)
return strings.Split(v, "", -1)[2]
}
}
return ""
}
func perm(str string) []string {
n := 0
for i := len(str) - 1; i > 0; i-- {
n += i
}
p := make([]string, n)
for i, k := 0, 0; k < n && i < len(str)-1; i++ {
for j := i + 1; j < len(str); j++ {
p[k] = str[i:i+1] + str[j:j+1]
k++
}
}
return p
}
type opp []string
func (me *opp) opposed(str string) bool {
tmp := strings.Split(str, "", -1)
tm := make([]string, 2)
sort.SortStrings(tmp)
for _, v := range *me {
tm = strings.Split(v, "", -1)
sort.SortStrings(tm)
if strings.Join(tmp, "") == strings.Join(tm, "") {
return true
}
}
return false
}
var opposed = &opp{}
var combinatns = &comb{}
func main() {
file, _ := os.Open("input.in")
input := bufio.NewReader(file)
str, _, _ := input.ReadLine()
cases, _ := strconv.Atoi(string(str))
ans := make([]string, cases)
i := 0
for str, _, err := input.ReadLine(); err == nil; {
line := strings.Fields(string(str))
c, _ := strconv.Atoi(line[0])
*combinatns = line[1 : c+1]
d, _ := strconv.Atoi(line[c+1])
*opposed = line[c+2 : c+2+d]
//n := line[c+2+d]
base := line[c+3+d]
ans[i] = process(base)
i++
str, _, err = input.ReadLine()
}
output(ans)
}
func process(base string) string {
set := ""
add := func(s string) {
set += s
}
clear := func() {
set = ""
}
combine := func() bool {
s1 := set[len(set)-2 : len(set)-1]
s2 := set[len(set)-1 : len(set)]
c := combinatns.combine(s1, s2)
if c != "" {
set = set[:len(set)-2]
add(c)
return true
}
return false
}
for i := 0; i < len(base); i++ {
add(base[i : i+1])
if len(set) < 2 {
continue
}
if combine() {
continue
}
for _, v := range perm(set) {
if opposed.opposed(v) {
clear()
break
}
}
}
return strings.Join(strings.Split(set, "", -1), ", ")
}
func output(ans []string) {
str := ""
for i, v := range ans {
str += fmt.Sprintf(out, i+1, v)
}
ioutil.WriteFile("output.out", []byte(str), 0666)
}
|
[
"nikola.mrzljak@fer.hr"
] |
nikola.mrzljak@fer.hr
|
a4c62877e6c1d20e71dc914be8a9177173f8443f
|
736c9e4877ccdecd96d233d67d4e395e5f735919
|
/pcc-gradient/sender/app/incast_client.cpp
|
5a2d09a50a20adc972a85dd2791ceb88b8fd155b
|
[
"GPL-3.0-only"
] |
permissive
|
5G-Measurement/PCC-Uspace
|
a35601692360290596fd9940ca11973c7ea0c23d
|
f89a3de579344585e38c926262bdb05964dd08b8
|
refs/heads/master
| 2023-01-24T00:18:35.610111
| 2020-11-22T03:53:43
| 2020-11-22T03:53:43
| 313,701,713
| 0
| 0
|
BSD-3-Clause
| 2020-11-17T18:51:29
| 2020-11-17T18:02:30
| null |
UTF-8
|
C++
| false
| false
| 5,192
|
cpp
|
#ifndef WIN32
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <netdb.h>
#include <time.h>
#include <math.h>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#include <wspiapi.h>
#endif
#include <iostream>
#include <udt.h>
#include "cc_incast.h"
#include <sys/time.h>
using namespace std;
int windowsize;
char argv1[50],argv2[50];
int Interval_avg;
int tt;
int trap;
int safe;
#ifndef WIN32
void* monitor(void*);
void* worker(void*);
#else
DWORD WINAPI monitor(LPVOID);
#endif
int count=0;
double avg_fluc;
struct timeval current;
int start_s, start_us;
int data_length;
int main(int argc, char* argv[])
{
//sendinginterval=0;
start_s = atoi(argv[4]);
start_us = atoi(argv[5]);
pthread_t t;
tt=0;
Interval_avg=50;
avg_fluc=0.25;
strcpy(argv1,argv[1]);
strcpy(argv2,argv[2]);
data_length = atoi(argv[3]);
// use this function to initialize the UDT library
int i=0;
while(i<1){
i++;
pthread_create(&t, NULL, worker, NULL);
pthread_join(t,NULL);
}
return 1;
}
void * worker(void * s)
{
cout<<endl;
srand((unsigned)time(NULL));
windowsize=data_length;//rand()%900+100;
UDT::startup();
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<BBCC>, sizeof(CCCFactory<BBCC>));
//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));
// 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(argv1, argv2, &hints, &peer))
{
cout << "incorrect server/peer address. " << argv1 << ":" << argv2 << 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
BBCC* cchandle = NULL;
int temp;
UDT::getsockopt(client, 0, UDT_CC, &cchandle, &temp);
// if (NULL != cchandle)
// cout<<"notNULL!"<<endl;
// cchandle->setRate(5);
//cchandle->m_dCWndSize=windowsize+100;
//cout<<cchandle->m_dCWndSize<<endl;
//cout<<"k"<<cchandle->m_dCWndSize<<endl;
int usize = 1456;
int size=0;
size=usize*windowsize;
//cout<<"size"<<size<<endl;
char* data = new char[size];
#ifndef WIN32
// count++;
//cout<<count<<endl;
#else
CreateThread(NULL, 0, monitor, &client, 0, NULL);
#endif
int ssize = 0;
int ss=0;
do {
gettimeofday(¤t, NULL);
if (current.tv_sec>=start_s+2 && current.tv_usec>=start_us)
break;
} while(1);
// cout<<start.tv_sec<<"."<<start.tv_usec<<endl;
cout<<"Start time "<<current.tv_sec<<"."<<current.tv_usec<<endl;
if (UDT::ERROR == (ss = UDT::send(client, data + ssize, size - ssize, 0)))
{
cout << "send:" << UDT::getlasterror().getErrorMessage() << endl;
//break;
}
//cout<<ss<<endl;
sleep(5);
//cout<<cchandle->count2<<endl;
//cout<<cchandle->m_dCWndSize<<endl;
//cout<<"YES!!"<<cchandle->haslost<<endl;
/*if(cchandle->haslost)
{cchandle->haslost=0; windowsize-=4;}
if(cchandle->hasloss)
{cchandle->hasloss=0;
windowsize-=7;
}
windowsize+=2;
if(ss==size)
// cout<<"FINISH!"<<endl;
*/
//cout<<windowsize<<endl;
//sleep(5);
delete [] data;
UDT::close(client);
// use this function to release the UDT library
UDT::cleanup();
//cout<<"TIME,"<<time<<endl;
sleep(3);
return NULL;
}
#ifndef WIN32
void* monitor(void* s)
#else
DWORD WINAPI monitor(LPVOID s)
#endif
{
UDTSOCKET u = *(UDTSOCKET*)s;
UDT::TRACEINFO perf;
cout << "SendRate(Mb/s)\tRTT(ms)\tCWnd\tPktSndPeriod(us)\tRecvACK\tLoss" << endl;
while (true)
{
#ifndef WIN32
sleep(100);
#else
Sleep(100);
#endif
if (UDT::ERROR == UDT::perfmon(u, &perf))
{
cout << "perfmon: " << UDT::getlasterror().getErrorMessage() << endl;
break;
}
cout
<< perf.pktCongestionWindow
<< endl;
}
#ifndef WIN32
return NULL;
#else
return 0;
#endif
}
|
[
"njay2@illinois.edu"
] |
njay2@illinois.edu
|
bee932171576f57bee93e221b6d8fc1408868561
|
964e0c2adfe540f6412472370b2ccc51f938e207
|
/3.5일차/Sprite.cpp
|
70fbbf76802b2914a30994b5b226bd90b3ef0cd3
|
[] |
no_license
|
andy5840/sosujungong
|
c804ed49792f77f0755b4231c96e048d50b4d1c1
|
d6002d94fca70d368ad403c091ecc06d7190cf0c
|
refs/heads/master
| 2022-11-30T12:38:49.348793
| 2020-08-19T06:50:06
| 2020-08-19T06:50:06
| 286,414,711
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 979
|
cpp
|
#include "stdafx.h"
#include "Sprite.h"
Sprite::Sprite(char* path)
{
texture = textureManager->LoadTextureFromFile(path);
D3DSURFACE_DESC desc;
texture->GetLevelDesc(0, &desc);
width = desc.Width;
height = desc.Height;
visibleRect.left = 0;
visibleRect.right = 0;
visibleRect.top = 0;
visibleRect.bottom = 0;
rect = visibleRect;
color = D3DCOLOR_ARGB(255, 255, 255, 255);
}
Sprite::~Sprite()
{
}
void Sprite::Render()
{
Object::Render();
pd3dSprite->SetTransform(&mat);
pd3dSprite->Draw(texture, &visibleRect, NULL, NULL, color);
}
int Sprite::getWidth()
{
return width;
}
int Sprite::getHeight()
{
return height;
}
D3DCOLOR Sprite::getColor()
{
return color;
}
void Sprite::setColor(D3DCOLOR color)
{
this->color = color;
}
void Sprite::setCenter(int width, int height, Sprite* sprite)
{
rect.left = -width / 2;
rect.top = -height / 2;
rect.right = width / 2;
rect.bottom = height / 2;
sprite->pos = D3DXVECTOR2(-width / 2, -height / 2);
}
|
[
"kalfka12345@gmail.com"
] |
kalfka12345@gmail.com
|
96dce74cc57071dcc14ad9eeb385db0bea59a9d9
|
8e514382d5844d0208ebba778eab28b0f76a89cd
|
/src/interface/execution_context.hpp
|
8c3d60916b4d3bbf3deaf42dcc1cfc7470a6bb0f
|
[
"MIT"
] |
permissive
|
KhalilBellakrid/ledger-test-library
|
580255d517f1ab7d4733614339e419b6d081b236
|
250c9fc992f498360f6396d4ed3ea1bb7637d863
|
refs/heads/master
| 2021-05-02T12:58:22.810296
| 2018-02-16T17:43:14
| 2018-02-16T17:43:14
| 120,751,274
| 0
| 3
| null | 2018-02-16T10:29:43
| 2018-02-08T11:12:46
|
C++
|
UTF-8
|
C++
| false
| false
| 453
|
hpp
|
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from async.djinni
#pragma once
#include <cstdint>
#include <memory>
namespace ledgerapp_gen {
class Runnable;
class ExecutionContext {
public:
virtual ~ExecutionContext() {}
virtual void execute(const std::shared_ptr<Runnable> & runnable) = 0;
virtual void delay(const std::shared_ptr<Runnable> & runnable, int64_t millis) = 0;
};
} // namespace ledgerapp_gen
|
[
"khalil.bellakrid@ledger.fr"
] |
khalil.bellakrid@ledger.fr
|
ae992b6a1b0f1da69bc52e67b368ab40419c78e1
|
66c869c7e34c1557d17ba7185549ea49f8955b64
|
/core/include/ample/ActionsFactory.h
|
a94ae78d95d9b62122cf318f9da553b627fdb224
|
[
"MIT"
] |
permissive
|
blizmax/ample
|
f091a00b9a69cac510be12d99f6f62de6989ec65
|
71336c2fb69748b8c2f27a6810e7cc047cbab359
|
refs/heads/master
| 2022-09-19T14:53:02.046860
| 2020-05-27T14:58:45
| 2020-05-27T14:58:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,341
|
h
|
#pragma once
#include "Factory.h"
#include "GraphicalRotateAction.h"
#include "GraphicalTranslateAction.h"
#include "FollowObjectAction.h"
#include "CameraTranslateAction.h"
#include "PhysicalApplyForceAction.h"
namespace ample::game::factory
{
static ample::utils::Factory<Action, const std::string &> ActionsFactory;
namespace registers
{
static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::GraphicalTranslateAction> GraphicalTranslateActionRegister("GraphicalTranslateAction");
static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::GraphicalRotateAction> GraphicalRotateActionRegister("GraphicalRotateAction");
static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::PhysicalApplyForceAction> PhysicalApplyForceActionRegister("PhysicalApplyForceAction");
static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::FollowObjectAction> FollowObjectActionActionRegister("FollowObjectAction");
static ample::utils::Factory<Action, const std::string &>::Register<ample::game::stateMachine::actions::CameraTranslateAction> CameraTranslateActionActionRegister("CameraTranslateAction");
} // namespace registers
} // namespace ample::game::factory
|
[
"glebmar2001@gmail.com"
] |
glebmar2001@gmail.com
|
f92333ed3b78cf40f333055a2bf75f75e6267738
|
36183993b144b873d4d53e7b0f0dfebedcb77730
|
/GameDevelopment/AI Game Programming Wisdom/SourceCode/02 Useful Techniques/07 Vykruta/ChildView.h
|
50ca275123e31322ffae7e7e2b7831e59de9a421
|
[] |
no_license
|
alecnunn/bookresources
|
b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0
|
4562f6430af5afffde790c42d0f3a33176d8003b
|
refs/heads/master
| 2020-04-12T22:28:54.275703
| 2018-12-22T09:00:31
| 2018-12-22T09:00:31
| 162,790,540
| 20
| 14
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,533
|
h
|
// ChildView.h : interface of the CChildView class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_CHILDVIEW_H__6F71D25A_D83E_11D5_BA44_000102368FA3__INCLUDED_)
#define AFX_CHILDVIEW_H__6F71D25A_D83E_11D5_BA44_000102368FA3__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <math.h>
class VECTOR2D;
void DrawLine(VECTOR2D vOrig, VECTOR2D vLine, int iColorType = 0);
void DrawLine2(VECTOR2D vOrig, VECTOR2D vLine, int iColorType = 0);
/////////////////////////////////////////////////////////////////////////////
// CChildView window
class CChildView : public CWnd
{
// Construction
public:
CChildView();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CChildView)
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CChildView();
// Generated message map functions
protected:
//{{AFX_MSG(CChildView)
afx_msg void OnPaint();
afx_msg void OnLButtonDown( UINT, CPoint );
afx_msg void OnRButtonDown( UINT, CPoint );
afx_msg void OnMouseMove( UINT nFlags, CPoint point );
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CHILDVIEW_H__6F71D25A_D83E_11D5_BA44_000102368FA3__INCLUDED_)
|
[
"alec.nunn@gmail.com"
] |
alec.nunn@gmail.com
|
310606d17fd13b0c2265e676adf73bbef6453ada
|
9bd74727033ae641c2d6c0f57fe1576fa7b05b37
|
/micrisoft/sharememory/Writer.cpp
|
e57c593eb5dda6385171cf4e5719b2105bc49b61
|
[] |
no_license
|
kamleshiitbhu/practice
|
eeff2ce478bfe176f4063f26dae020f6de9e5ab0
|
ec5c38d5e1f447811e578d619432f289266f61a3
|
refs/heads/master
| 2022-05-30T21:22:00.194423
| 2022-05-19T10:58:29
| 2022-05-19T10:58:29
| 124,258,203
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 529
|
cpp
|
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
using namespace std;
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *str = (char*) shmat(shmid,(void*)0,0);
cout<<"Write Data : ";
cin>>str;
printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt(str);
return 0;
}
|
[
"kamleshkumar356@gmail.com"
] |
kamleshkumar356@gmail.com
|
f5f1dd91f18f2933632b4ab953dc066b33533cc9
|
52e20f6ebe62bb24a0cc3c024b3ed8af0ef7bd57
|
/Geometry Objects/ConvexCylinder.cpp
|
028001981f1396ce100d1a547a3c7bc937c2d44b
|
[] |
no_license
|
matthiascy/crocus
|
a4bcc9b5683230f97c71fc8c8232e3cfd1e3029b
|
d0780e36d30c43a35d5bf9adc6b99892845cf95e
|
refs/heads/master
| 2023-01-14T01:15:29.091364
| 2019-12-09T17:59:51
| 2019-12-09T17:59:51
| 42,220,320
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,218
|
cpp
|
#include "ConvexCylinder.h"
#include <cmath>
const double ConvexCylinder::kEpsilon = 0.001;
ConvexCylinder::ConvexCylinder(void)
: GeometryObject(),
y0(-1.0),
y1(1.0),
radius(1.0),
inv_radius(1.0)
{}
ConvexCylinder::ConvexCylinder(const double bottom, const double top, const double r)
: GeometryObject(),
y0(bottom),
y1(top),
radius(r),
inv_radius(1.0 / radius)
{}
ConvexCylinder::ConvexCylinder(const ConvexCylinder& c)
: GeometryObject(c),
y0(c.y0),
y1(c.y1),
radius(c.radius),
inv_radius(c.inv_radius)
{}
ConvexCylinder& ConvexCylinder::operator= (const ConvexCylinder& rhs)
{
if (this == &rhs)
return (*this);
GeometryObject::operator= (rhs);
y0 = rhs.y0;
y1 = rhs.y1;
radius = rhs.radius;
inv_radius = rhs.inv_radius;
return (*this) ;
}
ConvexCylinder::~ConvexCylinder(void) {}
// The code reverses the normal when the ray hits the inside surface, allows both
// sides to be shaded, but completely messes up transparency.
bool ConvexCylinder::hit(const Ray& ray, double& tmin, ShadeRec& sr) const
{
double t;
double ox = ray.o.x;
double oy = ray.o.y;
double oz = ray.o.z;
double dx = ray.d.x;
double dy = ray.d.y;
double dz = ray.d.z;
double a = dx * dx + dz * dz;
double b = 2.0 * (ox * dx + oz * dz);
double c = ox * ox + oz * oz - radius * radius;
double disc = b * b - 4.0 * a * c ;
if (disc < 0.0)
return(false);
else
{
double e = sqrt(disc);
double denom = 2.0 * a;
t = (-b - e) / denom; // smaller root
if (t > kEpsilon)
{
double yhit = oy + t * dy;
if (yhit > y0 && yhit < y1)
{
tmin = t;
sr.normal = Normal((ox + t * dx) * inv_radius, 0.0, (oz + t * dz) * inv_radius);
sr.local_hit_point = ray.o + t * ray.d;
return (true);
}
}
t = (-b + e) / denom; // larger root
if (t > kEpsilon)
{
double yhit = oy + t * dy;
if (yhit > y0 && yhit < y1)
{
tmin = t;
sr.normal = Normal((ox + t * dx) * inv_radius, 0.0, (oz + t * dz) * inv_radius);
sr.local_hit_point = ray.o + t * ray.d;
return (true);
}
}
}
return (false);
}
bool ConvexCylinder::shadow_hit(const Ray &ray, float &tmin) const
{
double t;
double ox = ray.o.x;
double oy = ray.o.y;
double oz = ray.o.z;
double dx = ray.d.x;
double dy = ray.d.y;
double dz = ray.d.z;
double a = dx * dx + dz * dz;
double b = 2.0 * (ox * dx + oz * dz);
double c = ox * ox + oz * oz - radius * radius;
double disc = b * b - 4.0 * a * c ;
if (disc < 0.0)
return(false);
else
{
double e = sqrt(disc);
double denom = 2.0 * a;
t = (-b - e) / denom; // smaller root
if (t > kEpsilon)
{
double yhit = oy + t * dy;
if (yhit > y0 && yhit < y1)
{
tmin = t;
return (true);
}
}
t = (-b + e) / denom; // larger root
if (t > kEpsilon)
{
double yhit = oy + t * dy;
if (yhit > y0 && yhit < y1)
{
tmin = t;
return (true);
}
}
}
return (false);
}
|
[
"matthias_cy@outlook.com"
] |
matthias_cy@outlook.com
|
a02d8fd4ce849595ce3f7fd9eb24b6f0fa002e6a
|
dba9410a15ba312c5a37502b7c040de6c525974e
|
/bus-stops/bus-stops.cpp
|
77805271b9afc43423202845be05303fa15e7971
|
[] |
no_license
|
feco93/OSM-projects
|
587c53b061ada45035785baef2c2ae71c4e2e599
|
33815a894d64d56ccd1291427d288c8efcb69178
|
refs/heads/master
| 2020-04-25T14:36:03.003808
| 2015-04-12T08:21:35
| 2015-04-12T08:21:35
| 33,809,001
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,896
|
cpp
|
/*
* Sipos Ferenc, siposferenc93@gmail.com
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
*/
#include <map>
#include <list>
#include <string>
#include <iostream>
#include <cstddef>
#include <osmium/io/any_input.hpp>
#include <osmium/handler.hpp>
#include <osmium/visitor.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/index/map/sparse_table.hpp>
#include <osmium/index/map/vector.hpp>
#include <osmium/handler/node_locations_for_ways.hpp>
#include <osmium/geom/haversine.hpp>
class BusHandler:public osmium::handler::Handler
{
public:
osmium::index::map::VectorBasedSparseMap <osmium::unsigned_object_id_type,osmium::Location, std::vector > locations;
void relation (osmium::Relation & rel)
{
const char * bus = rel.tags ()["route"];
if (bus && (!strcmp (bus, "bus") /*|| !strcmp (bus, "trolleybus") || !strcmp(bus,"tram")*/) )
{
std::string bus_no;
if(rel.get_value_by_key("ref"))
{
bus_no=rel.get_value_by_key("ref");
}
else
{
bus_no=rel.get_value_by_key("name");
}
std::cout <<bus_no <<" BUS"<<'\n';
std::vector<std::vector<osmium::Location>> asd;
for(const osmium::Tag& info : rel.tags() )
{
std::cout <<info.key() <<": " <<info.value() <<'\t';
}
std::cout <<'\n';
int i=0;
for (const osmium::RelationMember& rm: rel.members())
{
if(rm.type() == osmium::item_type::node)
{
osmium::Location loc = locations.get(rm.positive_ref());
std::cout <<i <<"\tLon: " <<loc.lon() <<"\tLat: " <<loc.lat() <<'\n';
}
++i;
}
}
}
};
int main (int argc, char *argv[])
{
if (argc == 2)
{
osmium::io::File infile (argv[1]);
osmium::io::Reader reader (infile, osmium::osm_entity_bits::all);
BusHandler bus_handler;
osmium::handler::NodeLocationsForWays < osmium::index::map::VectorBasedSparseMap <osmium::unsigned_object_id_type, osmium::Location, std::vector > >
node_locations (bus_handler.locations);
osmium::apply (reader, node_locations, bus_handler);
reader.close ();
google::protobuf::ShutdownProtobufLibrary ();
}
else
{
std::cout << "Usage: " << argv[0] << "city.osm" << std::endl;
std::exit (1);
}
}
|
[
"siposferenc93@gmail.com"
] |
siposferenc93@gmail.com
|
01a7b31debe429bb783cef193cf4446270cee1fd
|
33035c05aad9bca0b0cefd67529bdd70399a9e04
|
/src/boost_geometry_io_svg_write_svg_multi.hpp
|
3c2086a333da0ec0f33bedd43d6b2a07a06ecaf5
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] |
permissive
|
elvisbugs/BoostForArduino
|
7e2427ded5fd030231918524f6a91554085a8e64
|
b8c912bf671868e2182aa703ed34076c59acf474
|
refs/heads/master
| 2023-03-25T13:11:58.527671
| 2021-03-27T02:37:29
| 2021-03-27T02:37:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 53
|
hpp
|
#include <boost/geometry/io/svg/write_svg_multi.hpp>
|
[
"k@kekyo.net"
] |
k@kekyo.net
|
a303607dc917160905dfc1459e96cb85883d4d76
|
4485b30d3188a4aed2d2d5dfb246e048c0505da1
|
/Solution/Solution/src/Engine/Engine.h
|
cde557a7a49fdfc61db7ee940e107427d3165038
|
[] |
no_license
|
BooLeet/PhasePortrait
|
3a2b214ece1f805cbee3842a4a4d5561fb56ce9e
|
5ea0fd2636617b20b2e1c37d6d7b4f5ab2f92081
|
refs/heads/main
| 2023-08-22T01:34:45.540012
| 2021-10-13T17:11:14
| 2021-10-13T17:11:14
| 327,359,563
| 7
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,742
|
h
|
#pragma once
#include <vector>
#include "OpenGLComponents.h"
#include <string>
class Scene;
class CameraBehaviour;
class RendererBehaviour;
class Input;
class Shader;
class Engine
{
private:
GLFWwindow* window;
Scene* scene;
double unscaledDeltaTime;
size_t windowWidth, windowHeight;
bool fullScreen;
Input* input;
Shader* defaultShader;
bool quitFlag = false;
bool CloseWindow();
public:
vec3 clearColor = vec3(0, 0, 0);
double timeScale;
// Has references for all the renderers on the scene
class RendererRegistry
{
private:
std::vector< RendererBehaviour*> renderers;
public:
// Adds a renderer
void RegisterRenderer(RendererBehaviour* renderer);
// Removes a renderer
void UnregisterRenderer(RendererBehaviour* renderer);
// Renders all objects
void RenderAll(CameraBehaviour* camera) const;
RendererBehaviour* operator[](size_t index) const;
size_t Size() const;
};
// Has references for all the cameras on the scene
class CameraRegistry
{
private:
std::vector<CameraBehaviour*> cameras;
public:
// Adds a camera
void RegisterCamera(CameraBehaviour* cam);
// Finds and removes a camera
void UnregisterCamera(CameraBehaviour* cam);
void RenderCameras(const RendererRegistry& rendererRegistry) const;
};
CameraRegistry cameraRegistry;
RendererRegistry rendererRegistry;
Engine(size_t windowWidth, size_t windowHeight,bool fullscreen);
~Engine();
// Main engine loop
int MainLoop();
Scene* GetScene();
size_t GetWindowWidth() const;
size_t GetWindowHeight() const;
double GetDeltaTime() const;
double GetUnscaledDeltaTime() const;
Input* GetInput() const;
void ConsoleLog(std::string str) const;
const Shader& GetDefaultShader() const;
void Quit();
};
|
[
"maxtheboo1337@gmail.com"
] |
maxtheboo1337@gmail.com
|
4af65f9f424670bcbb0ce716463dab0e8b7d8b3c
|
65439e109bcb4644341187d911fc6dcfd145ac4a
|
/src/Instrucao.cpp
|
663742f4db837fb5200285bda3223fc7598fe1e8
|
[] |
no_license
|
juan-santos/apresentacaoPAA
|
65e1ce2e802d15cdf5be9edfeba25a509ac2e4f7
|
7d082e692841a8b1a2206155c7259782d4da40be
|
refs/heads/master
| 2021-08-23T10:36:53.257363
| 2017-12-03T15:08:58
| 2017-12-03T15:08:58
| 112,538,810
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 921
|
cpp
|
#include "Instrucao.h"
Instrucao::Instrucao() {
}
int Instrucao::Run(sf::RenderWindow &App) {
sf::Event Event;
sf::Texture Texture;
sf::Sprite Sprite;
bool Running = true;
if (!Texture.loadFromFile("bin/Release/files/images/menu/instrucao.png")){
std::cerr << "Error loading menu.png" << std::endl;
}
Sprite.setTexture(Texture);
Sprite.setColor(sf::Color(255, 255, 255, 255));
while (Running) {
//Verifying events
while (App.pollEvent(Event)) {
// Window closed
if (Event.type == sf::Event::Closed) {
return SAIR;
}
//Key pressed
if (Event.type == sf::Event::KeyPressed) {
switch (Event.key.code) {
case sf::Keyboard::Return:
return MENU;
default:
break;
}
}
}
//Clearing screen
App.clear();
//Drawing
App.draw(Sprite);
App.display();
}
return SAIR;
}
|
[
"juan.h.santos@gmail.com"
] |
juan.h.santos@gmail.com
|
d224da84e34b8ac851d28e647b9b7b550e82f4c4
|
d6b461bf38bdadc03b30d39b1511b7e658d4890a
|
/Necro/Enemy.h
|
96857599728903225ae922242956e5b3031f8bd0
|
[] |
no_license
|
koe22kr/2Dbasis
|
f27d74a038f6eb5f92ae91fae88ea2dbac2bd98c
|
1763942042c31f520a4039deba8d9ad9ad0fbc82
|
refs/heads/master
| 2022-04-05T08:26:19.643151
| 2020-03-04T01:42:09
| 2020-03-04T01:42:09
| 185,978,543
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 745
|
h
|
#pragma once
#include "Std.h"
#include "Chara.h"
class Pather
{
public:
Pather* pre_pather = nullptr;
POINT pos = { 0,0 };
int Score = 0;
int direction;
int Getdirection();
Pather();
~Pather();
private:
};
class Enemy :public Chara
{
public:
virtual bool Init();
bool release();
virtual void Process();
virtual void Move();
virtual bool Mining();
virtual WINT Attack();
virtual void Change_rt(int start_rt,int end_rt);
POINT Astar();
vector<POINT> Direction_for_search;
vector<POINT> path;
set <Pather*> Openlist;
set <Pather*> Closelist;
Pather* find_Pather_in_openlist(set<Pather*> openlist, Pather* newpather);
Enemy();
virtual ~Enemy();
};
|
[
"koe22kr@gmail.com"
] |
koe22kr@gmail.com
|
d3a500690115a80dd9f2aa4bdeace366641c3426
|
1f48a24e68d346164bd654b4c11adcc1770fbcf2
|
/kocsi_pd.ino
|
94f2e613079fede2ddeaf8adbd0437def4a346ba
|
[
"MIT"
] |
permissive
|
erwzqsdsdsf/TDK
|
018f04e9f3bfacf1ae3ca7d4ff062072ae6a9bd7
|
c62c4ffac17caeed9d09f63f1ee068a19f85b679
|
refs/heads/master
| 2022-04-09T18:56:38.396222
| 2020-02-28T09:20:16
| 2020-02-28T09:20:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,529
|
ino
|
#include <Arduino.h>
#include <Wire.h>
#include <avr/wdt.h>
#include "PinChangeInt.h" //interrupt kezeléshez
//lábkiosztás definiálása
#define enc_pend1 4 //szögelfordulás mérése
#define enc_pend2 5
#define enc_cart1 2 //kocsi elmozdulásmérése
#define enc_cart2 3
#define rotR 12 //motor forgásiránya
#define rotL 13
#define pwm 10 //PWM jel
#define integral_null 8 //integrátor tag nullázása
#define poti 5 //poti
#define MAXPWM 230 //maximális kiadható PWM
#define calibn 7 //szögelfordulás nullpontjának
#define calibp 11 //kalibrálása
#define xnull 9
volatile int lastEncoded_pend = 0;
volatile int lastEncoded_cart = 0;
volatile long sum_pend = -1200; //nullpont beállítása alsó
long last_sum_pend = 0; //egyensúlyi helyzetben
volatile long sum_cart = 0; //kalibrálás a kocsi szélső,
//nullpont a középső helyzetében
double last_sum_cart = 0;
double xIntegral = 0;
long lastencoderValue_pend = 0;
long lastencoderValue_cart = 0;
int currPos = 0;
int lastPos = 0;
unsigned long currTime = 0;
unsigned long currTimeM = 0;
unsigned long lastTime = 0;
double sampleTime = 5; //mintavételezési idő
double velocity = 0;
double angVelocity = 0;
//szabalyozo parameterei
double p_fi = 90;
double d_fi = 4.7 / (sampleTime);
double p_x = 0.005;
double d_x = 0.08 / (sampleTime);
//pwm
int pwmValue;
//haladási irányu
bool R = 0;
int potiVal = 0;
//mozgoatlag
const int M = 1;
double readings[M];
int readIndex = 0;
double total = 0;
double average = 0;
void setup() {
Serial.begin (9600);
pinMode(enc_pend1, INPUT_PULLUP);
pinMode(enc_pend2, INPUT_PULLUP);
pinMode(enc_cart1,INPUT);
pinMode(enc_cart2, INPUT);
pinMode(integral_null, INPUT);
pinMode(poti,INPUT);
pinMode(calibp,INPUT);
pinMode(calibn,INPUT);
pinMode(xnull, INPUT_PULLUP);
//felhúzó ellenállások aktiválása
digitalWrite(enc_pend1, HIGH);
digitalWrite(enc_pend2, HIGH);
digitalWrite(enc_cart1, HIGH);
digitalWrite(enc_cart2, HIGH);
digitalWrite(xnull, HIGH);
//updateEncoder() függvény meghívása a fototranzisztor jelszintjének
//változásakor
attachPinChangeInterrupt(enc_pend1, updateEncoderPend, CHANGE);
attachPinChangeInterrupt(enc_pend2, updateEncoderPend, CHANGE);
attachPinChangeInterrupt(xnull, xNull, RISING);
attachInterrupt(0, updateEncoderCart, CHANGE);
attachInterrupt(1, updateEncoderCart, CHANGE);
//motorvezérlőhöz tartozó pinek kalibrálása
pinMode(pwm,OUTPUT);
pinMode(rotR,OUTPUT);
pinMode(rotL,OUTPUT);
pwmValue = 0;
Left();
analogWrite(pwm,pwmValue);
// light = analogRead(LIGHT);
// last_light = light;
}
void loop(){
currTime = micros();
//beavatkozó feszültség számítása:
if(currTime - lastTime >= sampleTime * 1000){
// currTimeM = micros();
// movingAverage(sum_cart);
// if(p_x * average < -5) average = -5 / p_x;
// if(p_x * average > 5) average = 5 / p_x;
pwmValue = p_fi * (double(sum_pend) + p_x * double(sum_cart) + d_x * double(sum_cart - last_sum_cart)) +
d_fi * (double(sum_pend - last_sum_pend) + p_x * double(sum_cart) + d_x * double(sum_cart - last_sum_cart));
last_sum_pend = sum_pend;
last_sum_cart = sum_cart;
lastTime = currTime;
if(pwmValue >= 0) Right();
else Left();
pwmValue = abs(pwmValue);
//ha túl közel vagyunk a szerkezet széléhez:
if(abs(sum_cart) >= 3200) pwmValue = 0;
//telítődés esetére:
if(pwmValue > MAXPWM) pwmValue = MAXPWM;
analogWrite(pwm,pwmValue);
// if(++i > 50){
// Serial.println(pwmValue);
// i=0;
// }
// i = micros();
// Serial.println(i-currTimeM);
// Serial.print('\t');
// if(abs(analogRead(LIGHT)-light) > 150)
// {
// enabledata = !enabledata;
// light = analogRead(LIGHT);
// }
// enabledata = (abs(analogRead(LIGHT)-light) > 150);
// if(enabledata && (i < arraysize)){
// cartarray[i] = sum_cart;
// pendarray[i] = sum_pend;
// i++;
// }
// if(!enabledata && i>200){
// analogWrite(pwm,0);
// for(int j = 0; j <= i; j++){
// Serial.print(cartarray[j]);
// Serial.print('\t');
// Serial.println(pendarray[j]);
// }
// i = 0;
// }
}
//
// //szögelfordulás nullpontjának menet közbeni kalibrálására
if(digitalRead(calibp)){
sum_pend = sum_pend + 1;
delay(300);
}
if(digitalRead(calibn)){
sum_pend = sum_pend - 1;
delay(300);
}
//integrátor menet közbeni nullázására
if(digitalRead(integral_null)){
xIntegral = 0;
sum_cart = 0;
}
// //Serial.print(sum_pend);
// //Serial.print('\t');
// //Serial.println(digitalRead(calibn));
}
void updateEncoderPend(){
int MSB = digitalRead(enc_pend1); //MSB = most significant bit
int LSB = digitalRead(enc_pend2); //LSB = least significant bit
//a pinek értékének konvertálása egész számmá:
int encoded = (MSB << 1) |LSB;
//az előző értékhez való hozzáadás
int sum = (lastEncoded_pend << 2) | encoded;
//menetirány megállapítása, ez alapján az elfordulásérték frissítése
if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011)
sum_pend ++;
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000)
sum_pend --;
lastEncoded_pend = encoded;
}
void updateEncoderCart(){
int MSB = digitalRead(enc_cart1);
int LSB = digitalRead(enc_cart2);
int encoded = (MSB << 1) |LSB;
int sum = (lastEncoded_cart << 2) | encoded;
if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011)
sum_cart --;
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000)
sum_cart ++;
lastEncoded_cart = encoded;
}
//ha negatív x irányba kell a kocsit vezérelni
void Left()
{
digitalWrite(rotR,LOW);
digitalWrite(rotL,HIGH);
R = 0;
}
//ha pozitív x irányba kell a kocsit vezérelni
void Right(){
digitalWrite(rotL,LOW);
digitalWrite(rotR,HIGH);
R = 1;
}
void movingAverage(double unit){
total -= readings[readIndex];
readings[readIndex] = unit;
total += readings[readIndex];
readIndex++;
if(readIndex >= M) readIndex = 0;
average = total / M;
}
void xNull(){
sum_cart = 0;
}
|
[
"antalpeter8840@gmail.com"
] |
antalpeter8840@gmail.com
|
73eeb9facbd46821aa6536f72a4ae4fa9dae3cf2
|
fb6331627a01ff490b474a890ff56c2310f6bc39
|
/ChinolChoko/kzyKT/kzyKT.cc
|
8390ca858fccfcc6ffbbc0e5b5ecad25cb806521
|
[] |
no_license
|
satellitex/acpc2017
|
a065b5f66734c5bdb206ae1c9c15f79ea032db70
|
8f938553eaaafe56565d77da9a406f05fe2ee107
|
refs/heads/master
| 2021-01-01T15:49:01.855760
| 2017-09-19T00:02:31
| 2017-09-19T00:02:31
| 97,707,979
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,220
|
cc
|
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--)
#define REP(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) REP(i,0,n)
typedef pair<double,double> P;
#define N 1001
double d[1<<15][15][15];
vector<int> G[N],rG[N],g;
bool u[N];
int n,cmp[N];
void add_edge(int x,int y){G[x].push_back(y);rG[y].push_back(x);}
void dfs(int x){u[x]=1;rep(i,G[x].size())if(!u[G[x][i]])dfs(G[x][i]);g.push_back(x);}
void rdfs(int x,int k){u[x]=1;cmp[x]=k;rep(i,rG[x].size())if(!u[rG[x][i]])rdfs(rG[x][i],k);}
int scc() {
memset(u,0,sizeof(u));g.clear();rep(i,n)if(!u[i])dfs(i);memset(u,0,sizeof(u));
int k=0;rrep(i,g.size())if(!u[g[i]])rdfs(g[i],k++);return k;
}
void init() {
rep(i,n) G[i].clear(),rG[i].clear();
g.clear();
}
int rev(int x) {return (x+n/2)%n;}
int two_sat(vector<P> v) {
init();
rep(i,v.size()) {
add_edge(v[i].F,rev(v[i].S));
add_edge(v[i].S,rev(v[i].F));
}
scc();
rep(i,n/2) {
if(cmp[i]==cmp[i+n/2]) return 0;
}
return 1;
}
double D(P a,P b) {
return sqrt((a.F-b.F)*(a.F-b.F)+(a.S-b.S)*(a.S-b.S));
}
int main() {
int m;
cin >> n >> m;
P a[n][2],b[m];
rep(i,n)rep(j,2) cin >> a[i][j].F >> a[i][j].S;
rep(i,m) cin >> b[i].F >> b[i].S;
rep(t,1<<m)rep(i,m)rep(j,m) d[t][i][j]=1<<30;
rep(k,m) {
d[1<<k][k][k]=0;
rep(t,1<<m) {
rep(i,m) {
if(!(t&(1<<i))) continue;
rep(j,m) {
if(!(t&(1<<j))) d[t|(1<<j)][k][j]=min(d[t|(1<<j)][k][j],d[t][k][i]+D(b[i],b[j]));
}
}
}
}
double c[n][n][4];
n*=2;
rep(i,n/2) {
REP(j,i+1,n/2) {
rep(k,4) c[i][j][k]=1<<30;
rep(k,m)rep(l,m)rep(s,2)rep(t,2)c[i][j][s+t*2]=min(c[i][j][s+t*2],D(a[i][s],b[k])+d[(1<<m)-1][k][l]+D(b[l],a[j][t]));
}
}
double l=0,r=10000;
rep(t,50) {
double mid=(l+r)/2;
vector<P> v;
rep(i,n/2) {
REP(j,i+1,n/2) {
if(c[i][j][0]>mid) v.push_back(P(i,j));
if(c[i][j][1]>mid) v.push_back(P(rev(i),j));
if(c[i][j][2]>mid) v.push_back(P(i,rev(j)));
if(c[i][j][3]>mid) v.push_back(P(rev(i),rev(j)));
}
}
if(two_sat(v)) r=mid;
else l=mid;
}
printf("%.10f\n",l);
return 0;
}
|
[
"s1200008aizu@gmail.com"
] |
s1200008aizu@gmail.com
|
a020088919fe78e4e4e195a36c06833bf39b26b5
|
9647fd27fed29c2614f8d406fa90f19f1b55370c
|
/simon-touch/voipproviderfactory.cpp
|
d88aae90ef30c77f894b6fefe015e0fa3cf6a927
|
[] |
no_license
|
KDE/simon-tools
|
aa42bdd96dff99a67c0e1a93adaa89afce7f749b
|
ca668c91b6ac2455b8bdd47f013701eff1ea1fb9
|
refs/heads/master
| 2021-01-06T20:37:26.029880
| 2019-03-03T01:06:46
| 2019-03-03T01:06:46
| 42,732,489
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 954
|
cpp
|
/*
* Copyright (C) 2011-2012 Peter Grasch <grasch@simon-listens.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* or (at your option) any later version, as published by the Free
* Software Foundation
*
* 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.
*/
#include "voipproviderfactory.h"
#include "skypevoipprovider.h"
VoIPProvider* VoIPProviderFactory::getProvider()
{
return new SkypeVoIPProvider;
}
|
[
"grasch@simon-listens.org"
] |
grasch@simon-listens.org
|
d2c6bc478596a0d4ce6d3fe51280de5181f093a3
|
23d71c9281cfd801a2f5599c53d475c7879ab707
|
/proyecto/ProyectoEstructuras/ProyectoEstructuras/Proyecto.cpp
|
88e0ed079de6034fd8f8781ea3939d96a185e3ea
|
[] |
no_license
|
abicarvajal/ProyectoEstructuras
|
479dd62d44fade0b491650247911c633beb85ab6
|
f2c77e9d8091f2009fff82b70b5f073c1047637a
|
refs/heads/master
| 2021-08-22T03:50:01.074416
| 2017-11-29T06:01:18
| 2017-11-29T06:01:18
| 112,433,406
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 26,936
|
cpp
|
#include <iostream>
#include <conio.h>
#include <string>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "qrcodegen.h"
#define Tam 11
#define vabTam 20
using namespace std;
//DEFINICION DE ESTRUCTURAS
struct Producto { //muestra produtos
char nombre[20];
float precio = 0;
float pUnidad = 0;
int stock = 0;
};
struct DatosCliente {
char nombre[15];
char apellido[15];
int cedula;
};
struct ListaDatosCliente
{
DatosCliente datosCliente;
float total = 0.0f;
ListaDatosCliente *ant, *sig;
};
struct ListaProducto {
Producto producto;
ListaProducto *sig;
ListaProducto *ant;
}listita;
struct Factura {
ListaProducto compra;
DatosCliente datos;
float total;
};
typedef ListaProducto *Lista;
typedef Factura *fact;
typedef ListaDatosCliente *ListaCliente;
//PROTOTIPOS DE FUNCIONES
int validaCedula();
void menuCompra(int opcion);
void compra(Lista &, Lista &, int);
void mostrarProductos(Lista);
void inicializarProductos(Lista &, char *, float, int, int);
int validarProducto(Lista &, char *, int);
void validarPrecio(Lista &, Lista);
void validarStock(Lista &);
void facturar(Lista &, fact &);
void ingresoDatos(fact &, Lista &);
void nuevaCompra(Lista &);
void gotoxy(int x, int y);
void barraCarga();
void seleccionarProducto(Lista lista);
int menuTeclas(Lista &);
void backgroundcolor(int color);
void guardar(ListaCliente &listaCliente, fact &factura, char *archivo, int contador);
bool esNumerico(string);
int validarIngresoNumeros(char *);
char *validarCaracteres(char *);
int menuDireccion();
void modificarListaCompra(Lista &, Lista &, Lista &);
void inicio();
void generarQr(char *);
static void generarQrBasico(char dato1[]);
static void printQr(const uint8_t qrcode[]);
int main() {
char nombreArchivo[12] = "factura.txt";
int i = 1, j = 0, contador = 0;
char opcion;
char *lista[vabTam] = { "Sprite 200ml","Coca-Cola","ChocoWonka","Caramelos",
"V220 bebida","Nueces 1kg","Pretzels","Chocolate",
"Te Verde","Queso Fresco","Frutaris","Harina 1kg",
"Helado 1L","Nescafe","Doritos","Powerade","Pilsener 1L",
"Yogurt 1L","Colcafe","Atun Real"};
float precios[vabTam] = { 1.00,1.00,2.30,2.4,2.90,3.00,2.00,1.50,1.50,2.30,0.25,2.00,2.00,1.75,1.00,2.30,2.4,2.90,3.00,2.00 };
int stock[vabTam] = { 5,5,2,2,2,6,5,6,7,8,1,1,1,1,1,2,6,5,6,7 };
Lista listaCompra, lisProductos, lisAuxiliar;
ListaCliente listaCliente;
fact factura;
factura = new (struct Factura);
listaCliente = new ListaDatosCliente();
listaCompra = NULL;
lisProductos = NULL;
lisAuxiliar = NULL;
listaCliente = NULL;
//Inicializa los productos disponibles
do {
inicializarProductos(lisProductos, lista[j], precios[j], stock[j], j);
inicializarProductos(lisAuxiliar, lista[j], precios[j], stock[j], j);
j++;
} while (j<vabTam);
inicio();
barraCarga();
//Muestra el menu hasta que se elija "Salir".
do {
menuCompra(i);
while ((opcion = getch()) != 13) {
if (opcion == 72) {
if (i == 1) {
i = 6;
}
else {
i--;
}
}
if (opcion == 80) {
if (i == 6) {
i = 1;
}
else {
i++;
}
}
menuCompra(i);
}
switch (i) {
case 1:
if (lisProductos == NULL) {
printf("No puede comprar mas productos");
i = 6;
exit(1);
}
else {
int opc;
system("cls");
opc = menuTeclas(lisProductos);
compra(listaCompra, lisProductos, opc);
validarStock(lisProductos);
}
system("pause");
break;
case 2:
system("cls");
modificarListaCompra(listaCompra, lisProductos, lisAuxiliar);
printf("\n\n");
mostrarProductos(listaCompra);
system("pause");
break;
case 3:
system("cls");
if (listaCompra != NULL) {
contador++;
printf("\n\n\tFACTURACION\n\n");
ingresoDatos(factura, listaCompra);
nuevaCompra(listaCompra);
guardar(listaCliente, factura, nombreArchivo, contador);
printf("\n\n SU COMPRA HA FINALIZADO CON EXITO\!\n\n");
system("pause");
system("cls");
barraCarga();
}
else {
printf("\n\n\n\t*******************************************");
printf("\n\n\t No ha seleccionado ningun producto\n");
printf("\n\n\t*******************************************\n");
Sleep(700);
//system("pause");
}
break;
case 4:
system("cls");
printf("Abriendo archivo ayuda...\n");
ShellExecute(NULL, L"open", L"C://Users/Administrador1/Desktop/proyecto/ManualdeUsuario.chm", NULL, NULL, SW_SHOWNORMAL);
system("pause");
break;
case 5:
system("cls");
printf("SOBRE NOSOTROS\n\n");
/* char lista[300] = "";
strcpy(lista, "https://scontent.fuio7-1.fna.fbcdn.net/v/t34.0-12/24203566_2162297370462812_645498074_n.jpg?oh=5ba57cf8ae52e28be8fcec13a863d333&oe=5A213C96");*/
//generarQr(lista);
system("pause");
break;
case 6:
system("cls");
printf("\n\n\t*******************************************\n");
printf("\t\tGracias por usar este software!\n");
printf("\n\t*******************************************\n");
system("Start C:/Users/Administrador1/Desktop/proyecto/ProyectoEstructuras/ProyectoEstructuras/PDFg.jar");
system("pause");//Sleep(2000);
break;
default:;
}
} while (i != 6);
return 0;
}
void backgroundcolor(int color) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
void inicio() {
system("color 0A");
gotoxy(0, 0);
backgroundcolor(7);
while (!kbhit()) {
gotoxy(20, 28); printf("||");
gotoxy(20, 29); printf("||");
gotoxy(20, 30); printf("||");
gotoxy(20, 31); printf("||");
gotoxy(20, 32); printf("||");
gotoxy(20, 33); printf("||");
gotoxy(20, 34); printf("||");
gotoxy(20, 35); printf("||");
gotoxy(20, 36); printf("||");
gotoxy(20, 37); printf("||");
gotoxy(20, 38); printf("||");
gotoxy(20, 39); printf("||");
gotoxy(78, 28); printf("||");
gotoxy(78, 29); printf("||");
gotoxy(78, 30); printf("||");
gotoxy(78, 31); printf("||");
gotoxy(78, 32); printf("||");
gotoxy(78, 33); printf("||");
gotoxy(78, 34); printf("||");
gotoxy(78, 35); printf("||");
gotoxy(78, 36); printf("||");
gotoxy(78, 37); printf("||");
gotoxy(78, 38); printf("||");
gotoxy(78, 39); printf("||");
gotoxy(22, 26); printf("********************************************************");
gotoxy(29, 28); printf("UNIVERSIDAD DE LAS FUERZAS ARMADAS ESPE");
gotoxy(38, 30); printf("ESTRUCTURA DE DATOS");
gotoxy(25, 32); printf("INTEGRANTES:");
gotoxy(38, 34); printf("Carvajal Abigail");
gotoxy(38, 35); printf("Corral Daniel");
gotoxy(40, 37); printf("TEMA PROYECTO:");
gotoxy(25, 39); printf("TIENDA VIRTUAL CON LISTAS DOBLEMENTE ENLAZADAS");
gotoxy(22, 41); printf("********************************************************");
gotoxy(25, 42); printf("\n");
gotoxy(25, 43); printf("\n");
gotoxy(25, 44); printf("\n");
gotoxy(25, 45); printf("\n");
gotoxy(25, 46); printf("\n");
gotoxy(25, 47); printf("\n");
gotoxy(25, 48); printf("\n");
gotoxy(25, 49); printf("\n");
gotoxy(25, 50); printf("\n");
gotoxy(25, 51); printf("\n");
}
system("cls");
}
int menuTeclas(Lista &lista) {
system("color 07");
system("cls");
Lista aux, aux1;
aux = lista;
aux1 = lista;
int cont = 0;
while (aux != NULL) {
cont++;
aux = aux->sig;
}
int men[50] = {};
string menNombre[50] = {};
float precio[50] = {};
for (int i = 0; i<cont; i++) {
men[i] = aux1->producto.stock;
menNombre[i] = aux1->producto.nombre;
precio[i] = aux1->producto.precio;
aux1 = aux1->sig;
}
int cursor = 0;
char tecla;
for (;;) {
system("cls");
backgroundcolor(7);
printf("\n\n\t PRODUCTOS DISPONIBLES\n\n");
printf(" Producto\t\t Precio\t Stock\n");
printf("---------------------------------------------------------\n");
for (int i = 0; i < cont; i++) {
if (cursor == i) {
backgroundcolor(160);
printf(" %s\t\t %.2f\t\t %d\n", menNombre[i].c_str(), precio[i], men[i]);
backgroundcolor(7);
}
else {
backgroundcolor(7);
printf(" %s\t\t %.2f\t\t %d\n", menNombre[i].c_str(), precio[i], men[i]);
}
}
for (;;) {
tecla = _getch();
if (tecla == 80) {
cursor++;
if (cursor == cont)
{
cursor = 0;
}
break;
}
if (tecla == 72) {
cursor--;
if (cursor == -1)
{
cursor = cont;
}
break;
}
if (tecla == 13) {
cursor += 1;
/*Dependiendo de donde el cursor de enter entra en el switch*/
return cursor;
}
}
}while (tecla != 13);
//printf("%d",cursor);
system("pause");
return cursor;
}
//Esta función permite realizar nuevas compras/vacia la lista de compras
void nuevaCompra(Lista &lista) {
if (lista != NULL) {
Lista punteroAuxiliar;
while (lista != NULL) {
punteroAuxiliar = lista->sig;
delete(lista);
lista = punteroAuxiliar;
}
}
}
//Ingresa datos de Usuario... aqui se mete generacion de QR
void ingresoDatos(fact &factura, Lista &lisProductos) {
fact aux = new(struct Factura);
char nombre[50], apellido[50];
int cedula;
//Nombre
strcpy(nombre, validarCaracteres("Ingrese su Nombre: "));
strcpy(aux->datos.nombre, nombre);
//Apellido
strcpy(apellido, validarCaracteres("Ingrese su Apellido: "));
strcpy(aux->datos.apellido, apellido);
//Cedula
fflush(stdin);
cedula = validaCedula();
aux->datos.cedula = cedula;
factura = aux;
facturar(lisProductos, aux);
}
char *validarCaracteres(char *mensaje) {
int i = 0;
bool esCadena = false;
char cadena[50];
do
{
i = 0;
fflush(stdin);
printf("%s", mensaje);
scanf("%s", &cadena);
while (cadena[i] != NULL)
{
if (cadena[i] > 64 && cadena[i] < 91)
{
esCadena = true;
}
if (cadena[i] > 96 && cadena[i] < 123)
{
esCadena = true;
}
i++;
}
if (esCadena == false) printf("Ingreso no valido.\n");
} while (esCadena == false);
return cadena;
}
void facturar(Lista &lisProductos, fact &factura) {
float total = 0;
Lista aux = new(struct ListaProducto);
aux = lisProductos;
char espacio[2] = "\t";
char fin[30] = "";
while (aux != NULL) {
aux->producto.pUnidad += aux->producto.precio;//*aux->producto.stock;
total += aux->producto.precio;//*aux->producto.stock;
aux = aux->sig;
}
factura->total = total;
system("cls");
printf("\n\t|**********************************************************|");
printf("\n\t|\t\t\t FACTURA |");
printf("\n\t| Usuario: %s %s ", factura->datos.nombre, factura->datos.apellido);
printf("\n\t| ID: %d ", factura->datos.cedula);
printf("\n\t|--------------------------------------------------------- |\n");
printf("\n\t| Producto\t\t Precio\t Cantidad |\n");
printf("\t|--------------------------------------------------------- |\n");
mostrarProductos(lisProductos);
printf("\t \t\t Total = %.2f\n", factura->total);
printf("\t|--------------------------------------------------------- |\n");
strcat(fin , factura->datos.nombre);
strcat(fin, espacio);
strcat(fin, factura->datos.apellido);
generarQr(fin);
}
//PARA INICIALIZAR LOS PRODUCTOS DISPONIBLES
void inicializarProductos(Lista &lisProductos, char *lista, float precios, int stock, int i) {
if (lisProductos == NULL) {
Lista aux, aux1;
aux = new (struct ListaProducto);
strcpy(aux->producto.nombre, lista);
aux->producto.precio = precios;
aux->producto.stock = stock;
aux->sig = aux->ant = NULL;
lisProductos = aux;
}
if (lisProductos != NULL) {
Lista aux, aux1;
aux = new (struct ListaProducto);
strcpy(aux->producto.nombre, lista);
aux->producto.precio = precios;
aux->producto.stock = stock;
aux1 = lisProductos;
aux->sig = aux1;
aux->ant = aux1->ant;
aux1->ant = aux;
lisProductos = aux;
}
}
void mostrarProductos(Lista lista) {
if (lista == NULL) {
printf("No existen elementos en la lista. \n");
}
else {
int i = 1;
while (lista != NULL) {
//SetConsoleTextAttribute ( salida, FOREGROUND_GREEN | BACKGROUND_BLUE );
printf("\t| %s\t\t %.2f\t\t %d |\n", lista->producto.nombre, lista->producto.precio, lista->producto.stock);
//SetConsoleTextAttribute ( salida, coloresOriginales);
printf("\t|--------------------------------------------------------- |\n");
lista = lista->sig;
i++;
}
printf("\n");
}
}
//MENU CON CURSORES
void menuCompra(int opcion) {
HANDLE salida = GetStdHandle(STD_OUTPUT_HANDLE);
WORD coloresOriginales;
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
GetConsoleScreenBufferInfo(salida, &csbiInfo);
coloresOriginales = csbiInfo.wAttributes;
switch (opcion) {
case 1:
system("cls");
printf("\t\t----------------------\n");
printf("\t\t CYBER-MARKET\n");
printf("\t\t----------------------\n\n");
SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE);
printf("\t Iniciar compra \n");
SetConsoleTextAttribute(salida, coloresOriginales);
printf("\t Eliminar de lista de productos \n");
printf("\t Finalizar Compra \n");
printf("\t Ayuda\n");
printf("\t Sobre Nosotros \n");
printf("\t Salir. \n\n");
break;
case 2:
system("cls");
printf("\t\t----------------------\n");
printf("\t\t CYBER-MARKET\n");
printf("\t\t----------------------\n\n");
printf("\t Iniciar compra. \n");
SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE);
printf("\t Eliminar de lista de productos \n");
SetConsoleTextAttribute(salida, coloresOriginales);
printf("\t Finalizar Compra \n");
printf("\t Ayuda\n");
printf("\t Sobre Nosotros \n");
printf("\t Salir. \n\n");
break;
case 3:
system("cls");
printf("\t\t----------------------\n");
printf("\t\t CYBER-MARKET\n");
printf("\t\t----------------------\n\n");
printf("\t Iniciar compra \n");
printf("\t Eliminar de lista de productos \n");
SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE);
printf("\t Finalizar Compra \n");
SetConsoleTextAttribute(salida, coloresOriginales);
printf("\t Ayuda\n");
printf("\t Sobre Nosotros \n");
printf("\t Salir. \n\n");
break;
case 4:
system("cls");
printf("\t\t----------------------\n");
printf("\t\t CYBER-MARKET\n");
printf("\t\t----------------------\n\n");
printf("\t Iniciar compra \n");
printf("\t Eliminar de lista de productos \n");
printf("\t Finalizar Compra \n");
SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE);
printf("\t Ayuda\n");
SetConsoleTextAttribute(salida, coloresOriginales);
printf("\t Sobre Nosotros \n");
printf("\t Salir. \n\n");
break;
case 5:
system("cls");
printf("\t\t----------------------\n");
printf("\t\t CYBER-MARKET\n");
printf("\t\t----------------------\n\n");
printf("\t Iniciar compra \n");
printf("\t Eliminar de lista de productos \n");
printf("\t Finalizar Compra \n");
printf("\t Ayuda\n");
SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE);
printf("\t Sobre Nosotros \n");
SetConsoleTextAttribute(salida, coloresOriginales);
printf("\t Salir. \n\n");
break;
case 6:
system("cls");
printf("\t\t----------------------\n");
printf("\t\t CYBER-MARKET\n");
printf("\t\t----------------------\n\n");
printf("\t Iniciar compra \n");
printf("\t Eliminar de lista de productos \n");
printf("\t Finalizar Compra \n");
printf("\t Ayuda\n");
printf("\t Sobre Nosotros \n");
SetConsoleTextAttribute(salida, FOREGROUND_GREEN | BACKGROUND_BLUE);
printf("\t Salir. \n\n");
SetConsoleTextAttribute(salida, coloresOriginales);
break;
default:;
}
}
void compra(Lista &listaCompra, Lista &lisProductos, int opc) {
printf("\n\n************************ \n");
printf("\nEl producto escogido es: \n");
int i = 0, cantidad;
float total = 0;
Lista auxprod = new (struct ListaProducto);
auxprod = lisProductos;
for (i = 0; i<opc - 1; i++)
{
auxprod = auxprod->sig;
}
printf("%s \n", auxprod->producto.nombre);
do {
cantidad = validarIngresoNumeros("\nIngrese la cantidad del producto que desea: ");
if (cantidad > auxprod->producto.stock)
printf("No disponemos de esa cantidad de productos.\n");
} while (cantidad < 0 || cantidad > auxprod->producto.stock);
auxprod->producto.stock = auxprod->producto.stock - cantidad;
//Se añade el producto seleccionado a la lista de compras
if (listaCompra != NULL) {
Lista aux, aux1;
aux = new (struct ListaProducto);
if (validarProducto(listaCompra, auxprod->producto.nombre, cantidad) != 0) {
strcpy(aux->producto.nombre, auxprod->producto.nombre);
aux->producto.stock = cantidad;
//aux->producto.precio = auxprod->producto.precio * cantidad;
aux1 = listaCompra;
aux->sig = aux1;
aux->ant = aux1->ant;
aux1->ant = aux;
listaCompra = aux;
}
}
else {
Lista aux, aux1;
aux = new (struct ListaProducto);
strcpy(aux->producto.nombre, auxprod->producto.nombre);
aux->producto.stock = cantidad;
//aux->producto.precio = auxprod->producto.precio;
aux->sig = aux->ant = NULL;
listaCompra = aux;
}
validarPrecio(listaCompra, lisProductos);
//Muestra la lista de compras antes de finalizar
system("cls");
printf("\n\tLa lista de compras es: \n\n");
printf("\t Producto\t\t Subtotal\t Cantidad\n");
printf("\t---------------------------------------------------------\n");
mostrarProductos(listaCompra);
auxprod = listaCompra;
while (auxprod != NULL)
{
total = total + auxprod->producto.precio;
auxprod = auxprod->sig;
}
printf("\t\t\t Total = %.2f\n\n", total);
}
int validarProducto(Lista &lista, char *nombreproducto, int cantidad) {
int band = 1;
Lista aux = new(ListaProducto);
aux = lista;
while (aux != NULL)
{
band = strcmp(nombreproducto, aux->producto.nombre);
if (band == 0)
{
aux->producto.stock = aux->producto.stock + cantidad;
break;
}
aux = aux->sig;
}
return (band);
}
void barraCarga() {
printf("\n \n\t\tPresione cualquier tecla para iniciar compra \n");
getch();
system("cls");
int x, y, i, z, a;
gotoxy(25, 10);
printf("CARGANDO");
for (i = 10; i<50; i++) {
gotoxy(i, 13);
printf("%c", 177);
gotoxy(36, 10);
printf("%d %c", i * 2, '%');
for (x = 50; x<70; x++) {
for (y = 1; y<70; y++) {
gotoxy(y, 24);
}
}
}
}
void gotoxy(int x, int y) {
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
void validarStock(Lista &lista) {
Lista aux = new(ListaProducto);
aux = lista;
if (aux != NULL) {
while (aux != NULL)
{
if (aux->producto.stock == 0)
{
if (aux->ant == NULL&&aux->sig == NULL) {
lista = NULL;
break;
}
if (aux->ant == NULL)
{
aux->sig->ant = NULL;
lista = aux->sig;
}
if (aux->sig == NULL)
{
aux->ant->sig = NULL;
}
if (aux->ant != NULL && aux->sig != NULL)
{
aux->ant->sig = aux->sig;
aux->sig->ant = aux->ant;
}
}
aux = aux->sig;
}
}
}
void guardar(ListaCliente &listacliente, fact &factura, char *archivo, int contador) {
FILE *ptr;
char nombre[30] = {""};
ptr = fopen(archivo, "a"); //REALIZO LA APERTURA DEL ARCHIVO
if (ptr == NULL)
{
printf("ERROR.\n");
}
else
{
strcpy(nombre, factura->datos.nombre);
//fputs(nombre,ptr);
fprintf(ptr, "Nombre: %s Apellido: %s Cedula: %d \n", nombre, factura->datos.apellido, factura->datos.cedula);
fclose(ptr);
}
}
//funcion para determinar el precio de la lisa de compras
void validarPrecio(Lista &listaCompra, Lista lisProductos) {
Lista aux = new(ListaProducto);
int band = 1;
aux = listaCompra;
while (aux != NULL)
{
while (lisProductos != NULL)
{
band = strcmp(lisProductos->producto.nombre, aux->producto.nombre);
if (band == 0)
{
aux->producto.precio = lisProductos->producto.precio * aux->producto.stock;
}
lisProductos = lisProductos->sig;
}
aux = aux->sig;
}
}
int validarIngresoNumeros(char *mensaje) {
string linea;
int numero;
bool repite = true;
do
{
//fflush(stdin);
printf("%s", mensaje);
fflush(stdin);
getline(cin, linea);
if (esNumerico(linea))
{
repite = false;
}
else
{
printf("Ingreso no valido.\n");
}
} while (repite);
numero = atoi(linea.c_str());
//cin.get();
return numero;
}
bool esNumerico(string linea) {
bool b = true;
int longitud = linea.size();
if (longitud == 0) //caundo el usuario pulsa enter
{
b = false;
}
else if (longitud == 1 && !isdigit(linea[0]))
{
b = false;
}
else
{
int i;
if (linea[0] == '+' || linea[0] == '-')
i = 1;
else i = 0;
while (i<longitud)
{
if (!isdigit(linea[i]))
{
b = false;
break;
}
i++;
}
}
return b;
}
int menuDireccion() {
int cursor = 0;
char tecla;
char *opc[2] = { "SI","NO" };
for (;;) {
system("cls");
printf("\n\n********************************************************\n");
printf("\n\nEsta seguro que desea eliminar el producto seleccionado?\n\n");
backgroundcolor(7);
for (int i = 0; i < 2; i++) {
if (cursor == i) {
backgroundcolor(160);
printf(" %s\t",opc[i]);
backgroundcolor(7);
}
else {
backgroundcolor(7);
printf(" %s\t",opc[i] );
}
}
for (;;) {
tecla = _getch();
if (tecla == 75) {
cursor++;
if (cursor == 2)
{
cursor = 0;
}
break;
}
if (tecla == 77) {
cursor--;
if (cursor == -1)
{
cursor = 2;
}
break;
}
if (tecla == 13) {
cursor += 1;
//printf("cursor = %d", cursor);
/*Dependiendo de donde el cursor de enter entra en el switch*/
return cursor;
}
}
}while (tecla != 13);
return cursor;
}
void modificarListaCompra(Lista &listaCompra, Lista &lisProductos, Lista &listAuxiliar)
{
int opc, op;
Lista aux2 = new (struct ListaProducto);
Lista auxprod = new (struct ListaProducto);
auxprod = listaCompra;
aux2 = listAuxiliar;
if (listaCompra == NULL)
{
printf("No existen productos disponibles.\n");
}
else {
printf(" ELIMINAR DE LA LISTA DE COMPRAS \n\n");
printf("Escoja que producto desea modificar: \n");
opc = menuTeclas(listaCompra);
op = menuDireccion();
//Elimnar el producto de la lsita de compras y aumentar en la lista de productos
if (op == 1)
{
for (int i = 0; i<opc - 1; i++)
auxprod = auxprod->sig;
//Se añade el producto selecionado a la lista de productos
if (lisProductos != NULL) {
Lista aux, aux1;
aux = new (struct ListaProducto);
if (validarProducto(lisProductos, auxprod->producto.nombre, auxprod->producto.stock) != 0) {
strcpy(aux->producto.nombre, auxprod->producto.nombre);
aux->producto.stock = auxprod->producto.stock;
aux->producto.precio = auxprod->producto.precio / aux->producto.stock;
aux1 = lisProductos;
aux->sig = aux1;
aux->ant = aux1->ant;
aux1->ant = aux;
lisProductos = aux;
}
}
else {
Lista aux, aux1;
aux = new (struct ListaProducto);
strcpy(aux->producto.nombre, auxprod->producto.nombre);
aux->producto.stock = auxprod->producto.stock;
aux->producto.precio = auxprod->producto.precio / aux->producto.stock;
aux->sig = aux->ant = NULL;
lisProductos = aux;
}
//Se elimina el producto de la lista de compras
if (auxprod->sig == NULL && auxprod->ant == NULL)
{
//printf("lista nula");
nuevaCompra(listaCompra);
}
else if (auxprod->ant == NULL)
{
//printf("1");
auxprod->sig->ant = NULL;
listaCompra = auxprod->sig;
}
else if (auxprod->sig == NULL)
{
//printf("2");
auxprod->ant->sig = NULL;
}
else if (auxprod->ant != NULL && auxprod->sig != NULL)
{
//printf("3");
auxprod->ant->sig = auxprod->sig;
auxprod->sig->ant = auxprod->ant;
}
}
//Devolver una cantidad de productos
if (op == 2)
{
printf("no");
system("PAUSE");
}
}
}
int validaCedula() {
//inicializacion de variables
int A[Tam], num, j, i, coc, pares, impares, digito, suma, sumtotal, res;
char opc;
int comprueba = 0, cedula;
do
{
i = 10;
pares = 0;
suma = 0;
impares = 0;
digito = 0;
sumtotal = 0;
num = validarIngresoNumeros("\nIngrese el numero de cedula:\t");
//scanf("%d",&num);
while ((num <= 1000000000) || (num >= 3000000000))
{
printf("Numero incorrecto. Ingrese cedula de nuevo:\t");
scanf("%d", &num);
}
//Asignación de cada numero a una posición
cedula = num;
do
{
coc = num / 10;
A[i] = num % 10;
i--;
num = coc;
} while (coc != 0);
pares += (A[2] + A[4] + A[6] + A[8]);
//printf("pares %d\n",pares);
for (j = 1; j<10; j++)
{
A[j] *= 2;
if (j % 2 == 0)
A[j] /= 2;
else
{
if (A[j]>9)
suma += A[j] - 9;
else
digito += A[j];
}
}
impares = suma + digito;
//printf("impares %d\n",impares);
sumtotal += impares + pares;
res = 10 - (sumtotal % 10);
A[1] *= 10;
A[0] = (A[1] / 2 + A[2]);
//printf("%d",A[0]);
if (res == 10)
res = 0;
if (res == A[10] && A[0] <= 24) {
printf("\n\t\tLa cedula es valida\n\n");
comprueba = 1;
}
else {
printf("\t\tLa cedula es invalida\n\n");
comprueba = 0;
}
} while ((comprueba == 0));
return cedula;
}
void generarQrBasico(char dato1[]) {
char *dato = dato1; // User-supplied text
enum qrcodegen_Ecc errCorLvl = qrcodegen_Ecc_LOW; // Error correction level
// Make and print the QR Code symbol
uint8_t qrcode[qrcodegen_BUFFER_LEN_MAX];
uint8_t tempBuffer[qrcodegen_BUFFER_LEN_MAX];
bool ok = qrcodegen_encodeText(dato, tempBuffer, qrcode, errCorLvl,
qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true);
if (ok)
printQr(qrcode);
}
static void printQr(const uint8_t qrcode[]) {
int size = qrcodegen_getSize(qrcode);
int border = 4;
for (int y = -border; y < size + border; y++) {
for (int x = -border; x < size + border; x++) {
fputs((qrcodegen_getModule(qrcode, x, y) ? "\333\333" : " "), stdout);
}
fputs("\n", stdout);
}
}
static void generarQr(char *mensaje)
{
printf("GENERADOR DE QR\n");
generarQrBasico(mensaje);
system("pause");
}
|
[
"cheshire18eros@gmail.com"
] |
cheshire18eros@gmail.com
|
a40b78e53bcb5d16ac5dd4fc44375829d1f9c9c4
|
2ded02bed0db431b80e918b41c644e66478f1c0a
|
/array/union_sorted_array.cpp
|
407328c508b4b606a09655b9ebaaa41bafb39c31
|
[] |
no_license
|
itsmegr/next-dsa
|
e73bbd373c8bfc0e93d84d2870849b764c11abdb
|
fa50875f3b7a77bf9bfb215c311c5d8a280c3f4e
|
refs/heads/master
| 2023-05-15T00:32:12.443113
| 2021-06-09T17:02:55
| 2021-06-09T17:02:55
| 325,457,327
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,197
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
#define fo(i,n) for(i=0;i<n;i++)
#define Fo(i,k,n) for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1)
#define ll long long
#define ull unsigned long long
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define pb push_back
#define mp make_pair
typedef pair<int, int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vpii;
typedef vector<pll> vpl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
void solve();
void takeArrayInput(int arr[], int n){
int i;
fo(i,n){
cin>>arr[i];
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t = 1;
cin >> t;
while(t--) {
solve();
}
return 0;
}
void solve()
{
int i, j, n, m;
cin>>n;
int* a = new int[n];
takeArrayInput(a, n);
cin>>m;
int* b = new int[m];
takeArrayInput(b,m);
if(a[0]>b[0]){
swap(a,b);
swap(m,n);
}
//this programme will also run for array containing duplicate elemenst
int count = 1, intersec = 0;
i=0;j=0;
while(i<n-1&&j<m){
if(a[i]!=a[i+1]){
count++;
if(b[j]>a[i]&&b[j]<a[i+1]){
count++;
j++;
}
else if(b[j]==a[i]||b[j]==a[i+1]){
j++;
if(b[j]!=b[j-1]) intersec++;
}
}
else{
if(b[j]==a[i]){
j++;
if(b[j]!=b[j-1]) intersec++;
}
}
deb2(i,j);
deb(count);
deb(intersec);
i++;
}
if(i==n-1){
while(j<m-1){
if(b[j]!=b[j+1]&&b[j]!=a[i]){
count++;
}
j++;
}
count++;
}
if(j==m){
i++;
while(i<n-1){
if(a[i]!=a[i+1]&&a[i]!=b[m-1]){
count++;
}
i++;
}
count++;
}
deb(count);
deb(intersec);
}
|
[
"unigovind@gmail.com"
] |
unigovind@gmail.com
|
2442c3ecbb03bbc84d0180304e82123b0a16c202
|
7f11317085d407d10b0e55c4b31bc81333a07eaa
|
/Codeforces/1191/d/d.cpp
|
b3602ede18875f802b723f552ca94b70a776b2d7
|
[] |
no_license
|
ericbrandwein/competencias
|
14116a1bc76e70a55ebebdc946679cd92cb8a3db
|
bf22b874646586ae7de573991fa932a2fa90e2c9
|
refs/heads/master
| 2023-05-03T09:51:26.100257
| 2021-05-30T16:18:08
| 2021-05-30T16:18:08
| 371,562,451
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,423
|
cpp
|
//#pragma GCC optimize("Ofast")
//#pragma GCC optimize("unroll-loops,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define endl '\n'
#define elif else if
#define ll long long int
#define ld long double
#define vec vector
#define forn(a) for(ll a=0; a<n; a++)
#define fore(a, v, n) for(ll a=v; a<n; a++)
#define all(x) x.begin(), x.end()
#define presicion(x) cout<<fixed<<setprecision(x)
#define dbg(x) cerr<<#x<<" = "<<x<<endl
#define PI 3.14159265358979323
#define sen(ang) sin((ang)*PI/180)
//cout<<flush;
using namespace std;
int main() {
IOS;
ll n;
cin >> n;
vec<ll> a(n);
ll suma = 0;
forn (i) {
cin >> a[i];
suma += a[i];
}
vec<string> jugadores = {"sjfnb", "cslnb"};
sort(all(a));
if (n >= 2 && a[0] == 0 && a[1] == 0) {
cout << jugadores[1] << endl;
return 0;
}
ll iguales = 1;
ll numero_igual = a[0];
fore (i, 1, n) {
if (a[i] == a[i-1]) {
iguales++;
numero_igual = a[i];
}
}
if (iguales > 2) {
cout << jugadores[1] << endl;
return 0;
}
fore (i, 0, n) {
if (a[i] == numero_igual - 1) {
cout << jugadores[1] << endl;
return 0;
}
}
ll escalera = (n-1) * n / 2;
ll restante = suma - escalera;
if (restante % 2 == 0) {
cout << jugadores[1] << endl;
} else {
cout << jugadores[0] << endl;
}
return 0;
}
|
[
"brandweineric@gmail.com"
] |
brandweineric@gmail.com
|
d408ca50bdb42bf173e87a6a271e041646a70101
|
ff25608db10343d007c5b6e3cdd1bbba72b49c23
|
/Tanoa_Life.Tanoa/The-Programmer/GPS/menu/gps_menu_map.hpp
|
3d8515074ac7a19b6fd3ce27f11890d3ee68c546
|
[] |
no_license
|
172644/FriendLife.Tanoa
|
f722b690dd35132e839d829dd3e7cfb62f8d5a12
|
cb1efc0ccefacd6abcb390c22813c881298091a4
|
refs/heads/master
| 2022-12-25T21:37:24.101175
| 2020-10-10T21:03:59
| 2020-10-10T21:03:59
| 289,088,357
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,324
|
hpp
|
/*
Author: Maxence Lyon
Altis DEV: https://altisdev.com/user/maxence-lyon
Teamspeak 3: ts.the-programmer.com
Web site: www.the-programmer.com
Steam: « Une Vache Sur CS – Maxence », please leave a message on my profile who says the exact reason before adding me.
Terms of use:
- This file is forbidden unless you have permission from the author. If you have this file without permission to use it please do not use it and do not share it.
- If you have permission to use this file, you can use it on your server however it is strictly forbidden to share it.
- Out of respect for the author please do not delete this information.
License number:
Server's name:
Owner's name:
*/
class gps_menu_map {
idd = 369853;
name = "gps_menu_map";
class controlsBackground
{
class Fond : A3GPS_RscPicture
{
text = "\Assets\Data\The-Programmer\GPS\menu\textures\gps_map.paa";
x = 0.2975 * safezoneW + safezoneX;
y = 0.155 * safezoneH + safezoneY;
w = 0.4 * safezoneW;
h = 0.7 * safezoneH;
idc = -1;
};
class map : A3GPS_RscMapControl
{
idc = 2201;
x = 0.3457 * safezoneW + safezoneX;
y = 0.342 * safezoneH + safezoneY;
w = 0.305 * safezoneW;
h = 0.32 * safezoneH;
};
};
class controls
{
class RscPicture_1208 : A3GPS_RscPicture
{
idc = 1205;
text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_L_ca.paa";
x = 0.689 * safezoneW + safezoneX;
y = 0.338 * safezoneH + safezoneY;
w = 0.0239062 * safezoneW;
h = 0.33 * safezoneH;
};
class RscPicture_1209 : A3GPS_RscPicture
{
idc = 1213;
text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_R_ca.paa";
x = 0.8261 * safezoneW + safezoneX;
y = 0.338 * safezoneH + safezoneY;
w = 0.0239062 * safezoneW;
h = 0.33 * safezoneH;
};
class RscPicture_1210 : A3GPS_RscPicture
{
idc = 1201;
text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_B_ca.paa";
x = 0.7075 * safezoneW + safezoneX;
y = 0.658 * safezoneH + safezoneY;
w = 0.1275 * safezoneW;
h = 0.051 * safezoneH;
};
class RscPicture_1211 : A3GPS_RscPicture
{
idc = 1208;
text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_BL_ca.paa";
x = 0.689 * safezoneW + safezoneX;
y = 0.658 * safezoneH + safezoneY;
w = 0.0239034 * safezoneW;
h = 0.051 * safezoneH;
};
class RscPicture_1212 : A3GPS_RscPicture
{
idc = 1212;
text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_BR_ca.paa";
x = 0.8261 * safezoneW + safezoneX;
y = 0.658 * safezoneH + safezoneY;
w = 0.0239034 * safezoneW;
h = 0.051 * safezoneH;
};
class RscPicture_1213 : A3GPS_RscPicture
{
idc = 1206;
text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_TL_ca.paa";
x = 0.689 * safezoneW + safezoneX;
y = 0.303 * safezoneH + safezoneY;
w = 0.0239034 * safezoneW;
h = 0.051 * safezoneH;
};
class RscPicture_1214 : A3GPS_RscPicture
{
idc = 1214;
text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_TR_ca.paa";
x = 0.8261 * safezoneW + safezoneX;
y = 0.303 * safezoneH + safezoneY;
w = 0.0239034 * safezoneW;
h = 0.051 * safezoneH;
};
class RscPicture_1215 : A3GPS_RscPicture
{
idc = 1215;
text = "\A3\ui_f\data\GUI\Rsc\RscMiniMapSmall\gps_T_ca.paa";
x = 0.703 * safezoneW + safezoneX;
y = 0.303 * safezoneH + safezoneY;
w = 0.1275 * safezoneW;
h = 0.051 * safezoneH;
};
class saved_paths : A3GPS_RscListBox
{
idc = 1500;
x = 0.7175 * safezoneW + safezoneX;
y = 0.363 * safezoneH + safezoneY;
w = 0.1 * safezoneW;
h = 0.2 * safezoneH;
};
class exec_saved : A3GPS_RscButton
{
idc = 1600;
x = 0.7175 * safezoneW + safezoneX;
y = 0.623 * safezoneH + safezoneY;
w = 0.103581 * safezoneW;
h = 0.035 * safezoneH;
};
class delete_saved : A3GPS_RscButton
{
idc = 1601;
x = 0.7175 * safezoneW + safezoneX;
y = 0.582 * safezoneH + safezoneY;
w = 0.103581 * safezoneW;
h = 0.035 * safezoneH;
};
class femer : A3GPS_RscbuttonMain
{
idc = 2403;
onbuttonclick = "closeDialog 0;";
x = 0.486301833333333 * safezoneW + safezoneX;
y = 0.636430678466076 * safezoneH + safezoneY;
w = 0.02 * safezoneW;
h = 0.02 * safezoneH;
animTextureDefault = "";
animTextureNormal = "";
animTextureDisabled = "";
animTextureOver = "";
animTextureFocused = "";
animTexturePressed = "";
text = "";
};
};
};
|
[
"azoxx.g@gmail.com"
] |
azoxx.g@gmail.com
|
b95f0a0598ccb5f1e0c5f92f6f1d99ec119ac348
|
77263106b3b07890763ae16c2b43b200480579ac
|
/ball trail/box.cpp
|
470f23390b23d740b584b74c62ce6ac0757ca76f
|
[] |
no_license
|
vivasvan1/tempballtrail
|
1f608f9453a7cb4f03abb470e296682b19e2a087
|
bfc00c95bcbf4570675fea734ede6307740c9ad0
|
refs/heads/master
| 2021-05-15T04:14:04.008632
| 2018-02-12T18:31:06
| 2018-02-12T18:31:06
| 119,888,572
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 345
|
cpp
|
#include "box.h"
Box::Box(const float width,const float height,const float depth,const std::string& fileName)
{
SetDepth(depth);
SetHeight(height);
}
Box::~Box()
{
//dtor
}
void Box::Draw(Box box)
{
// floor.Draw();
// ceil.Draw();
// left.Draw();
// right.Draw();
// endWall.Draw();
// frontWall.Draw();
}
|
[
"vivasvanpatel40@gmail.com"
] |
vivasvanpatel40@gmail.com
|
65635830a16978796b85593059886db4edac8ed2
|
9da42e04bdaebdf0193a78749a80c4e7bf76a6cc
|
/third_party/gecko-15/win32/include/nsIToolkitProfile.h
|
c0f0f24d7cf800dfcb237e90d564988c7f726f7d
|
[
"Apache-2.0"
] |
permissive
|
bwp/SeleniumWebDriver
|
9d49e6069881845e9c23fb5211a7e1b8959e2dcf
|
58221fbe59fcbbde9d9a033a95d45d576b422747
|
refs/heads/master
| 2021-01-22T21:32:50.541163
| 2012-11-09T16:19:48
| 2012-11-09T16:19:48
| 6,602,097
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,430
|
h
|
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/toolkit/profile/nsIToolkitProfile.idl
*/
#ifndef __gen_nsIToolkitProfile_h__
#define __gen_nsIToolkitProfile_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsILocalFile; /* forward declaration */
class nsIToolkitProfile; /* forward declaration */
class nsIProfileUnlocker; /* forward declaration */
/* starting interface: nsIProfileLock */
#define NS_IPROFILELOCK_IID_STR "7c58c703-d245-4864-8d75-9648ca4a6139"
#define NS_IPROFILELOCK_IID \
{0x7c58c703, 0xd245, 0x4864, \
{ 0x8d, 0x75, 0x96, 0x48, 0xca, 0x4a, 0x61, 0x39 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIProfileLock : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPROFILELOCK_IID)
/* readonly attribute nsILocalFile directory; */
NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) = 0;
/* readonly attribute nsILocalFile localDirectory; */
NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) = 0;
/* readonly attribute PRInt64 replacedLockTime; */
NS_SCRIPTABLE NS_IMETHOD GetReplacedLockTime(PRInt64 *aReplacedLockTime) = 0;
/* void unlock (); */
NS_SCRIPTABLE NS_IMETHOD Unlock(void) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIProfileLock, NS_IPROFILELOCK_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIPROFILELOCK \
NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory); \
NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory); \
NS_SCRIPTABLE NS_IMETHOD GetReplacedLockTime(PRInt64 *aReplacedLockTime); \
NS_SCRIPTABLE NS_IMETHOD Unlock(void);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIPROFILELOCK(_to) \
NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) { return _to GetDirectory(aDirectory); } \
NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) { return _to GetLocalDirectory(aLocalDirectory); } \
NS_SCRIPTABLE NS_IMETHOD GetReplacedLockTime(PRInt64 *aReplacedLockTime) { return _to GetReplacedLockTime(aReplacedLockTime); } \
NS_SCRIPTABLE NS_IMETHOD Unlock(void) { return _to Unlock(); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIPROFILELOCK(_to) \
NS_SCRIPTABLE NS_IMETHOD GetDirectory(nsILocalFile * *aDirectory) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetDirectory(aDirectory); } \
NS_SCRIPTABLE NS_IMETHOD GetLocalDirectory(nsILocalFile * *aLocalDirectory) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLocalDirectory(aLocalDirectory); } \
NS_SCRIPTABLE NS_IMETHOD GetReplacedLockTime(PRInt64 *aReplacedLockTime) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetReplacedLockTime(aReplacedLockTime); } \
NS_SCRIPTABLE NS_IMETHOD Unlock(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Unlock(); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsProfileLock : public nsIProfileLock
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROFILELOCK
nsProfileLock();
private:
~nsProfileLock();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsProfileLock, nsIProfileLock)
nsProfileLock::nsProfileLock()
{
/* member initializers and constructor code */
}
nsProfileLock::~nsProfileLock()
{
/* destructor code */
}
/* readonly attribute nsILocalFile directory; */
NS_IMETHODIMP nsProfileLock::GetDirectory(nsILocalFile * *aDirectory)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsILocalFile localDirectory; */
NS_IMETHODIMP nsProfileLock::GetLocalDirectory(nsILocalFile * *aLocalDirectory)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute PRInt64 replacedLockTime; */
NS_IMETHODIMP nsProfileLock::GetReplacedLockTime(PRInt64 *aReplacedLockTime)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void unlock (); */
NS_IMETHODIMP nsProfileLock::Unlock()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
/* starting interface: nsIToolkitProfile */
#define NS_ITOOLKITPROFILE_IID_STR "7422b090-4a86-4407-972e-75468a625388"
#define NS_ITOOLKITPROFILE_IID \
{0x7422b090, 0x4a86, 0x4407, \
{ 0x97, 0x2e, 0x75, 0x46, 0x8a, 0x62, 0x53, 0x88 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIToolkitProfile : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ITOOLKITPROFILE_IID)
/* readonly attribute nsILocalFile rootDir; */
NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) = 0;
/* readonly attribute nsILocalFile localDir; */
NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) = 0;
/* attribute AUTF8String name; */
NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) = 0;
NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) = 0;
/* void remove (in boolean removeFiles); */
NS_SCRIPTABLE NS_IMETHOD Remove(bool removeFiles) = 0;
/* nsIProfileLock lock (out nsIProfileUnlocker aUnlocker); */
NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIToolkitProfile, NS_ITOOLKITPROFILE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSITOOLKITPROFILE \
NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir); \
NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir); \
NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName); \
NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName); \
NS_SCRIPTABLE NS_IMETHOD Remove(bool removeFiles); \
NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSITOOLKITPROFILE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) { return _to GetRootDir(aRootDir); } \
NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) { return _to GetLocalDir(aLocalDir); } \
NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) { return _to GetName(aName); } \
NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) { return _to SetName(aName); } \
NS_SCRIPTABLE NS_IMETHOD Remove(bool removeFiles) { return _to Remove(removeFiles); } \
NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM) { return _to Lock(aUnlocker, _retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSITOOLKITPROFILE(_to) \
NS_SCRIPTABLE NS_IMETHOD GetRootDir(nsILocalFile * *aRootDir) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRootDir(aRootDir); } \
NS_SCRIPTABLE NS_IMETHOD GetLocalDir(nsILocalFile * *aLocalDir) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLocalDir(aLocalDir); } \
NS_SCRIPTABLE NS_IMETHOD GetName(nsACString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetName(aName); } \
NS_SCRIPTABLE NS_IMETHOD SetName(const nsACString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetName(aName); } \
NS_SCRIPTABLE NS_IMETHOD Remove(bool removeFiles) { return !_to ? NS_ERROR_NULL_POINTER : _to->Remove(removeFiles); } \
NS_SCRIPTABLE NS_IMETHOD Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Lock(aUnlocker, _retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsToolkitProfile : public nsIToolkitProfile
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSITOOLKITPROFILE
nsToolkitProfile();
private:
~nsToolkitProfile();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsToolkitProfile, nsIToolkitProfile)
nsToolkitProfile::nsToolkitProfile()
{
/* member initializers and constructor code */
}
nsToolkitProfile::~nsToolkitProfile()
{
/* destructor code */
}
/* readonly attribute nsILocalFile rootDir; */
NS_IMETHODIMP nsToolkitProfile::GetRootDir(nsILocalFile * *aRootDir)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsILocalFile localDir; */
NS_IMETHODIMP nsToolkitProfile::GetLocalDir(nsILocalFile * *aLocalDir)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute AUTF8String name; */
NS_IMETHODIMP nsToolkitProfile::GetName(nsACString & aName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsToolkitProfile::SetName(const nsACString & aName)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void remove (in boolean removeFiles); */
NS_IMETHODIMP nsToolkitProfile::Remove(bool removeFiles)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIProfileLock lock (out nsIProfileUnlocker aUnlocker); */
NS_IMETHODIMP nsToolkitProfile::Lock(nsIProfileUnlocker * *aUnlocker NS_OUTPARAM, nsIProfileLock * *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIToolkitProfile_h__ */
|
[
"haleokekahuna@gmail.com"
] |
haleokekahuna@gmail.com
|
844a9d6f44dc610d697bcdaf299fd020ae4fa5f5
|
4bcc9806152542ab43fc2cf47c499424f200896c
|
/tensorflow/lite/delegates/gpu/cl/kernels/space_to_depth_test.cc
|
17b32bcaecc7e59dca660c340a673480ac32b64d
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] |
permissive
|
tensorflow/tensorflow
|
906276dbafcc70a941026aa5dc50425ef71ee282
|
a7f3934a67900720af3d3b15389551483bee50b8
|
refs/heads/master
| 2023-08-25T04:24:41.611870
| 2023-08-25T04:06:24
| 2023-08-25T04:14:08
| 45,717,250
| 208,740
| 109,943
|
Apache-2.0
| 2023-09-14T20:55:50
| 2015-11-07T01:19:20
|
C++
|
UTF-8
|
C++
| false
| false
| 1,938
|
cc
|
/* Copyright 2020 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 <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/lite/delegates/gpu/cl/kernels/cl_test.h"
#include "tensorflow/lite/delegates/gpu/common/operations.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/tasks/space_to_depth_test_util.h"
namespace tflite {
namespace gpu {
namespace cl {
namespace {
// A known Qualcomm Adreno bug makes the 1 channel test fail on some Adreno
// 5xxs.
TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x2x2x1BlockSize2) {
ASSERT_OK(SpaceToDepthTensorShape1x2x2x1BlockSize2Test(&exec_env_));
}
TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x2x2x2BlockSize2) {
ASSERT_OK(SpaceToDepthTensorShape1x2x2x2BlockSize2Test(&exec_env_));
}
TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x2x2x3BlockSize2) {
ASSERT_OK(SpaceToDepthTensorShape1x2x2x3BlockSize2Test(&exec_env_));
}
TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x4x4x1BlockSize2) {
ASSERT_OK(SpaceToDepthTensorShape1x4x4x1BlockSize2Test(&exec_env_));
}
TEST_F(OpenCLOperationTest, SpaceToDepthTensorShape1x6x6x1BlockSize3) {
ASSERT_OK(SpaceToDepthTensorShape1x6x6x1BlockSize3Test(&exec_env_));
}
} // namespace
} // namespace cl
} // namespace gpu
} // namespace tflite
|
[
"gardener@tensorflow.org"
] |
gardener@tensorflow.org
|
7fae0103d14ec73e12e2b4e94f9dcf6e30b681b4
|
2abc848023b0701b0a1c66b53a29938f6819a6dd
|
/Aula-01/Tarefa-01/Tarefa-01.ino
|
82d7796dd8502be46898d7f0d8634d81cafa5563
|
[
"MIT"
] |
permissive
|
thiagola92/PUC-INF1805
|
1e2fe76994ea9fe902fa20407544c10c7d2598bb
|
8d5b022f97181c698fa6607b3aecb672fe95b1eb
|
refs/heads/master
| 2021-06-25T22:35:36.001266
| 2020-01-24T04:57:51
| 2020-01-24T04:57:51
| 124,196,700
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,348
|
ino
|
#define LED_PIN 13
#define KEY1 A1
#define KEY2 A2
#define KEY3 A3
int state = 1;
float delayTime = 1000;
unsigned long old;
int but1pressed;
int but2pressed;
int but1delay = 1000;
int but2delay = 1000;
unsigned long but1old;
unsigned long but2old;
void setup() {
// put your setup code here, to run once:
pinMode(LED_PIN, OUTPUT);
pinMode(KEY1, INPUT_PULLUP);
pinMode(KEY2, INPUT_PULLUP);
pinMode(KEY3, INPUT_PULLUP);
Serial.begin(9600);
but1pressed = 1000 + millis();
but2pressed = millis();
}
void loop() {
// put your main code here, to run repeatedly:
unsigned long now = millis();
int but1 = digitalRead(KEY1);
int but2 = digitalRead(KEY2);
int but3 = digitalRead(KEY3);
if((now >= but1old + but1delay) && (but1 == 0)){
delayTime /= 2.0;
but1pressed = now;
Serial.print('a');
Serial.print(delayTime);
Serial.print('\n');
but1old = now;
}
if((now >= but2old + but2delay) && (but2 == 0)){
delayTime *= 2;
but2pressed = now;
Serial.print('b');
Serial.print(delayTime);
Serial.print('\n');
but2old = now;
}
if (now >= old + delayTime){
old = now;
state = !state;
digitalWrite(LED_PIN, state);
}
int interval = abs(but1pressed - but2pressed);
//Serial.println(interval);
if(interval <= 500){
while(1);
}
}
|
[
"thiagola92@gmail.com"
] |
thiagola92@gmail.com
|
824d50a5a1a74e3339f7f3b167e15a8ee569caa2
|
349ca5e14381a74d7d1e0fe542a0d62c664ca2da
|
/c++/Study1/Study1/CTest1.h
|
5595412c4a53a49197552463ededff0f1846b153
|
[] |
no_license
|
somnisfelix/work
|
a4994c3a7b6409e3e954d0ed5b473f202288caaf
|
57af7c092faf2d1c2cfa5e33655908ceb4346dc1
|
refs/heads/master
| 2020-07-27T10:59:05.985251
| 2020-01-07T01:59:39
| 2020-01-07T01:59:39
| 209,066,492
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 782
|
h
|
#pragma once
class CTest1
{
public:
CTest1();
virtual ~CTest1();
public:
void ConstTest1(const int number)
{
//number = 100; // 에러 매개변수에 const가 있으므로
m_nTestNumber = 20;
}
void ConstTest2(int number) const
{
number = 100;
//m_nTestNumber = 20; // 에러 함수선언 뒤에 const가 붙었으므로
//int test = ConstTest3(20);
//test = 200;
}
const int GetNumber()
{
return m_nTestNumber;
}
public:
// 순수 가상함수 상속시 구현해줘야한다.
virtual void ChildTest() = 0;
virtual void ChildTest2()
{
m_nTestNumber = 200;
}
protected:
int m_nTestNumber;
};
class CTestChild : public CTest1
{
public:
CTestChild();
virtual ~CTestChild();
public:
virtual void ChildTest()
{
m_nTestNumber = 20;
}
};
|
[
"somnisfelix@naver.com"
] |
somnisfelix@naver.com
|
21d815d9c686ea95921031d8fe2066005f2a5422
|
c583a5fd60d8497c82c2864e5dec2d1b0853f3b1
|
/0092-Reverse_Linked_List_II/main.cpp
|
c418ead103c018884aa2896c25fb9557c21b2957
|
[] |
no_license
|
oliver-zeng/leetcode
|
401c9455c73cfe198b1d947407596aaa4d61f6fe
|
d98fbefb9c6fc0dc78da3cfabf7906f3fa712102
|
refs/heads/master
| 2020-12-19T19:17:45.522346
| 2020-06-04T12:25:03
| 2020-06-04T12:25:03
| 235,826,235
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,022
|
cpp
|
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createListNode(int arr[], int sz) {
if (sz == 0)
return NULL;
ListNode* head = new ListNode(arr[0]);
ListNode* cur = head;
for (int i = 1; i < sz; i++) {
cur->next = new ListNode(arr[i]);
cur = cur->next;
}
return head;
}
void printListNode(ListNode* head) {
ListNode* p = head;
while(p) {
cout << p->val << " -> ";
p = p->next;
}
cout << "null" << endl;
return;
}
class Solution {
private:
bool g_debug = false;
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
// 建立哨兵节点,里面的value随意写一个,能调用构造就行
ListNode* dummyHead = new ListNode(-1);
dummyHead->next = head;
// 找到m-1与m节点
ListNode* mPrev = dummyHead;
ListNode* mNode;
for (int i = 0; i < m - 1; i++, mPrev = mPrev->next);
mNode = mPrev->next;
if (g_debug)
cout << "mPrev " << mPrev->val << " mNode " << mNode->val << endl;
// 逆转从[m, n]的节点
// 逆转完成,prev是节点n,cur是节点n+1
int times = n - m + 1;
ListNode* prev = mPrev;
ListNode* cur = mNode;
ListNode* next;
while(times--) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
// mPrev -> [n, m] -> n + 1
mPrev->next = prev;
mNode->next = cur;
// 释放哨兵节点
head = dummyHead->next;
delete dummyHead;
return head;
}
};
int main() {
int m = 2, n = 4;
int arr[] = { 1,2,3,4,5 };
//int m = 1, n = 1;
//int arr[] = { 5 };
ListNode* p = createListNode(arr, sizeof(arr)/sizeof(int));
printListNode(p);
Solution().reverseBetween(p, m, n);
printListNode(p);
return 0;
}
|
[
"964994927@qq.com"
] |
964994927@qq.com
|
d1f1a335cda6b2fecd64ce254996e08f8219665b
|
5ec06dab1409d790496ce082dacb321392b32fe9
|
/clients/cpp-restsdk/generated/model/ComAdobeGraniteLicenseImplLicenseCheckFilterProperties.h
|
b697353f2d529559a4bdfbe1cffc3fc696309055
|
[
"Apache-2.0"
] |
permissive
|
shinesolutions/swagger-aem-osgi
|
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
|
c2f6e076971d2592c1cbd3f70695c679e807396b
|
refs/heads/master
| 2022-10-29T13:07:40.422092
| 2021-04-09T07:46:03
| 2021-04-09T07:46:03
| 190,217,155
| 3
| 3
|
Apache-2.0
| 2022-10-05T03:26:20
| 2019-06-04T14:23:28
| null |
UTF-8
|
C++
| false
| false
| 2,890
|
h
|
/**
* Adobe Experience Manager OSGI config (AEM) API
* Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API
*
* OpenAPI spec version: 1.0.0-pre.0
* Contact: opensource@shinesolutions.com
*
* NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/*
* ComAdobeGraniteLicenseImplLicenseCheckFilterProperties.h
*
*
*/
#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteLicenseImplLicenseCheckFilterProperties_H_
#define ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteLicenseImplLicenseCheckFilterProperties_H_
#include "../ModelBase.h"
#include "ConfigNodePropertyBoolean.h"
#include "ConfigNodePropertyInteger.h"
#include "ConfigNodePropertyArray.h"
namespace org {
namespace openapitools {
namespace client {
namespace model {
/// <summary>
///
/// </summary>
class ComAdobeGraniteLicenseImplLicenseCheckFilterProperties
: public ModelBase
{
public:
ComAdobeGraniteLicenseImplLicenseCheckFilterProperties();
virtual ~ComAdobeGraniteLicenseImplLicenseCheckFilterProperties();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
void fromJson(web::json::value& json) override;
void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override;
void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override;
/////////////////////////////////////////////
/// ComAdobeGraniteLicenseImplLicenseCheckFilterProperties members
/// <summary>
///
/// </summary>
std::shared_ptr<ConfigNodePropertyInteger> getCheckInternval() const;
bool checkInternvalIsSet() const;
void unsetCheckInternval();
void setCheckInternval(std::shared_ptr<ConfigNodePropertyInteger> value);
/// <summary>
///
/// </summary>
std::shared_ptr<ConfigNodePropertyArray> getExcludeIds() const;
bool excludeIdsIsSet() const;
void unsetExcludeIds();
void setExcludeIds(std::shared_ptr<ConfigNodePropertyArray> value);
/// <summary>
///
/// </summary>
std::shared_ptr<ConfigNodePropertyBoolean> getEncryptPing() const;
bool encryptPingIsSet() const;
void unsetEncryptPing();
void setEncryptPing(std::shared_ptr<ConfigNodePropertyBoolean> value);
protected:
std::shared_ptr<ConfigNodePropertyInteger> m_CheckInternval;
bool m_CheckInternvalIsSet;
std::shared_ptr<ConfigNodePropertyArray> m_ExcludeIds;
bool m_ExcludeIdsIsSet;
std::shared_ptr<ConfigNodePropertyBoolean> m_EncryptPing;
bool m_EncryptPingIsSet;
};
}
}
}
}
#endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_ComAdobeGraniteLicenseImplLicenseCheckFilterProperties_H_ */
|
[
"cliffano@gmail.com"
] |
cliffano@gmail.com
|
92eb27a94c553af8a00cd7466823db317e7ac020
|
b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1
|
/C++ code/HDU Online Judge/4605(2).cpp
|
de7a0b735e3e27b9cf016ee47a97d7c63762f084
|
[] |
no_license
|
fsps60312/old-C-code
|
5d0ffa0796dde5ab04c839e1dc786267b67de902
|
b4be562c873afe9eacb45ab14f61c15b7115fc07
|
refs/heads/master
| 2022-11-30T10:55:25.587197
| 2017-06-03T16:23:03
| 2017-06-03T16:23:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,639
|
cpp
|
#include<cstdio>
#include<cassert>
#include<vector>
#include<set>
using namespace std;
const int INF=2147483647;
int Rand()
{
static unsigned int seed=20160221;
seed*=0xdefaced,seed+=115216;
return (seed+=seed>>20)&0x7fffffff;
}
static int Node_COUNTER=0;
struct Node
{
Node *ch[2];
const int x;
int sz;
int cnt7,cnt2;
int tag7,tag2;
int ref;
Node(const int _x):ch{NULL,NULL},x(_x),sz(1),cnt7(),cnt2(),tag7(),tag2(),ref(0)
{
Node_COUNTER++;
}
Node(Node *o):ch{o->ch[0],o->ch[1]},x(o->x),sz(o->sz),cnt7(o->cnt7),cnt2(o->cnt2),tag7(o->tag7),tag2(o->tag2),ref(0)
{
Node_COUNTER++;
for(int d=0;d<2;d++)if(ch[d])ch[d]->ref++;
}
~Node(){Node_COUNTER--;}
void Add(const int v7,const int v2)
{
if(cnt7==-1)return;
cnt7+=v7,cnt2+=v2;
tag7+=v7,tag2+=v2;
}
};
void Assign(Node* &o,Node *v)
{
if(v)v->ref++;
if(o&&!--o->ref)
{
for(int d=0;d<2;d++)Assign(o->ch[d],NULL);
delete o;
}
o=v;
}
void PutDown(Node *o)
{
assert(o);
if(!o->tag7&&!o->tag2)return;
for(int d=0;d<2;d++)if(o->ch[d])
{
Assign(o->ch[d],new Node(o->ch[d]));
o->ch[d]->Add(o->tag7,o->tag2);
}
o->tag7=o->tag2=0;
}
int Sz(Node *o){return o?o->sz:0;}
void Maintain(Node *o){o->sz=Sz(o->ch[0])+1+Sz(o->ch[1]);}
void Merge(Node* &o,Node *a,Node *b)
{
if(a)a=new Node(a),a->ref++;
if(b)b=new Node(b),b->ref++;
if(!a||!b)Assign(o,a?a:b);
else if(Rand()%(a->sz+b->sz)<a->sz)
{
Assign(o,a);
PutDown(o);
Merge(o->ch[1],o->ch[1],b);
Maintain(o);
}
else
{
Assign(o,b);
PutDown(o);
Merge(o->ch[0],a,o->ch[0]);
Maintain(o);
}
Assign(a,NULL),Assign(b,NULL);
}
void Split(Node *o,Node* &a,Node* &b,const int x)
{
if(o)o=new Node(o),o->ref++;
if(!o)Assign(a,NULL),Assign(b,NULL);
else if((o->x)<=x)
{
Assign(a,o);
PutDown(a);
Split(a->ch[1],a->ch[1],b,x);
Maintain(a);
}
else
{
Assign(b,o);
PutDown(b);
Split(b->ch[0],a,b->ch[0],x);
Maintain(b);
}
Assign(o,NULL);
}
void Query(Node *o,const int x,int &cnt7,int &cnt2)
{
if(!o)return;
PutDown(o);
if(x<=(o->x))
{
cnt7=o->cnt7,cnt2=o->cnt2;
Query(o->ch[0],x,cnt7,cnt2);
}
else Query(o->ch[1],x,cnt7,cnt2);
}
Node *S[100000];
int N,W[100000];
vector<int>ET[100000];
void BuildTree(const int u)
{
// printf("u=%d\n",u);
if(ET[u].empty())return;
assert((int)ET[u].size()==2);
for(int d=0;d<2;d++)
{
Node *a=NULL,*b=NULL,*c=NULL;
Split(S[u],b,c,W[u]);
Split(b,a,b,W[u]-1);
assert(a&&c);
a->Add(0,1),b->cnt7=-1,c->Add(d,3);
Merge(b,b,c);
Merge(S[ET[u][d]],a,b);
Assign(a,NULL),Assign(b,NULL),Assign(c,NULL);
BuildTree(ET[u][d]);
}
}
void Merge(Node* &o,const int x)
{
Node *n=NULL;
Assign(n,new Node(x));
Merge(o,o,n);
Assign(n,NULL);
}
int main()
{
// freopen("in.txt","r",stdin);
for(int i=0;i<100000;i++)S[i]=NULL;
int testcount;scanf("%d",&testcount);
while(testcount--)
{
scanf("%d",&N);
for(int i=0;i<N;i++)ET[i].clear();
for(int i=0;i<N;i++)scanf("%d",&W[i]);
if(true)
{
int m;scanf("%d",&m);
for(int u,a,b;m--;)
{
scanf("%d%d%d",&u,&a,&b),u--,a--,b--;
ET[u].push_back(a),ET[u].push_back(b);
}
}
if(true)
{
set<int>tmp;
for(int i=0;i<N;i++)tmp.insert(W[i]-1),tmp.insert(W[i]);
Assign(S[0],NULL);
for(const int v:tmp)Merge(S[0],v);
Merge(S[0],INF);
}
BuildTree(0);
int querycount;scanf("%d",&querycount);
for(int v,x,cnt7,cnt2;querycount--;)
{
scanf("%d%d",&v,&x),v--;
Query(S[v],x,cnt7,cnt2);
if(cnt7==-1)puts("0");
else printf("%d %d\n",cnt7,cnt2);
}
}
// printf("Node_COUNTER=%d\n",Node_COUNTER);
// for(int i=0;i<100000;i++)Assign(S[i],NULL);
// printf("Node_COUNTER=%d\n",Node_COUNTER);
// assert(Node_COUNTER==0);
return 0;
}
|
[
"fsps60312@yahoo.com.tw"
] |
fsps60312@yahoo.com.tw
|
8901c7b0a6522c3bafbf3f2c7233c4b075942a78
|
b7ef6ad95ba4479255abe0e995b4f3928245223b
|
/myEngine/eGameObject.cpp
|
ed3dd731ddd75c8b462e24818759d236bb46ff17
|
[] |
no_license
|
jelcic/SpaceHero
|
2cdfd44115675a87b6cd63badeba21a9da4ecb8f
|
dcddedaaffd17b86c7309f1e2ce72cb56122ce45
|
refs/heads/master
| 2020-04-29T00:45:41.836522
| 2019-03-18T21:01:45
| 2019-03-18T21:01:45
| 175,096,326
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,479
|
cpp
|
#include "eGameObject.h"
#include "Director.h"
namespace Engine
{
eGameObject::eGameObject(int Zorder)
: zOrder(Zorder) {}
eGameObject::~eGameObject() { }
void eGameObject::Init()
{
init();
}
void eGameObject::Update(float dt)
{
update(dt);
if (collider)
collider->Update(Angle);
}
void eGameObject::Draw()
{
draw();
if (collider)
collider->Draw();
}
void eGameObject::SetAnchorPoint(Vec2 anchorPoint)
{
AnchorPoint = anchorPoint;
}
void eGameObject::SetGameObjectScale(float scale)
{
this->scale = scale;
}
void eGameObject::SetRotationCenter(float x, float y)
{
rotationCenter.X = x;
rotationCenter.Y = y;
}
void eGameObject::AddCollider(Engine::eCollider * _collider)
{
if (collider)
delete collider;
collider = _collider;
collide = true;
}
void eGameObject::DrawCollider(bool draw)
{
if(collider)
collider->ShowCollider(draw);
}
Engine::eCollider * eGameObject::GetCollider()
{
return collider;
}
Size eGameObject::GetObjectSize()
{
return objectSize;
}
Vec2& eGameObject::GetPosition()
{
return Position;
}
Vec2 eGameObject::GetRotationCenter()
{
return rotationCenter;
}
void eGameObject::_setPosition(Vec2 newPosition)
{
Position = newPosition;
}
void eGameObject::Collision(eGameObject * secondObject) { }
void eGameObject::SetObjectSize(int width, int height)
{
objectSize.Width = width;
objectSize.Height = height;
}
eGameObject::eGameObject() {}
}
|
[
"marko.jelcic@gmail.com"
] |
marko.jelcic@gmail.com
|
6eafc91e8b8083415befe6df065c6c0926d9bac2
|
133d0f38b3da2c51bf52bcdfa11d62978b94d031
|
/testAutocad/vendor/objectArx/inc/oleaprot.h
|
d44996624c03dfd45289b7b09a929ba3b15baae0
|
[] |
no_license
|
Aligon42/ImportIFC
|
850404f1e1addf848e976b0351d9e217a72f868a
|
594001fc0942d356eb0d0472c959195151510493
|
refs/heads/master
| 2023-08-15T08:00:14.056542
| 2021-07-05T13:49:28
| 2021-07-05T13:49:28
| 361,410,709
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,772
|
h
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef OLEAUTO_H
#define OLEAUTO_H
#include "adesk.h"
#include "acdbport.h"
#ifdef _ADESK_WINDOWS_
#include "dbmain.h"
#pragma pack (push, 8)
//
// AcAxOleLinkManager is used to maintain the link between an ARX
// objects and their respective COM wrapper.
//
class ADESK_NO_VTABLE AcAxOleLinkManager
{
public:
// Given a pointer to a database resident object, return
// the IUnknown of the COM wrapper. NULL is returned if
// no wrapper is found.
virtual IUnknown* GetIUnknown(AcDbObject* pObject) = 0;
// Set the link between a database resident object and a
// COM wrapper. If the IUnknown is NULL, then the link is removed.
virtual Adesk::Boolean SetIUnknown(AcDbObject* pObject, IUnknown* pUnknown) = 0;
// Given a pointer to a database object, return
// the IUnknown of the COM wrapper. NULL is returned if
// no wrapper is found.
virtual IUnknown* GetIUnknown(AcDbDatabase* pDatabase) = 0;
// Set the link between a database object and a COM wrapper.
// If the IUnknown is NULL, then the link is removed.
virtual Adesk::Boolean SetIUnknown(AcDbDatabase* pDatabase, IUnknown* pUnknown) = 0;
// Given a pointer to a database object, return the
// IDispatch of then document object. NULL is returned if
// the database does not belong to a particular document.
virtual IDispatch* GetDocIDispatch(AcDbDatabase* pDatabase) = 0;
// Set the link between a database object and the IDispatch
// of the document it belongs to. If the IDispatch is NULL, then
// the link is removed.
virtual Adesk::Boolean SetDocIDispatch(AcDbDatabase* pDatabase, IDispatch* pDispatch) = 0;
// Given a pointer to a database resident object and a subentID, return
// the IUnknown of the COM wrapper. NULL is returned if
// no wrapper is found.
virtual IUnknown* GetIUnknown(AcDbObject* pObject,
const AcDbSubentId &id) = 0;
// Set the link between a database resident object, a subentID and a
// COM wrapper. If the IUnknown is NULL, then the link is removed.
virtual Adesk::Boolean SetIUnknown(AcDbObject* pObject,
const AcDbSubentId &id, IUnknown* pUnknown) = 0;
};
ACDB_PORT AcAxOleLinkManager* AcAxGetOleLinkManager();
#pragma pack (pop)
#endif //_ADESK_WINDOWS_
#endif // OLEAUTO_H
|
[
"antoine.cacheux@procal.fr"
] |
antoine.cacheux@procal.fr
|
90adc2873bb8bc9aa197434fd3e11f4e837b1efd
|
c6380fd22ed0075558202336657f2dd9bce9c336
|
/state-machine/StateMachine.cpp
|
6e368fd9b212472188707a0af76422c45300024b
|
[
"MIT"
] |
permissive
|
fivunlm/statemachine
|
ec51ddbb67d3022690164373c97fe73c85d09974
|
0a00b32499f748ed80d66709b1745d9318231c07
|
refs/heads/master
| 2021-06-07T20:54:07.061897
| 2016-10-25T14:33:34
| 2016-10-25T14:33:34
| 56,595,646
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,315
|
cpp
|
//
// Created by FernandoDamian on 4/19/2016.
//
#include <assert.h>
#include <cstdio>
#include "StateMachine.h"
#include "EventData.h"
StateMachine::StateMachine(int maxStates, int initialState) :
m_maxStates( maxStates ),
m_currentState(initialState),
m_eventGenerated(0),
m_pEventData(NULL)
{
}
void StateMachine::ExternalEvent(int newState, EventData * pData)
{
if( newState == EVENT_IGNORED)
{
if( pData ) {
delete pData;
pData = NULL;
}
}
else
{
InternalEvent(newState, pData);
StateEngine();
}
}
void StateMachine::InternalEvent(int newState, EventData * pData)
{
if( pData == NULL)
pData = new EventData();
m_pEventData = pData;
m_eventGenerated = true;
m_currentState = newState;
}
void StateMachine::StateEngine()
{
EventData* pDataTemp = NULL;
while( m_eventGenerated )
{
pDataTemp = m_pEventData;
m_pEventData = NULL;
m_eventGenerated = false;
assert(m_currentState < m_maxStates);
const StateStruct * pStateMap = GetStateMap();
(this->*pStateMap[m_currentState].pStateFunc)(pDataTemp);
if(pDataTemp)
{
delete pDataTemp;
pDataTemp = NULL;
}
}
}
|
[
"lopez.fernando.damian@gmail.com"
] |
lopez.fernando.damian@gmail.com
|
70d51d0247f9d91f874a7a380f149e7048f302d8
|
36d5bc47dd874e52e8aeb2de56be32c40966d5f6
|
/Lab 3/inputValidation.cpp
|
4d46b574969a5c5f30c4ff2bc015ef4a0781018f
|
[] |
no_license
|
esotericwarrior/CS162
|
cb95b1d6e65ebcac31b6bf6e9e2379409f5285ff
|
91efc8e4fc4ffc486b709991436fef7a080775f2
|
refs/heads/master
| 2020-03-17T12:27:18.666545
| 2018-11-01T17:15:10
| 2018-11-01T17:15:10
| 133,588,967
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,199
|
cpp
|
/********************************************************************
** Program name: warGame *
** Author: Tristan Santiago *
** Date: January 28, 2018 *
** Description: lines 13-45 are case validating. *
** lines 47-77 are > 1 and < 91 integer validating. *
********************************************************************/
#include "inputValidation.hpp"
#include <iostream>
using namespace std;
double menuValidation(double anything) // make sure numbers coming in are initialized as doubles
{
bool check = true;
while(check == true) //Begins infinite loop that will only break if an integer of 1 or 2. https://www.hackerearth.com/practice/notes/validating-user-input-in-c/
{
if(cin.fail()) //if not an integer:
{
cin.clear(); // clears the error flag on cin. https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input
cin.ignore(100, '\n'); // skips to the next newline, and skips 100 characters
cout << "Please enter an integer, either 1 or 2." << endl; // asks for input again
cin >> anything;
}
if(!cin.fail() && (anything == 1 || anything == 2)) // If valid input:
{
check = false;
return anything;
}
else // if an integer, but not a 2 or 3:
{
cin.clear();
cin.ignore(100, '\n');
cout << "Please enter a 1 or a 2."<<endl;
cin >> anything;
}
}
}
double integerValidation(double intValidate)
{
bool check = true;
//cout << "Please enter a number greater than one." << endl; // edited to be greater than 1, rather than 0
//cin >> intValidate;
while(check == true)
{
if(cin.fail()) //if not an integer:
{
cin.clear(); // clears the error flag on cin. https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input
cin.ignore(100, '\n'); // skips to the next newline, and skips 100 characters
cout << "Please enter an integer." << endl; // asks for input again
cin >> intValidate;
}
if (!cin.fail() && (intValidate > 1 && intValidate < 91)) // greater than 1, not zero
{
check = false;
return intValidate;
}
else
{
cin.clear();
cin.ignore(100, '\n');
cout << "Please enter a number greater than 1 and less than 90."<<endl;
cin >> intValidate;
}
}
}
double menu4Validation(int validate) // make sure numbers coming in are initialized as doubles
{
//int validate;
while(1) //Begins infinite loop that will only break if an integer of 1 or 2. https://www.hackerearth.com/practice/notes/validating-user-input-in-c/
{
if(cin.fail()) // if not an integer:
{
cin.clear(); // clears the error flag on cin. https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input
cin.ignore(100, '\n'); // skips to the next newline, and skips 100 characters
cout << "Please enter a valid option." << endl; // asks for input again
cin >> validate;
// cout << "Not an integer catch: " << validate << endl; -- test cout
}
if(!cin.fail() && (validate == 1 || validate == 2 || validate == 3 || validate == 4)) // If valid input:
// if(!cin.fail() && (0 < validate < 5)) // If valid input:
{ // cout << validate << endl; -- test cout
return validate; // then break loop.
break;
}
else // if an integer, but not a valid option
{
cin.clear();
cin.ignore(100, '\n');
cout << "Invalid option."<<endl;
cin >> validate;
// cout << "Not correct integer catch: " << validate << endl; -- test cout
}
}
}
// double arrayValidation(double rowValidate, double colValidate) // expecting rows/columns to be passed here
// {
// bool check = true;
// int row, col;
// while (trueCheck1 == true)
// {
// cout << "Enter the row number (starting at row 1)" << endl;
// cin >> row;
// if (row <= rowValidate && row > 0)
// {
// row = row - 1;
// trueCheck1 = false;
// }
// else
// {
// cout << "Starting row position must be within the given number of rows! " << endl;
// cin.clear();
// cin.ignore();
// }
// }
// while (trueCheck1 == false)
// {
// cout << "Enter the column number (starting at column 1)" << endl;
// cin >> col;
// if (col <= colValidate && col > 0)
// {
// col = col - 1;
// trueCheck1 = true;
// }
// else
// {
// cout << "Starting column position must be within the given number of columns! " << endl;
// cin.clear();
// cin.ignore();
// }
// }
// trueCheck2 = false;
// return row;
// return col;
// }
|
[
"37146990+esotericwarrior@users.noreply.github.com"
] |
37146990+esotericwarrior@users.noreply.github.com
|
b2caacb547c190a44baa155dbce19a2c6fd1287f
|
28f713d1558fdd2ff1d2f4b0900077af3d4f4d43
|
/cs233/satwiks2/Lab12/cacheblock.cpp
|
83749842391f291314577efcd70390a1e1a63542
|
[] |
no_license
|
itsmesatwik/uiuc_2021
|
10fe39a80c4a1e8a48886d6b89a7d15eaa5048e4
|
55aaacdf33fd84f51cb2f5631ee24ceb98afcd95
|
refs/heads/master
| 2023-04-11T06:03:35.701127
| 2021-04-26T19:40:42
| 2021-04-26T19:40:42
| 360,992,113
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 291
|
cpp
|
#include "cacheblock.h"
uint32_t Cache::Block::get_address() const {
auto index = _cache_config.get_num_index_bits();
auto tag = _cache_config.get_num_tag_bits();
auto offset = 32 - tag - index;
return (tag == 32) ? _tag : (_tag << (index + offset)) + (_index << offset);
}
|
[
"satwik.illini@gmail.com"
] |
satwik.illini@gmail.com
|
4dadd57910714d41bb996d845225e7a9767e97e7
|
d80ec9a928ff228cc99f8112254b6c9b449e097d
|
/Game/main.cpp
|
c47857b47e3d03c04bec06f7ff9c68d651de4e5b
|
[] |
no_license
|
The-Team-7/The-KU-Journey
|
47a371dca693d3ecae779864ce666a7b9ea5925d
|
b8a3aa5ad85f414c1363d3afa7c8d8445fc2e926
|
refs/heads/master
| 2020-03-20T21:43:56.470370
| 2018-07-04T02:21:12
| 2018-07-04T02:21:12
| 137,756,919
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 139
|
cpp
|
#include<SFML/Graphics.hpp>
#include"Game.h"
#include "DEFINITIONS.h"
int main() {
sg::Game(1920, 1080, "The KU Journey");
return 0;
}
|
[
"sbijay777@gmail.com"
] |
sbijay777@gmail.com
|
ce00f8ca5290e109c1ebe991232b65040ba07b06
|
c4050611b5cc5f8b58ecdcb6c78b9cbe294c3da1
|
/source/math/math.hpp
|
ee2d1633ed162a99cee85946d5df51c9a4805d09
|
[] |
no_license
|
RenatoUtsch/boids
|
138ec06718fb0d62ddbfcb6fe34e0f9945abd07c
|
b23af256d2c7b847d2c63fe35df13b961a33f117
|
refs/heads/master
| 2021-01-20T11:14:16.350095
| 2014-11-30T21:20:47
| 2014-11-30T21:20:47
| 27,350,294
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,833
|
hpp
|
/*
* Math library intended for computer graphics, animation, physics and games
* (but not restricted to it).
*
* Copyright (c) 2014 Renato Utsch <renatoutsch@gmail.com>
*
* 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.
*/
#ifndef MATH_MATH_HPP
#define MATH_MATH_HPP
/**
* Proper inclusion of the standard math library and definition of additional
* types in case they are missing.
* Please use this header instead of including <cmath>.
**/
#include <cmath>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif // !M_PI
/**
* Converts from degrees to radians.
**/
inline double toRads(double degrees) {
return degrees * (M_PI / 180.0);
}
/**
* Converts from radians to degrees.
**/
inline double toDegrees(double rads) {
return rads * (180.0 / M_PI);
}
#endif // !MATH_MATH_HPP
|
[
"renatoutsch@gmail.com"
] |
renatoutsch@gmail.com
|
3e22a61c4bc4645cd12aa633e270d42cc0a54cd5
|
6c13991a694cd4ab5320c5bf79bab0e9d392e354
|
/envoy/source/common/protobuf/utility.cc
|
f2c94278313fca82213637bd6e7b14b994780d50
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
bdecoste/upstream-envoy-openssl
|
4cac1ac3df194f0896bb79db2813f0c8db14e8ca
|
f2bd116a9dd1f7da8ba00b6d473607190fdb0b2c
|
refs/heads/master
| 2022-10-13T08:05:35.704119
| 2019-10-11T22:11:24
| 2019-10-11T22:11:24
| 208,906,237
| 0
| 0
|
Apache-2.0
| 2022-09-23T22:28:25
| 2019-09-16T22:04:09
|
C++
|
UTF-8
|
C++
| false
| false
| 17,618
|
cc
|
#include "common/protobuf/utility.h"
#include <numeric>
#include "envoy/protobuf/message_validator.h"
#include "common/common/assert.h"
#include "common/common/fmt.h"
#include "common/json/json_loader.h"
#include "common/protobuf/message_validator_impl.h"
#include "common/protobuf/protobuf.h"
#include "absl/strings/match.h"
#include "yaml-cpp/yaml.h"
namespace Envoy {
namespace {
absl::string_view filenameFromPath(absl::string_view full_path) {
size_t index = full_path.rfind("/");
if (index == std::string::npos || index == full_path.size()) {
return full_path;
}
return full_path.substr(index + 1, full_path.size());
}
void blockFormat(YAML::Node node) {
node.SetStyle(YAML::EmitterStyle::Block);
if (node.Type() == YAML::NodeType::Sequence) {
for (auto it : node) {
blockFormat(it);
}
}
if (node.Type() == YAML::NodeType::Map) {
for (auto it : node) {
blockFormat(it.second);
}
}
}
} // namespace
namespace ProtobufPercentHelper {
uint64_t checkAndReturnDefault(uint64_t default_value, uint64_t max_value) {
ASSERT(default_value <= max_value);
return default_value;
}
uint64_t convertPercent(double percent, uint64_t max_value) {
// Checked by schema.
ASSERT(percent >= 0.0 && percent <= 100.0);
return max_value * (percent / 100.0);
}
bool evaluateFractionalPercent(envoy::type::FractionalPercent percent, uint64_t random_value) {
return random_value % fractionalPercentDenominatorToInt(percent.denominator()) <
percent.numerator();
}
uint64_t fractionalPercentDenominatorToInt(
const envoy::type::FractionalPercent::DenominatorType& denominator) {
switch (denominator) {
case envoy::type::FractionalPercent::HUNDRED:
return 100;
case envoy::type::FractionalPercent::TEN_THOUSAND:
return 10000;
case envoy::type::FractionalPercent::MILLION:
return 1000000;
default:
// Checked by schema.
NOT_REACHED_GCOVR_EXCL_LINE;
}
}
} // namespace ProtobufPercentHelper
MissingFieldException::MissingFieldException(const std::string& field_name,
const Protobuf::Message& message)
: EnvoyException(
fmt::format("Field '{}' is missing in: {}", field_name, message.DebugString())) {}
ProtoValidationException::ProtoValidationException(const std::string& validation_error,
const Protobuf::Message& message)
: EnvoyException(fmt::format("Proto constraint validation failed ({}): {}", validation_error,
message.DebugString())) {
ENVOY_LOG_MISC(debug, "Proto validation error; throwing {}", what());
}
void MessageUtil::loadFromJson(const std::string& json, Protobuf::Message& message,
ProtobufMessage::ValidationVisitor& validation_visitor) {
Protobuf::util::JsonParseOptions options;
options.case_insensitive_enum_parsing = true;
// Let's first try and get a clean parse when checking for unknown fields;
// this should be the common case.
options.ignore_unknown_fields = false;
const auto strict_status = Protobuf::util::JsonStringToMessage(json, &message, options);
if (strict_status.ok()) {
// Success, no need to do any extra work.
return;
}
// If we fail, we see if we get a clean parse when allowing unknown fields.
// This is essentially a workaround
// for https://github.com/protocolbuffers/protobuf/issues/5967.
// TODO(htuch): clean this up when protobuf supports JSON/YAML unknown field
// detection directly.
options.ignore_unknown_fields = true;
const auto relaxed_status = Protobuf::util::JsonStringToMessage(json, &message, options);
// If we still fail with relaxed unknown field checking, the error has nothing
// to do with unknown fields.
if (!relaxed_status.ok()) {
throw EnvoyException("Unable to parse JSON as proto (" + relaxed_status.ToString() +
"): " + json);
}
// We know it's an unknown field at this point.
validation_visitor.onUnknownField("type " + message.GetTypeName() + " reason " +
strict_status.ToString());
}
void MessageUtil::loadFromJson(const std::string& json, ProtobufWkt::Struct& message) {
// No need to validate if converting to a Struct, since there are no unknown
// fields possible.
return loadFromJson(json, message, ProtobufMessage::getNullValidationVisitor());
}
void MessageUtil::loadFromYaml(const std::string& yaml, Protobuf::Message& message,
ProtobufMessage::ValidationVisitor& validation_visitor) {
const auto loaded_object = Json::Factory::loadFromYamlString(yaml);
// Load the message if the loaded object has type Object or Array.
if (loaded_object->isObject() || loaded_object->isArray()) {
const std::string json = loaded_object->asJsonString();
loadFromJson(json, message, validation_visitor);
return;
}
throw EnvoyException("Unable to convert YAML as JSON: " + yaml);
}
void MessageUtil::loadFromFile(const std::string& path, Protobuf::Message& message,
ProtobufMessage::ValidationVisitor& validation_visitor,
Api::Api& api) {
const std::string contents = api.fileSystem().fileReadToEnd(path);
// If the filename ends with .pb, attempt to parse it as a binary proto.
if (absl::EndsWith(path, FileExtensions::get().ProtoBinary)) {
// Attempt to parse the binary format.
if (message.ParseFromString(contents)) {
MessageUtil::checkForUnexpectedFields(message, validation_visitor);
return;
}
throw EnvoyException("Unable to parse file \"" + path + "\" as a binary protobuf (type " +
message.GetTypeName() + ")");
}
// If the filename ends with .pb_text, attempt to parse it as a text proto.
if (absl::EndsWith(path, FileExtensions::get().ProtoText)) {
if (Protobuf::TextFormat::ParseFromString(contents, &message)) {
return;
}
throw EnvoyException("Unable to parse file \"" + path + "\" as a text protobuf (type " +
message.GetTypeName() + ")");
}
if (absl::EndsWith(path, FileExtensions::get().Yaml)) {
loadFromYaml(contents, message, validation_visitor);
} else {
loadFromJson(contents, message, validation_visitor);
}
}
void MessageUtil::checkForUnexpectedFields(const Protobuf::Message& message,
ProtobufMessage::ValidationVisitor& validation_visitor,
Runtime::Loader* runtime) {
// Reject unknown fields.
const auto& unknown_fields = message.GetReflection()->GetUnknownFields(message);
if (!unknown_fields.empty()) {
std::string error_msg;
for (int n = 0; n < unknown_fields.field_count(); ++n) {
error_msg += absl::StrCat(n > 0 ? ", " : "", unknown_fields.field(n).number());
}
// We use the validation visitor but have hard coded behavior below for deprecated fields.
// TODO(htuch): Unify the deprecated and unknown visitor handling behind the validation
// visitor pattern. https://github.com/envoyproxy/envoy/issues/8092.
validation_visitor.onUnknownField("type " + message.GetTypeName() +
" with unknown field set {" + error_msg + "}");
}
const Protobuf::Descriptor* descriptor = message.GetDescriptor();
const Protobuf::Reflection* reflection = message.GetReflection();
for (int i = 0; i < descriptor->field_count(); ++i) {
const auto* field = descriptor->field(i);
// If this field is not in use, continue.
if ((field->is_repeated() && reflection->FieldSize(message, field) == 0) ||
(!field->is_repeated() && !reflection->HasField(message, field))) {
continue;
}
#ifdef ENVOY_DISABLE_DEPRECATED_FEATURES
bool warn_only = false;
#else
bool warn_only = true;
#endif
absl::string_view filename = filenameFromPath(field->file()->name());
// Allow runtime to be null both to not crash if this is called before server initialization,
// and so proto validation works in context where runtime singleton is not set up (e.g.
// standalone config validation utilities)
if (runtime && field->options().deprecated() &&
!runtime->snapshot().deprecatedFeatureEnabled(
absl::StrCat("envoy.deprecated_features.", filename, ":", field->name()))) {
warn_only = false;
}
// If this field is deprecated, warn or throw an error.
if (field->options().deprecated()) {
std::string err = fmt::format(
"Using deprecated option '{}' from file {}. This configuration will be removed from "
"Envoy soon. Please see https://www.envoyproxy.io/docs/envoy/latest/intro/deprecated "
"for details.",
field->full_name(), filename);
if (warn_only) {
ENVOY_LOG_MISC(warn, "{}", err);
} else {
const char fatal_error[] =
" If continued use of this field is absolutely necessary, see "
"https://www.envoyproxy.io/docs/envoy/latest/configuration/operations/runtime"
"#using-runtime-overrides-for-deprecated-features for how to apply a temporary and "
"highly discouraged override.";
throw ProtoValidationException(err + fatal_error, message);
}
}
// If this is a message, recurse to check for deprecated fields in the sub-message.
if (field->cpp_type() == Protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {
if (field->is_repeated()) {
const int size = reflection->FieldSize(message, field);
for (int j = 0; j < size; ++j) {
checkForUnexpectedFields(reflection->GetRepeatedMessage(message, field, j),
validation_visitor, runtime);
}
} else {
checkForUnexpectedFields(reflection->GetMessage(message, field), validation_visitor,
runtime);
}
}
}
}
std::string MessageUtil::getYamlStringFromMessage(const Protobuf::Message& message,
const bool block_print,
const bool always_print_primitive_fields) {
std::string json = getJsonStringFromMessage(message, false, always_print_primitive_fields);
auto node = YAML::Load(json);
if (block_print) {
blockFormat(node);
}
YAML::Emitter out;
out << node;
return out.c_str();
}
std::string MessageUtil::getJsonStringFromMessage(const Protobuf::Message& message,
const bool pretty_print,
const bool always_print_primitive_fields) {
Protobuf::util::JsonPrintOptions json_options;
// By default, proto field names are converted to camelCase when the message is converted to JSON.
// Setting this option makes debugging easier because it keeps field names consistent in JSON
// printouts.
json_options.preserve_proto_field_names = true;
if (pretty_print) {
json_options.add_whitespace = true;
}
// Primitive types such as int32s and enums will not be serialized if they have the default value.
// This flag disables that behavior.
if (always_print_primitive_fields) {
json_options.always_print_primitive_fields = true;
}
std::string json;
const auto status = Protobuf::util::MessageToJsonString(message, &json, json_options);
// This should always succeed unless something crash-worthy such as out-of-memory.
RELEASE_ASSERT(status.ok(), "");
return json;
}
namespace {
void jsonConvertInternal(const Protobuf::Message& source,
ProtobufMessage::ValidationVisitor& validation_visitor,
Protobuf::Message& dest) {
Protobuf::util::JsonPrintOptions json_options;
json_options.preserve_proto_field_names = true;
std::string json;
const auto status = Protobuf::util::MessageToJsonString(source, &json, json_options);
if (!status.ok()) {
throw EnvoyException(fmt::format("Unable to convert protobuf message to JSON string: {} {}",
status.ToString(), source.DebugString()));
}
MessageUtil::loadFromJson(json, dest, validation_visitor);
}
} // namespace
void MessageUtil::jsonConvert(const Protobuf::Message& source, ProtobufWkt::Struct& dest) {
// Any proto3 message can be transformed to Struct, so there is no need to check for unknown
// fields. There is one catch; Duration/Timestamp etc. which have non-object canonical JSON
// representations don't work.
jsonConvertInternal(source, ProtobufMessage::getNullValidationVisitor(), dest);
}
void MessageUtil::jsonConvert(const ProtobufWkt::Struct& source,
ProtobufMessage::ValidationVisitor& validation_visitor,
Protobuf::Message& dest) {
jsonConvertInternal(source, validation_visitor, dest);
}
ProtobufWkt::Struct MessageUtil::keyValueStruct(const std::string& key, const std::string& value) {
ProtobufWkt::Struct struct_obj;
ProtobufWkt::Value val;
val.set_string_value(value);
(*struct_obj.mutable_fields())[key] = val;
return struct_obj;
}
// TODO(alyssawilk) see if we can get proto's CodeEnumToString made accessible
// to avoid copying it. Otherwise change this to absl::string_view.
std::string MessageUtil::CodeEnumToString(ProtobufUtil::error::Code code) {
switch (code) {
case ProtobufUtil::error::OK:
return "OK";
case ProtobufUtil::error::CANCELLED:
return "CANCELLED";
case ProtobufUtil::error::UNKNOWN:
return "UNKNOWN";
case ProtobufUtil::error::INVALID_ARGUMENT:
return "INVALID_ARGUMENT";
case ProtobufUtil::error::DEADLINE_EXCEEDED:
return "DEADLINE_EXCEEDED";
case ProtobufUtil::error::NOT_FOUND:
return "NOT_FOUND";
case ProtobufUtil::error::ALREADY_EXISTS:
return "ALREADY_EXISTS";
case ProtobufUtil::error::PERMISSION_DENIED:
return "PERMISSION_DENIED";
case ProtobufUtil::error::UNAUTHENTICATED:
return "UNAUTHENTICATED";
case ProtobufUtil::error::RESOURCE_EXHAUSTED:
return "RESOURCE_EXHAUSTED";
case ProtobufUtil::error::FAILED_PRECONDITION:
return "FAILED_PRECONDITION";
case ProtobufUtil::error::ABORTED:
return "ABORTED";
case ProtobufUtil::error::OUT_OF_RANGE:
return "OUT_OF_RANGE";
case ProtobufUtil::error::UNIMPLEMENTED:
return "UNIMPLEMENTED";
case ProtobufUtil::error::INTERNAL:
return "INTERNAL";
case ProtobufUtil::error::UNAVAILABLE:
return "UNAVAILABLE";
case ProtobufUtil::error::DATA_LOSS:
return "DATA_LOSS";
default:
return "";
}
}
bool ValueUtil::equal(const ProtobufWkt::Value& v1, const ProtobufWkt::Value& v2) {
ProtobufWkt::Value::KindCase kind = v1.kind_case();
if (kind != v2.kind_case()) {
return false;
}
switch (kind) {
case ProtobufWkt::Value::KIND_NOT_SET:
return v2.kind_case() == ProtobufWkt::Value::KIND_NOT_SET;
case ProtobufWkt::Value::kNullValue:
return true;
case ProtobufWkt::Value::kNumberValue:
return v1.number_value() == v2.number_value();
case ProtobufWkt::Value::kStringValue:
return v1.string_value() == v2.string_value();
case ProtobufWkt::Value::kBoolValue:
return v1.bool_value() == v2.bool_value();
case ProtobufWkt::Value::kStructValue: {
const ProtobufWkt::Struct& s1 = v1.struct_value();
const ProtobufWkt::Struct& s2 = v2.struct_value();
if (s1.fields_size() != s2.fields_size()) {
return false;
}
for (const auto& it1 : s1.fields()) {
const auto& it2 = s2.fields().find(it1.first);
if (it2 == s2.fields().end()) {
return false;
}
if (!equal(it1.second, it2->second)) {
return false;
}
}
return true;
}
case ProtobufWkt::Value::kListValue: {
const ProtobufWkt::ListValue& l1 = v1.list_value();
const ProtobufWkt::ListValue& l2 = v2.list_value();
if (l1.values_size() != l2.values_size()) {
return false;
}
for (int i = 0; i < l1.values_size(); i++) {
if (!equal(l1.values(i), l2.values(i))) {
return false;
}
}
return true;
}
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
}
namespace {
void validateDuration(const ProtobufWkt::Duration& duration) {
if (duration.seconds() < 0 || duration.nanos() < 0) {
throw DurationUtil::OutOfRangeException(
fmt::format("Expected positive duration: {}", duration.DebugString()));
}
if (duration.nanos() > 999999999 ||
duration.seconds() > Protobuf::util::TimeUtil::kDurationMaxSeconds) {
throw DurationUtil::OutOfRangeException(
fmt::format("Duration out-of-range: {}", duration.DebugString()));
}
}
} // namespace
uint64_t DurationUtil::durationToMilliseconds(const ProtobufWkt::Duration& duration) {
validateDuration(duration);
return Protobuf::util::TimeUtil::DurationToMilliseconds(duration);
}
uint64_t DurationUtil::durationToSeconds(const ProtobufWkt::Duration& duration) {
validateDuration(duration);
return Protobuf::util::TimeUtil::DurationToSeconds(duration);
}
void TimestampUtil::systemClockToTimestamp(const SystemTime system_clock_time,
ProtobufWkt::Timestamp& timestamp) {
// Converts to millisecond-precision Timestamp by explicitly casting to millisecond-precision
// time_point.
timestamp.MergeFrom(Protobuf::util::TimeUtil::MillisecondsToTimestamp(
std::chrono::time_point_cast<std::chrono::milliseconds>(system_clock_time)
.time_since_epoch()
.count()));
}
} // namespace Envoy
|
[
"bdecoste@gmail.com"
] |
bdecoste@gmail.com
|
d0db69819e838d05939abc27e43e585b40b0a1c3
|
c5f4724d927c12f236b9710355c170681d75ebd9
|
/Homework/p0/main.cpp
|
c525393104de8a81cba8b515f3fb34a2b499c29d
|
[] |
no_license
|
Vin129/Games101_hw
|
8b5b5700f412ae4c5bd7319c27d3e0317ebf3ff7
|
0f732658a1537aedbbe6e67260c7e2226045e1f8
|
refs/heads/main
| 2023-02-09T18:00:57.132379
| 2021-01-02T11:10:21
| 2021-01-02T11:10:21
| 324,705,265
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,924
|
cpp
|
#include<cmath>
#include<eigen3/Eigen/Core>
#include<eigen3/Eigen/Dense>
#include<iostream>
using namespace std;
#define PI acos(-1)
int main(){
// Basic Example of cpp
clog << "Hello World" << std::endl;
std::cout << "Example of cpp \n";
float a = 1.0, b = 2.0;
std::cout << a << std::endl;
std::cout << a/b << std::endl;
std::cout << std::sqrt(b) << std::endl;
std::cout << std::acos(-1) << std::endl;
std::cout << std::sin(30.0/180.0*acos(-1)) << std::endl;
// Example of vector
std::cout << "Example of vector \n";
// vector definition
Eigen::Vector3f v(1.0f,2.0f,3.0f);
Eigen::Vector3f w(1.0f,0.0f,0.0f);
// vector output
std::cout << "Example of output \n";
std::cout << v << std::endl;
// vector add
std::cout << "Example of add \n";
std::cout << v + w << std::endl;
// vector scalar multiply
std::cout << "Example of scalar multiply \n";
std::cout << v * 3.0f << std::endl;
std::cout << 2.0f * v << std::endl;
// Example of matrix
std::cout << "Example of matrix \n";
// matrix definition
Eigen::Matrix3f i,j;
i << 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0;
j << 2.0, 3.0, 1.0, 4.0, 6.0, 5.0, 9.0, 7.0, 8.0;
// matrix output
std::cout << "Example of output \n";
std::cout << i << std::endl;
// matrix add i + j
// matrix scalar multiply i * 2.0
// matrix multiply i * j
// matrix multiply vector i * v
std::cout << "Homework 1 \n";
Eigen::Vector3f p(2.0f,1.0f,1.0f);
Eigen::Matrix3f transform,rotation;
float mX = 1.0,mY = 2.0;
float radian = 45/180*PI;
transform << 1,0,1,
0,1,2,
0,0,1,
rotation << cos(radian), -1*sin(radian), mX,
sin(radian), cos(radian), mY,
0.0, 0.0, 1.0;
Eigen::Vector3f result = transform*rotation*p;
cout << result << endl;
return 0;
}
|
[
"515019721@qq.com"
] |
515019721@qq.com
|
cecb50e20ed04f9837a39102d3dc64a3cff03c81
|
960499569a1018c2a8817d21b13e79856ff344ba
|
/services/catalog/reader.cc
|
3ae85d6ecc90831fb1ae034130a20d919c966f63
|
[
"BSD-3-Clause"
] |
permissive
|
ollie314/chromium
|
e0082d960bb3c0b19a38315f8d25dd7645129d04
|
533a1c2a90fe2a3bc74892f66f34d45aef3a8f98
|
refs/heads/master
| 2022-12-30T17:45:45.833312
| 2016-11-13T22:46:54
| 2016-11-13T22:46:53
| 49,952,784
| 0
| 0
| null | 2016-11-13T22:46:54
| 2016-01-19T12:58:33
| null |
UTF-8
|
C++
| false
| false
| 8,695
|
cc
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/catalog/reader.h"
#include "base/bind.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/json/json_file_value_serializer.h"
#include "base/json/json_reader.h"
#include "base/memory/ptr_util.h"
#include "base/path_service.h"
#include "base/task_runner_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "services/catalog/constants.h"
#include "services/catalog/entry.h"
#include "services/catalog/manifest_provider.h"
#include "services/service_manager/public/cpp/names.h"
namespace catalog {
namespace {
base::FilePath GetManifestPath(const base::FilePath& package_dir,
const std::string& name,
const std::string& package_name_override) {
// TODO(beng): think more about how this should be done for exe targets.
std::string path = service_manager::GetNamePath(name);
std::string package_name =
package_name_override.empty() ? path : package_name_override;
return package_dir.AppendASCII(kPackagesDirName).AppendASCII(
package_name + "/manifest.json");
}
base::FilePath GetExecutablePath(const base::FilePath& package_dir,
const std::string& name) {
// It's still a mojo: URL, use the default mapping scheme.
const std::string host = service_manager::GetNamePath(name);
return package_dir.AppendASCII(host + "/" + host + ".library");
}
std::unique_ptr<Entry> ProcessManifest(
std::unique_ptr<base::Value> manifest_root,
const base::FilePath& package_dir) {
// Manifest was malformed or did not exist.
if (!manifest_root)
return nullptr;
const base::DictionaryValue* dictionary = nullptr;
if (!manifest_root->GetAsDictionary(&dictionary))
return nullptr;
std::unique_ptr<Entry> entry = Entry::Deserialize(*dictionary);
if (!entry)
return nullptr;
entry->set_path(GetExecutablePath(package_dir, entry->name()));
return entry;
}
std::unique_ptr<Entry> CreateEntryForManifestAt(
const base::FilePath& manifest_path,
const base::FilePath& package_dir) {
JSONFileValueDeserializer deserializer(manifest_path);
int error = 0;
std::string message;
// TODO(beng): probably want to do more detailed error checking. This should
// be done when figuring out if to unblock connection completion.
return ProcessManifest(deserializer.Deserialize(&error, &message),
package_dir);
}
void ScanDir(
const base::FilePath& package_dir,
const Reader::ReadManifestCallback& read_manifest_callback,
scoped_refptr<base::SingleThreadTaskRunner> original_thread_task_runner,
const base::Closure& read_complete_closure) {
base::FileEnumerator enumerator(package_dir, false,
base::FileEnumerator::DIRECTORIES);
while (1) {
base::FilePath path = enumerator.Next();
if (path.empty())
break;
base::FilePath manifest_path = path.AppendASCII("manifest.json");
std::unique_ptr<Entry> entry =
CreateEntryForManifestAt(manifest_path, package_dir);
if (!entry)
continue;
// Skip over subdirs that contain only manifests, they're artifacts of the
// build (e.g. for applications that are packaged into others) and are not
// valid standalone packages.
base::FilePath package_path = GetExecutablePath(package_dir, entry->name());
if (entry->name() != "service:service_manager" &&
entry->name() != "service:catalog" && !base::PathExists(package_path)) {
continue;
}
original_thread_task_runner->PostTask(
FROM_HERE,
base::Bind(read_manifest_callback, base::Passed(&entry)));
}
original_thread_task_runner->PostTask(FROM_HERE, read_complete_closure);
}
std::unique_ptr<Entry> ReadManifest(
const base::FilePath& package_dir,
const std::string& mojo_name,
const std::string& package_name_override,
const base::FilePath& manifest_path_override) {
base::FilePath manifest_path;
if (manifest_path_override.empty()) {
manifest_path =
GetManifestPath(package_dir, mojo_name, package_name_override);
} else {
manifest_path = manifest_path_override;
}
std::unique_ptr<Entry> entry = CreateEntryForManifestAt(manifest_path,
package_dir);
if (!entry) {
entry.reset(new Entry(mojo_name));
entry->set_path(GetExecutablePath(
package_dir.AppendASCII(kPackagesDirName), mojo_name));
}
return entry;
}
void AddEntryToCache(EntryCache* cache, std::unique_ptr<Entry> entry) {
std::vector<std::unique_ptr<Entry>> children = entry->TakeChildren();
for (auto& child : children)
AddEntryToCache(cache, std::move(child));
(*cache)[entry->name()] = std::move(entry);
}
void DoNothing(service_manager::mojom::ResolveResultPtr) {}
} // namespace
// A sequenced task runner is used to guarantee requests are serviced in the
// order requested. To do otherwise means we may run callbacks in an
// unpredictable order, leading to flake.
Reader::Reader(base::SequencedWorkerPool* worker_pool,
ManifestProvider* manifest_provider)
: Reader(manifest_provider) {
file_task_runner_ = worker_pool->GetSequencedTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::GetSequenceToken(),
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
}
Reader::Reader(base::SingleThreadTaskRunner* task_runner,
ManifestProvider* manifest_provider)
: Reader(manifest_provider) {
file_task_runner_ = task_runner;
}
Reader::~Reader() {}
void Reader::Read(const base::FilePath& package_dir,
EntryCache* cache,
const base::Closure& read_complete_closure) {
file_task_runner_->PostTask(
FROM_HERE,
base::Bind(&ScanDir, package_dir,
base::Bind(&Reader::OnReadManifest, weak_factory_.GetWeakPtr(),
cache, base::Bind(&DoNothing)),
base::ThreadTaskRunnerHandle::Get(),
read_complete_closure));
}
void Reader::CreateEntryForName(
const std::string& mojo_name,
EntryCache* cache,
const CreateEntryForNameCallback& entry_created_callback) {
if (manifest_provider_) {
std::unique_ptr<base::Value> manifest_root =
manifest_provider_->GetManifest(mojo_name);
if (manifest_root) {
base::PostTaskAndReplyWithResult(
file_task_runner_.get(), FROM_HERE,
base::Bind(&ProcessManifest, base::Passed(&manifest_root),
system_package_dir_),
base::Bind(&Reader::OnReadManifest, weak_factory_.GetWeakPtr(), cache,
entry_created_callback));
return;
}
}
base::FilePath manifest_path_override;
{
auto override_iter = manifest_path_overrides_.find(mojo_name);
if (override_iter != manifest_path_overrides_.end())
manifest_path_override = override_iter->second;
}
std::string package_name_override;
{
auto override_iter = package_name_overrides_.find(mojo_name);
if (override_iter != package_name_overrides_.end())
package_name_override = override_iter->second;
}
base::PostTaskAndReplyWithResult(
file_task_runner_.get(), FROM_HERE,
base::Bind(&ReadManifest, system_package_dir_, mojo_name,
package_name_override, manifest_path_override),
base::Bind(&Reader::OnReadManifest, weak_factory_.GetWeakPtr(), cache,
entry_created_callback));
}
void Reader::OverridePackageName(const std::string& service_name,
const std::string& package_name) {
package_name_overrides_.insert(std::make_pair(service_name, package_name));
}
void Reader::OverrideManifestPath(const std::string& service_name,
const base::FilePath& path) {
manifest_path_overrides_.insert(std::make_pair(service_name, path));
}
Reader::Reader(ManifestProvider* manifest_provider)
: manifest_provider_(manifest_provider), weak_factory_(this) {
PathService::Get(base::DIR_MODULE, &system_package_dir_);
}
void Reader::OnReadManifest(
EntryCache* cache,
const CreateEntryForNameCallback& entry_created_callback,
std::unique_ptr<Entry> entry) {
if (!entry)
return;
service_manager::mojom::ResolveResultPtr result =
service_manager::mojom::ResolveResult::From(*entry);
AddEntryToCache(cache, std::move(entry));
entry_created_callback.Run(std::move(result));
}
} // namespace catalog
|
[
"commit-bot@chromium.org"
] |
commit-bot@chromium.org
|
b7e6d80e44efe80ca447b1f0eff791f7872cbcd8
|
bddb40149f9028297d9b4f3f6b77514cadac9bca
|
/Source/Prototypes/filemanagement/filemanagement/FileButton_ShellExecute.cpp
|
dbc7fabd2a8679e444025bbc9025346f9a5acbe0
|
[] |
no_license
|
JamesTerm/GremlinGames
|
91d61a50d0926b8e95cad21053ba2cf6c3316003
|
fd0366af007bff8cffe4941b4bb5bb16948a8c66
|
refs/heads/master
| 2021-10-20T21:15:53.121770
| 2019-03-01T15:45:58
| 2019-03-01T15:45:58
| 173,261,435
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,154
|
cpp
|
#include "stdafx.h"
bool FileButton_ShellExecute::Interface_FileClick_Execute //! Return whether you succeeded
( HWND hWnd, //! The control of the (first) window clicked upon
char **FileName) //! The list of filenames that where clicked upon
{
if (ApplicationInstance_TriCaster()) return false;
// Iterate through the list of files and call Shell Execute on each item
// This Command should be called dead last (Has a priority of 1)
char* thisFile = *FileName;
static char directory[128];
char* errorMessage = directory;
bool ret = false;
while (thisFile)
{
strcpy(directory, thisFile);
char* nameOnly = NewTek_GetFileNameFromPath(directory);
// Do not relaunch ourselves
char *pExtension = NewTek_GetLastDot( nameOnly );
if ((pExtension)&&(stricmp(pExtension, TLF_BASE_FILEEXT )))
{ // Now check its not a folder
if (nameOnly && (nameOnly != directory))
{
// Seperate the name from the directory
*(nameOnly - 1) = 0;
int errRet = (int)ShellExecute(NewTek_GetGlobalParentHWND(), NULL, nameOnly, NULL, directory, SW_SHOW);
if (errRet < 33)
{
bool ShowErrorMessage = true;
char SystemPath[MAX_PATH];
if (errRet == SE_ERR_NOASSOC && GetSystemDirectory(SystemPath, MAX_PATH) != 0)
{
const size_t RunParametersLength = MAX_PATH + 64;
char RunParameters[RunParametersLength];
_snprintf(RunParameters, RunParametersLength, "shell32.dll,OpenAs_RunDLL %s\\%s", directory, nameOnly);
ShowErrorMessage = ((int)ShellExecute(NewTek_GetGlobalParentHWND(), "open", "rundll32.exe", RunParameters, SystemPath, SW_SHOW) < 33);
}
if (ShowErrorMessage)
{
sprintf(errorMessage, TL_GetString( "TR::" "There was an error performing Shell Execute on \"%s\"", "There was an error performing Shell Execute on \"%s\"" ), thisFile);
NewTek_MessageBox(NULL, errorMessage, TL_GetString( "TR::" "Error Executing File", "Error Executing File" ), MB_OK, NULL);
}
}
else ret = true;
}
}
// Look at the next file
FileName++;
thisFile = *FileName;
}
return ret;
}
|
[
"james@e2c3bcc0-b32a-0410-840c-db224dcf21cb"
] |
james@e2c3bcc0-b32a-0410-840c-db224dcf21cb
|
217749098f0a598178341df24e6d4514c7d61f1e
|
615a8bb951c9f8a6c125548730e00b01566eb384
|
/Sandbox/src/Layers/CImguiLayer.h
|
be5e225ae29e3c4a70b08f9496c5d871fd597d39
|
[
"Apache-2.0"
] |
permissive
|
Krais1989/KraisEngine
|
c176c8e52baddaf3a318a437af3ba46746f99cd1
|
b7f79a4cd38cd83c3f9c762fd4d93ebd713ca3cd
|
refs/heads/master
| 2023-08-31T10:15:31.913994
| 2021-03-06T19:37:47
| 2021-03-06T19:37:47
| 283,689,588
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 353
|
h
|
#pragma once
#include <ke_pch.h>
#include <KraisEngine.h>
class CImguiLayer : public KE::CLayer
{
public:
CImguiLayer();
virtual void OnAttach();
virtual void OnDetach();
virtual void OnUpdate(float dt);
virtual void OnEvent(KE::CEvent& ev);
virtual void OnRender();
protected:
bool m_ShowDemo = true;
bool m_CameraTool = true;
};
|
[
"krais1989@gmail.com"
] |
krais1989@gmail.com
|
7ae165034429cebc15102d9059509c82988b4339
|
5f31b04cf297e03f8be4608d258f9fee46c063e8
|
/ProjectTest/03_event_driven_programming/testhead.cpp
|
0dbea5ce9fb50a03cb219a1522ed4d2dfaa32263
|
[] |
no_license
|
cybershuimo/SDL_Experiment
|
0c93eaa0a67e359b9bf7e998a2bf4855e4473cb2
|
c2684e8a1be0e82300ba52ac6611e16995f3ca2d
|
refs/heads/master
| 2021-09-10T07:34:42.675641
| 2018-01-12T08:05:43
| 2018-01-12T08:05:43
| 114,712,687
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 146
|
cpp
|
#include <stdio.h>
#include "testhead.h"
int main(int argc, char const *argv[])
{
int a = 2;
change(a);
printf("a is %i\n", a);
return 0;
}
|
[
"27873085+cybershuimo@users.noreply.github.com"
] |
27873085+cybershuimo@users.noreply.github.com
|
fdde0689ac5297d94b8119525d437f1b622eee3e
|
d6b4bdf418ae6ab89b721a79f198de812311c783
|
/tem/include/tencentcloud/tem/v20201221/model/CosToken.h
|
c66f25d2b462bf1084b142caf574e1203c653470
|
[
"Apache-2.0"
] |
permissive
|
TencentCloud/tencentcloud-sdk-cpp-intl-en
|
d0781d461e84eb81775c2145bacae13084561c15
|
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
|
refs/heads/master
| 2023-08-21T12:29:54.125071
| 2023-08-21T01:12:39
| 2023-08-21T01:12:39
| 277,769,407
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,262
|
h
|
/*
* 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.
*/
#ifndef TENCENTCLOUD_TEM_V20201221_MODEL_COSTOKEN_H_
#define TENCENTCLOUD_TEM_V20201221_MODEL_COSTOKEN_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Tem
{
namespace V20201221
{
namespace Model
{
/**
* Cos token
*/
class CosToken : public AbstractModel
{
public:
CosToken();
~CosToken() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取Unique request ID
* @return RequestId Unique request ID
*
*/
std::string GetRequestId() const;
/**
* 设置Unique request ID
* @param _requestId Unique request ID
*
*/
void SetRequestId(const std::string& _requestId);
/**
* 判断参数 RequestId 是否已赋值
* @return RequestId 是否已赋值
*
*/
bool RequestIdHasBeenSet() const;
/**
* 获取Bucket name
* @return Bucket Bucket name
*
*/
std::string GetBucket() const;
/**
* 设置Bucket name
* @param _bucket Bucket name
*
*/
void SetBucket(const std::string& _bucket);
/**
* 判断参数 Bucket 是否已赋值
* @return Bucket 是否已赋值
*
*/
bool BucketHasBeenSet() const;
/**
* 获取Bucket region
* @return Region Bucket region
*
*/
std::string GetRegion() const;
/**
* 设置Bucket region
* @param _region Bucket region
*
*/
void SetRegion(const std::string& _region);
/**
* 判断参数 Region 是否已赋值
* @return Region 是否已赋值
*
*/
bool RegionHasBeenSet() const;
/**
* 获取`SecretId` of temporary key
* @return TmpSecretId `SecretId` of temporary key
*
*/
std::string GetTmpSecretId() const;
/**
* 设置`SecretId` of temporary key
* @param _tmpSecretId `SecretId` of temporary key
*
*/
void SetTmpSecretId(const std::string& _tmpSecretId);
/**
* 判断参数 TmpSecretId 是否已赋值
* @return TmpSecretId 是否已赋值
*
*/
bool TmpSecretIdHasBeenSet() const;
/**
* 获取`SecretKey` of temporary key
* @return TmpSecretKey `SecretKey` of temporary key
*
*/
std::string GetTmpSecretKey() const;
/**
* 设置`SecretKey` of temporary key
* @param _tmpSecretKey `SecretKey` of temporary key
*
*/
void SetTmpSecretKey(const std::string& _tmpSecretKey);
/**
* 判断参数 TmpSecretKey 是否已赋值
* @return TmpSecretKey 是否已赋值
*
*/
bool TmpSecretKeyHasBeenSet() const;
/**
* 获取`sessionToken` of temporary key
* @return SessionToken `sessionToken` of temporary key
*
*/
std::string GetSessionToken() const;
/**
* 设置`sessionToken` of temporary key
* @param _sessionToken `sessionToken` of temporary key
*
*/
void SetSessionToken(const std::string& _sessionToken);
/**
* 判断参数 SessionToken 是否已赋值
* @return SessionToken 是否已赋值
*
*/
bool SessionTokenHasBeenSet() const;
/**
* 获取`StartTime` of temporary key acquisition
* @return StartTime `StartTime` of temporary key acquisition
*
*/
std::string GetStartTime() const;
/**
* 设置`StartTime` of temporary key acquisition
* @param _startTime `StartTime` of temporary key acquisition
*
*/
void SetStartTime(const std::string& _startTime);
/**
* 判断参数 StartTime 是否已赋值
* @return StartTime 是否已赋值
*
*/
bool StartTimeHasBeenSet() const;
/**
* 获取`ExpiredTime` of temporary key
* @return ExpiredTime `ExpiredTime` of temporary key
*
*/
std::string GetExpiredTime() const;
/**
* 设置`ExpiredTime` of temporary key
* @param _expiredTime `ExpiredTime` of temporary key
*
*/
void SetExpiredTime(const std::string& _expiredTime);
/**
* 判断参数 ExpiredTime 是否已赋值
* @return ExpiredTime 是否已赋值
*
*/
bool ExpiredTimeHasBeenSet() const;
/**
* 获取Full package path
* @return FullPath Full package path
*
*/
std::string GetFullPath() const;
/**
* 设置Full package path
* @param _fullPath Full package path
*
*/
void SetFullPath(const std::string& _fullPath);
/**
* 判断参数 FullPath 是否已赋值
* @return FullPath 是否已赋值
*
*/
bool FullPathHasBeenSet() const;
private:
/**
* Unique request ID
*/
std::string m_requestId;
bool m_requestIdHasBeenSet;
/**
* Bucket name
*/
std::string m_bucket;
bool m_bucketHasBeenSet;
/**
* Bucket region
*/
std::string m_region;
bool m_regionHasBeenSet;
/**
* `SecretId` of temporary key
*/
std::string m_tmpSecretId;
bool m_tmpSecretIdHasBeenSet;
/**
* `SecretKey` of temporary key
*/
std::string m_tmpSecretKey;
bool m_tmpSecretKeyHasBeenSet;
/**
* `sessionToken` of temporary key
*/
std::string m_sessionToken;
bool m_sessionTokenHasBeenSet;
/**
* `StartTime` of temporary key acquisition
*/
std::string m_startTime;
bool m_startTimeHasBeenSet;
/**
* `ExpiredTime` of temporary key
*/
std::string m_expiredTime;
bool m_expiredTimeHasBeenSet;
/**
* Full package path
*/
std::string m_fullPath;
bool m_fullPathHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TEM_V20201221_MODEL_COSTOKEN_H_
|
[
"tencentcloudapi@tencent.com"
] |
tencentcloudapi@tencent.com
|
5ac429ef741a94ec8dedb20012e6fe33018fcdcb
|
dd1e9e3796576da599f3981a7abaf2fcd9d6b89a
|
/BlitzSharp3D/gxruntime/graphics/bgfx/BGFXScene.cpp
|
f49c59ba1928b56c44fe146bab1a7dfa446995a4
|
[
"Zlib",
"BSD-3-Clause"
] |
permissive
|
blitzimagine/BlitzSharp3D
|
4ae674cfdd2aba09f6844dce10ad44796c92aad0
|
cbf25a5d4ad3e1081e819c0dfaeb3ce40cd57860
|
refs/heads/master
| 2023-04-13T08:50:40.440863
| 2022-06-08T13:41:12
| 2022-06-08T13:41:12
| 189,093,663
| 9
| 1
|
NOASSERTION
| 2021-09-04T22:52:21
| 2019-05-28T19:52:11
|
C
|
UTF-8
|
C++
| false
| false
| 13,348
|
cpp
|
#include "BGFXScene.h"
#include <bgfx/bgfx.h>
#include <bx/math.h>
#include "BGFXBase.h"
#include "BGFXLight.h"
#include "BGFXGraphics.h"
#include "BGFXCanvas.h"
#include "BGFXShader.h"
#include "BGFXUtil.h"
static int tex_stages = 1;
static float BLACK[] = { 0,0,0 };
static float WHITE[] = { 1,1,1 };
static float GRAY[] = { .5f,.5f,.5f };
BGFXScene::BGFXScene(BGFXGraphics* g) : mGraphics(g)
{
mHasTexture = false;
mCanvas = (BGFXCanvas*)mGraphics->createCanvas(mGraphics->getWidth(), mGraphics->getHeight(), 0);
mFX = 0;
setAmbient(GRAY);
setAmbient2(BLACK);
setPerspProj(1, 1000, 1, 1);
setViewport(0, 0, g->getWidth(), g->getHeight());
setViewMatrix(nullptr);
setWorldMatrix(nullptr);
}
BGFXScene::~BGFXScene()
{
}
int BGFXScene::hwTexUnits()
{
return 0;
}
int BGFXScene::gfxDriverCaps3D()
{
return 0;
}
void BGFXScene::setWBuffer(bool enable)
{
}
void BGFXScene::setHWMultiTex(bool enable)
{
}
void BGFXScene::setDither(bool enable)
{
}
void BGFXScene::setAntialias(bool enable)
{
}
void BGFXScene::setWireframe(bool enable)
{
}
void BGFXScene::setFlippedTris(bool enable)
{
}
void BGFXScene::setAmbient()
{
if (mFX & FX_FULLBRIGHT)
{
setAmbientColor(1.0f, 1.0f, 1.0f);
} else if (mFX & FX_CONDLIGHT)
{
setAmbientColor(mAmbient2[0], mAmbient2[1], mAmbient2[2]);
} else
{
setAmbientColor(mAmbient[0], mAmbient[1], mAmbient[2]);
}
}
void BGFXScene::setAmbient(const float rgb[3])
{
mAmbient[0] = rgb[0];
mAmbient[1] = rgb[1];
mAmbient[2] = rgb[2];
}
void BGFXScene::setAmbient2(const float rgb[3])
{
mAmbient2[0] = rgb[0];
mAmbient2[1] = rgb[1];
mAmbient2[2] = rgb[2];
}
void BGFXScene::setFogColor(const float rgb[3])
{
}
void BGFXScene::setFogRange(float nr, float fr)
{
}
void BGFXScene::setFogMode(int mode)
{
}
void BGFXScene::setZMode(int mode)
{
mZMode = mode;
}
void BGFXScene::setViewport(int x, int y, int w, int h)
{
mCanvas->getFrameBuffer()->bind(1);
//bgfx::setViewFrameBuffer(1, mGraphics->get3DFrameBuffer());
bgfx::setViewMode(1, bgfx::ViewMode::Sequential);
bgfx::setViewRect(1, x, y, w, h);
}
void BGFXScene::setOrthoProj(float nr, float fr, float w, float h)
{
mCanvas->getFrameBuffer()->bind(1);
float W = 2 / w;
float H = 2 / h;
float Q = 1 / (fr - nr);
mProjectionMatrix[0] = W;
mProjectionMatrix[5] = H;
mProjectionMatrix[10] = Q;
mProjectionMatrix[11] = 0;
mProjectionMatrix[14] = -Q * nr;
mProjectionMatrix[15] = 1;
bgfx::setViewTransform(1, mViewMatrix, mProjectionMatrix);
}
void BGFXScene::setPerspProj(float nr, float fr, float w, float h)
{
mCanvas->getFrameBuffer()->bind(1);
memset(mProjectionMatrix, 0, sizeof(mProjectionMatrix));
float W = 2 * nr / w;
float H = 2 * nr / h;
float Q = fr / (fr - nr);
mProjectionMatrix[0] = W;
mProjectionMatrix[5] = H;
mProjectionMatrix[10] = Q;
mProjectionMatrix[11] = 1;
mProjectionMatrix[14] = -Q * nr;
mProjectionMatrix[15] = 0;
bgfx::setViewTransform(1, mViewMatrix, mProjectionMatrix);
}
void BGFXScene::setViewMatrix(const Matrix* matrix)
{
mCanvas->getFrameBuffer()->bind(1);
if (matrix)
{
//bgfx::setViewFrameBuffer(1, mGraphics->get3DFrameBuffer());
const Matrix* m = matrix;
mViewMatrix[ 0] = m->elements[0][0]; mViewMatrix[ 1] = m->elements[0][1]; mViewMatrix[ 2] = m->elements[0][2]; mViewMatrix[ 3] = 0.0f;
mViewMatrix[ 4] = m->elements[1][0]; mViewMatrix[ 5] = m->elements[1][1]; mViewMatrix[ 6] = m->elements[1][2]; mViewMatrix[ 7] = 0.0f;
mViewMatrix[ 8] = m->elements[2][0]; mViewMatrix[ 9] = m->elements[2][1]; mViewMatrix[10] = m->elements[2][2]; mViewMatrix[11] = 0.0f;
mViewMatrix[12] = m->elements[3][0]; mViewMatrix[13] = m->elements[3][1]; mViewMatrix[14] = m->elements[3][2]; mViewMatrix[15] = 1.0f;
} else
{
bx::mtxIdentity(mViewMatrix);
}
bgfx::setViewTransform(1, mViewMatrix, mProjectionMatrix);
}
void BGFXScene::setWorldMatrix(const Matrix* matrix)
{
mCanvas->getFrameBuffer()->bind(1);
//bgfx::setViewFrameBuffer(1, mGraphics->get3DFrameBuffer());
if (matrix) {
const Matrix* m = matrix;
mWorldMatrix[0] = m->elements[0][0]; mWorldMatrix[1] = m->elements[0][1]; mWorldMatrix[2] = m->elements[0][2]; mWorldMatrix[3] = 0.0f;
mWorldMatrix[4] = m->elements[1][0]; mWorldMatrix[5] = m->elements[1][1]; mWorldMatrix[6] = m->elements[1][2]; mWorldMatrix[7] = 0.0f;
mWorldMatrix[8] = m->elements[2][0]; mWorldMatrix[9] = m->elements[2][1]; mWorldMatrix[10] = m->elements[2][2]; mWorldMatrix[11] = 0.0f;
mWorldMatrix[12] = m->elements[3][0]; mWorldMatrix[13] = m->elements[3][1]; mWorldMatrix[14] = m->elements[3][2]; mWorldMatrix[15] = 1.0f;
} else
{
bx::mtxIdentity(mWorldMatrix);
}
bgfx::setTransform(mWorldMatrix);
}
void BGFXScene::setTexState(int index, const TexState& state, bool set_blend, uint64_t& output_state)
{
mCanvas->getFrameBuffer()->bind(1);
setTexture(state.canvas->getTexture());
if (state.canvas->getFlags() & gxCanvas::CANVAS_TEX_MASK)
{
unsigned int mask = state.canvas->getMask();
float red, green, blue;
argb_int_to_float(mask, &red, &green, &blue, nullptr);
setDiscardColor(red, green, blue, true);
} else
{
setDiscardColor(0.0f, 0.0f, 0.0f, false);
}
}
void BGFXScene::setRenderState(const RenderState& rs)
{
mCanvas->getFrameBuffer()->bind(1);
//bgfx::setViewFrameBuffer(1, mGraphics->get3DFrameBuffer());
uint64_t state = 0;
bool zEnable = false;
bool zWrite = false;
switch (mZMode)
{
case ZMODE_NORMAL:
zEnable = true;
zWrite = true;
break;
case ZMODE_DISABLE:
zEnable = false;
zWrite = false;
break;
case ZMODE_CMPONLY:
zEnable = true;
zWrite = false;
break;
}
if (zEnable)
state |= BGFX_STATE_DEPTH_TEST_LESS;
if (zWrite)
state |= BGFX_STATE_WRITE_Z;
switch (rs.blend)
{
case BLEND_REPLACE:
//disable alpha blending
state &= ~(BGFX_STATE_BLEND_ALPHA);
break;
case BLEND_ALPHA:
state |= BGFX_STATE_BLEND_ALPHA;
break;
case BLEND_MULTIPLY:
state |= BGFX_STATE_BLEND_MULTIPLY;
break;
case BLEND_ADD:
//state |= BGFX_STATE_BLEND_ADD;
state |= BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_ONE);
break;
}
state |= BGFX_STATE_WRITE_RGB;
state |= BGFX_STATE_WRITE_A;
state |= BGFX_STATE_CULL_CW;
state |= BGFX_STATE_MSAA;
mFX = rs.fx;
if (mFX & FX_FULLBRIGHT)
{
for (int i = 0; i < mLightCount; i ++)
mLightEnabled[i] = false;
} else if (mFX & FX_CONDLIGHT)
{
for (int i = 0; i < mLightCount; i++)
mLightEnabled[i] = mLightDirectional[i];
} else
{
for (int i = 0; i < mLightCount; i++)
mLightEnabled[i] = true;
}
TexState* hw = mTexStates;
hw->matValid = false;
mNumTextures = 0;
mHasTexture = false;
for (int k = 0; k < MAX_TEXTURES; k++)
{
const RenderState::TexState& ts = rs.tex_states[k];
if (!ts.canvas || !ts.blend)
continue;
if (ts.canvas != hw->canvas)
hw->canvas = (BGFXCanvas*)ts.canvas;
if (ts.blend != hw->blend)
hw->blend = ts.blend;
if (ts.flags != hw->flags)
hw->flags = ts.flags;
if (ts.matrix || hw->matValid)
{
if (ts.matrix)
{
memcpy(hw->matrix.elements[0], ts.matrix->elements[0], 12);
memcpy(hw->matrix.elements[1], ts.matrix->elements[1], 12);
memcpy(hw->matrix.elements[2], ts.matrix->elements[2], 12);
memcpy(hw->matrix.elements[3], ts.matrix->elements[3], 12);
// Texture coords are vertically flipped in BGFX vs DX7
hw->matrix.elements[2][1] *= -1;
hw->matValid = true;
} else
{
hw->matValid = false;
}
}
if (mNumTextures < tex_stages)
{
mHasTexture = true;
setTexState(mNumTextures, *hw, true, state);
}
hw++;
mNumTextures++;
}
hw = mTexStates;
if (hw->matValid)
{
setTextureTransform(&hw->matrix);
}
else
{
Matrix matrix = {};
matrix.elements[0][0] = 1; matrix.elements[0][1] = 0; matrix.elements[0][2] = 0;
matrix.elements[1][0] = 0; matrix.elements[1][1] = 1; matrix.elements[1][2] = 0;
matrix.elements[2][0] = 0; matrix.elements[2][1] = 0; matrix.elements[2][2] = 1;
matrix.elements[3][0] = 0; matrix.elements[3][1] = 0; matrix.elements[3][2] = 0;
setTextureTransform(&matrix);
}
bgfx::setState(state);
setColor(rs.color[0], rs.color[1], rs.color[2], rs.alpha);
}
bool BGFXScene::begin(const std::vector<gxLight*>& lights)
{
mCanvas->getFrameBuffer()->bind(1);
//bgfx::setViewFrameBuffer(1, mGraphics->get3DFrameBuffer());
// This dummy draw call is here to make sure that view 0 is cleared
// if no other draw calls are submitted to view 0.
bgfx::touch(1);
int index = 0;
// Clean lights
for (int i = 0; i < BLITZ_MAX_LIGHTS; i++)
{
for (int j = 0; j < 4; j++)
{
mLightPosRadius[i][j] = 0.0f;
mLightRGBInnerR[i][j] = 0.0f;
mLightDirection[i][j] = 0.0f;
mLightDirectional[i] = false;
mLightEnabled[i] = false;
}
}
for (auto l : lights)
{
BGFXLight* light = (BGFXLight*)l;
uint32_t type = light->getType();
float range = light->getRange();
float color[3];
float position[3];
float direction[3];
float inner, outer;
light->getColor(color);
light->getPosition(position);
light->getDirection(direction);
light->getConeAngles(&inner, &outer);
mLightPosRadius[index][0] = position[0];
mLightPosRadius[index][1] = position[1];
mLightPosRadius[index][2] = position[2];
mLightPosRadius[index][3] = outer;//3.0f;
mLightRGBInnerR[index][0] = color[0];
mLightRGBInnerR[index][1] = color[1];
mLightRGBInnerR[index][2] = color[2];
mLightRGBInnerR[index][3] = inner;//0.8f;
mLightDirectional[index] = type == gxLight::LIGHT_POINT || type == gxLight::LIGHT_SPOT ? false : true;
if (type != gxLight::LIGHT_POINT)
{
mLightDirection[index][0] = direction[0];
mLightDirection[index][1] = direction[1];
mLightDirection[index][2] = direction[2];
mLightDirection[index][3] = 1.0;
}
// TODO: Support directional lights
index++;
if (index >= BLITZ_MAX_LIGHTS)
break;
}
mLightCount = index;
return true;
}
void BGFXScene::clear(const float rgb[3], float alpha, float z, bool clear_argb, bool clear_z)
{
mCanvas->getFrameBuffer()->bind(1);
//bgfx::setViewFrameBuffer(1, mGraphics->get3DFrameBuffer());
bgfx::setPaletteColor(0, rgb[0], rgb[1], rgb[2], alpha);
bgfx::setViewClear(1, (clear_argb?BGFX_CLEAR_COLOR:0) | (clear_z?BGFX_CLEAR_DEPTH:0), z, 0, 0);
bgfx::touch(1);
}
void BGFXScene::render(gxMesh* mesh, int first_vert, int vert_cnt, int first_tri, int tri_cnt)
{
mCanvas->getFrameBuffer()->bind(1);
//bgfx::setViewFrameBuffer(1, mGraphics->get3DFrameBuffer());
// With BGFX you need to set the transform for every render call!
bgfx::setTransform(mWorldMatrix);
setLightCount(mLightCount);
setLightEnabled(mLightEnabled);
setLightPosRadius(mLightPosRadius);
setLightRGBInnerR(mLightRGBInnerR);
setLightDirection(mLightDirection);
mesh->render(first_vert, vert_cnt, first_tri, tri_cnt);
setAmbient();
setUseTexture(mHasTexture);
bgfx::submit(1, mGraphics->getDefaultShader()->getProgram());
/*mCanvas->getFrameBuffer()->bind(1);
uint64_t bgfx_state = 0;
for (int k = tex_stages; k < mNumTextures; k++)
{
const TexState& state = mTexStates[k];
switch (state.blend)
{
default:
break;
}
setTexState(0, state, false, bgfx_state);
mesh->render(first_vert, vert_cnt, first_tri, tri_cnt);
setAmbient();
setUseTexture(mHasTexture);
bgfx::submit(1, mGraphics->getDefaultShader()->getProgram());
}*/
//if (tex_stages > 1)
// setTexState(1, mTexStates[1], true, bgfx_state);
//setTexState(0, mTexStates[0], true, bgfx_state);
}
void BGFXScene::end()
{
//setViewOrtho(1, mGraphics->getWidth(), mGraphics->getHeight());
}
gxLight* BGFXScene::createLight(int flags)
{
return d_new BGFXLight(flags);
}
void BGFXScene::freeLight(gxLight* l)
{
delete l;
}
int BGFXScene::getTrianglesDrawn()const
{
return 0;
}
|
[
"39096122+HumanGamer@users.noreply.github.com"
] |
39096122+HumanGamer@users.noreply.github.com
|
be3700b7d87cecfe3d582d00f2a9f6314ab5435f
|
52c56ac3090eb7bef0b1ae0e310db95bf05bce4d
|
/incl/domain/alliedcoalition.h
|
3d028d282dcf99a04c42272d0d44764479094f6a
|
[
"Unlicense"
] |
permissive
|
HexTools/one
|
ea6ce35d502728cdf6a2aa47ce2e6ddb2f73f7a2
|
87af3a4568bda72580accb4db9d4d12654df0293
|
refs/heads/master
| 2020-06-05T07:44:19.750921
| 2014-08-14T20:29:42
| 2014-08-14T20:29:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 231
|
h
|
#ifndef ALLIEDCOALITION_H
#define ALLIEDCOALITION_H
class AlliedCoalition
{
public:
enum
{
OTHER = 0,
BRITISH, // 1
FRENCH, // 2
VICHY, // 3
SOVIET, // 4
USA, // 5
GREEKS, // 6
COUNT // 7
};
};
#endif
|
[
"moondt@gmail.com"
] |
moondt@gmail.com
|
2b8117e3aeb12ec2e43d6c66d3f4849f14a84343
|
d98a957583e3d7e1ad822a74d24052c57ab3bbce
|
/test/compare/test_compare_uint64.cpp
|
49306f64d8069d18eca9d89228538ce4b9f7e5c8
|
[
"MIT"
] |
permissive
|
VeloPayments/v-portable-runtime
|
c0cd8cca5f0d68e37783f1cac9d1f075d8e95034
|
0e19f718f40786d44517d8f8fbd341e05a92b649
|
refs/heads/master
| 2023-09-03T19:16:34.938669
| 2023-08-17T23:08:32
| 2023-08-17T23:08:32
| 249,749,371
| 0
| 1
|
MIT
| 2023-08-17T23:08:34
| 2020-03-24T15:45:48
|
C
|
UTF-8
|
C++
| false
| false
| 1,074
|
cpp
|
/**
* \file test_compare_uint64.cpp
*
* Unit tests for compare_uint64.
*
* \copyright 2017-2023 Velo-Payments, Inc. All rights reserved.
*/
#include <vpr/compare.h>
#include <minunit/minunit.h>
#include <string.h>
TEST_SUITE(compare_uint64);
/**
* Test that comparing two uint64_t values that are equal results in 0.
*/
TEST(equality)
{
const uint64_t X = 17;
const uint64_t Y = 17;
TEST_EXPECT(0 == memcmp(&X, &Y, sizeof(uint64_t)));
TEST_EXPECT(0 == compare_uint64(&X, &Y, sizeof(uint64_t)));
}
/**
* Test that X > Y results in a return value that is greater than zero.
*/
TEST(greater_than)
{
const uint64_t X = 17;
const uint64_t Y = 14;
TEST_EXPECT(0 < memcmp(&X, &Y, sizeof(uint64_t)));
TEST_EXPECT(0 < compare_uint64(&X, &Y, sizeof(uint64_t)));
}
/**
* Test that X < Y results in a return value that is less than zero.
*/
TEST(less_than)
{
const uint64_t X = 17;
const uint64_t Y = 19;
TEST_EXPECT(0 > memcmp(&X, &Y, sizeof(uint64_t)));
TEST_EXPECT(0 > compare_uint64(&X, &Y, sizeof(uint64_t)));
}
|
[
"nanolith@gmail.com"
] |
nanolith@gmail.com
|
984382e159ff2793d84240485334c873adeda010
|
1e0be6beadcdd136b1ec714ee3df463a38c559fa
|
/HDU/2031.cpp
|
e004bc9e90585d97e8d9c03624921dd982c26ea1
|
[] |
no_license
|
yukinoxita/AC_CODE
|
8172be6fc170acde67afd3f8101ef620ac4693ec
|
36588308831571cb13b4f5b105f92c7a6ffd3a84
|
refs/heads/master
| 2021-07-25T20:34:45.066631
| 2020-10-09T11:53:33
| 2020-10-09T11:53:33
| 224,656,641
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 720
|
cpp
|
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int n,r;
int bit[100];
char alpha[6]={'A','B','C','D','E','F'};
int sit;
bool flag;
void print()
{
int i;
if(flag)printf("-");
for(i=sit;i>=1;i--)
{
if(bit[i]<10)printf("%d",bit[i]);
else printf("%c",alpha[bit[i]%10]);//这一步能看懂吗
}
}
void kenkan()
{
int num = n;
sit = 0 ;
while(num)
{
bit[++sit] = num % r;
num /= r;
}
}
int main()
{
int i,j;
freopen("2.in","r",stdin);
while(scanf("%d%d",&n,&r)!=EOF)
{
flag = false;
if(n<0){flag = true;n = -n;}
kenkan();
print();
printf("\n");
}
return 0;
}
|
[
"m1091057545@163.com"
] |
m1091057545@163.com
|
bc26e47505adec98492e9866813edb18b0f0f371
|
c6389f9b11fd40ee9295f4e88a14a8057e294e4f
|
/components/asio/asio/asio/include/asio/detail/win_iocp_socket_accept_op.hpp
|
0aa850fde3257b279f7f6c060ff8f1f504000233
|
[
"MIT",
"BSL-1.0"
] |
permissive
|
ghsecuritylab/N14
|
987ebb27cfbd7ebf84deadeb09a480aa51be34c7
|
76bc595e3face0903436e48165f31724e4d4532a
|
refs/heads/master
| 2021-02-28T19:46:09.834253
| 2019-11-19T14:36:58
| 2019-11-19T14:36:58
| 245,728,464
| 0
| 0
|
MIT
| 2020-03-08T00:40:31
| 2020-03-08T00:40:30
| null |
UTF-8
|
C++
| false
| false
| 9,639
|
hpp
|
//
// detail/win_iocp_socket_accept_op.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP
#define ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#if defined(ASIO_HAS_IOCP)
#include "asio/detail/bind_handler.hpp"
#include "asio/detail/buffer_sequence_adapter.hpp"
#include "asio/detail/fenced_block.hpp"
#include "asio/detail/handler_alloc_helpers.hpp"
#include "asio/detail/handler_invoke_helpers.hpp"
#include "asio/detail/memory.hpp"
#include "asio/detail/operation.hpp"
#include "asio/detail/socket_ops.hpp"
#include "asio/detail/win_iocp_socket_service_base.hpp"
#include "asio/error.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace detail {
template <typename Socket, typename Protocol, typename Handler>
class win_iocp_socket_accept_op : public operation
{
public:
ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_accept_op);
win_iocp_socket_accept_op(win_iocp_socket_service_base& socket_service,
socket_type socket, Socket& peer, const Protocol& protocol,
typename Protocol::endpoint* peer_endpoint,
bool enable_connection_aborted, Handler& handler)
: operation(&win_iocp_socket_accept_op::do_complete),
socket_service_(socket_service),
socket_(socket),
peer_(peer),
protocol_(protocol),
peer_endpoint_(peer_endpoint),
enable_connection_aborted_(enable_connection_aborted),
handler_(ASIO_MOVE_CAST(Handler)(handler))
{
handler_work<Handler>::start(handler_);
}
socket_holder& new_socket()
{
return new_socket_;
}
void* output_buffer()
{
return output_buffer_;
}
DWORD address_length()
{
return sizeof(sockaddr_storage_type) + 16;
}
static void do_complete(void* owner, operation* base,
const asio::error_code& result_ec,
std::size_t /*bytes_transferred*/)
{
asio::error_code ec(result_ec);
// Take ownership of the operation object.
win_iocp_socket_accept_op* o(static_cast<win_iocp_socket_accept_op*>(base));
ptr p = { asio::detail::addressof(o->handler_), o, o };
handler_work<Handler> w(o->handler_);
if (owner)
{
typename Protocol::endpoint peer_endpoint;
std::size_t addr_len = peer_endpoint.capacity();
socket_ops::complete_iocp_accept(o->socket_,
o->output_buffer(), o->address_length(),
peer_endpoint.data(), &addr_len,
o->new_socket_.get(), ec);
// Restart the accept operation if we got the connection_aborted error
// and the enable_connection_aborted socket option is not set.
if (ec == asio::error::connection_aborted
&& !o->enable_connection_aborted_)
{
o->reset();
o->socket_service_.restart_accept_op(o->socket_,
o->new_socket_, o->protocol_.family(),
o->protocol_.type(), o->protocol_.protocol(),
o->output_buffer(), o->address_length(), o);
p.v = p.p = 0;
return;
}
// If the socket was successfully accepted, transfer ownership of the
// socket to the peer object.
if (!ec)
{
o->peer_.assign(o->protocol_,
typename Socket::native_handle_type(
o->new_socket_.get(), peer_endpoint), ec);
if (!ec)
o->new_socket_.release();
}
// Pass endpoint back to caller.
if (o->peer_endpoint_)
*o->peer_endpoint_ = peer_endpoint;
}
ASIO_HANDLER_COMPLETION((*o));
// Make a copy of the handler so that the memory can be deallocated before
// the upcall is made. Even if we're not about to make an upcall, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
detail::binder1<Handler, asio::error_code>
handler(o->handler_, ec);
p.h = asio::detail::addressof(handler.handler_);
p.reset();
// Make the upcall if required.
if (owner)
{
fenced_block b(fenced_block::half);
ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_));
w.complete(handler, handler.handler_);
ASIO_HANDLER_INVOCATION_END;
}
}
private:
win_iocp_socket_service_base& socket_service_;
socket_type socket_;
socket_holder new_socket_;
Socket& peer_;
Protocol protocol_;
typename Protocol::endpoint* peer_endpoint_;
unsigned char output_buffer_[(sizeof(sockaddr_storage_type) + 16) * 2];
bool enable_connection_aborted_;
Handler handler_;
};
#if defined(ASIO_HAS_MOVE)
template <typename Protocol, typename Handler>
class win_iocp_socket_move_accept_op : public operation
{
public:
ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_move_accept_op);
win_iocp_socket_move_accept_op(
win_iocp_socket_service_base& socket_service, socket_type socket,
const Protocol& protocol, asio::io_context& peer_io_context,
typename Protocol::endpoint* peer_endpoint,
bool enable_connection_aborted, Handler& handler)
: operation(&win_iocp_socket_move_accept_op::do_complete),
socket_service_(socket_service),
socket_(socket),
peer_(peer_io_context),
protocol_(protocol),
peer_endpoint_(peer_endpoint),
enable_connection_aborted_(enable_connection_aborted),
handler_(ASIO_MOVE_CAST(Handler)(handler))
{
handler_work<Handler>::start(handler_);
}
socket_holder& new_socket()
{
return new_socket_;
}
void* output_buffer()
{
return output_buffer_;
}
DWORD address_length()
{
return sizeof(sockaddr_storage_type) + 16;
}
static void do_complete(void* owner, operation* base,
const asio::error_code& result_ec,
std::size_t /*bytes_transferred*/)
{
asio::error_code ec(result_ec);
// Take ownership of the operation object.
win_iocp_socket_move_accept_op* o(
static_cast<win_iocp_socket_move_accept_op*>(base));
ptr p = { asio::detail::addressof(o->handler_), o, o };
handler_work<Handler> w(o->handler_);
if (owner)
{
typename Protocol::endpoint peer_endpoint;
std::size_t addr_len = peer_endpoint.capacity();
socket_ops::complete_iocp_accept(o->socket_,
o->output_buffer(), o->address_length(),
peer_endpoint.data(), &addr_len,
o->new_socket_.get(), ec);
// Restart the accept operation if we got the connection_aborted error
// and the enable_connection_aborted socket option is not set.
if (ec == asio::error::connection_aborted
&& !o->enable_connection_aborted_)
{
o->reset();
o->socket_service_.restart_accept_op(o->socket_,
o->new_socket_, o->protocol_.family(),
o->protocol_.type(), o->protocol_.protocol(),
o->output_buffer(), o->address_length(), o);
p.v = p.p = 0;
return;
}
// If the socket was successfully accepted, transfer ownership of the
// socket to the peer object.
if (!ec)
{
o->peer_.assign(o->protocol_,
typename Protocol::socket::native_handle_type(
o->new_socket_.get(), peer_endpoint), ec);
if (!ec)
o->new_socket_.release();
}
// Pass endpoint back to caller.
if (o->peer_endpoint_)
*o->peer_endpoint_ = peer_endpoint;
}
ASIO_HANDLER_COMPLETION((*o));
// Make a copy of the handler so that the memory can be deallocated before
// the upcall is made. Even if we're not about to make an upcall, a
// sub-object of the handler may be the true owner of the memory associated
// with the handler. Consequently, a local copy of the handler is required
// to ensure that any owning sub-object remains valid until after we have
// deallocated the memory here.
detail::move_binder2<Handler,
asio::error_code, typename Protocol::socket>
handler(0, ASIO_MOVE_CAST(Handler)(o->handler_), ec,
ASIO_MOVE_CAST(typename Protocol::socket)(o->peer_));
p.h = asio::detail::addressof(handler.handler_);
p.reset();
// Make the upcall if required.
if (owner)
{
fenced_block b(fenced_block::half);
ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "..."));
w.complete(handler, handler.handler_);
ASIO_HANDLER_INVOCATION_END;
}
}
private:
win_iocp_socket_service_base& socket_service_;
socket_type socket_;
socket_holder new_socket_;
typename Protocol::socket peer_;
Protocol protocol_;
typename Protocol::endpoint* peer_endpoint_;
unsigned char output_buffer_[(sizeof(sockaddr_storage_type) + 16) * 2];
bool enable_connection_aborted_;
Handler handler_;
};
#endif // defined(ASIO_HAS_MOVE)
} // namespace detail
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // defined(ASIO_HAS_IOCP)
#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP
|
[
"qitas@qitas.cn"
] |
qitas@qitas.cn
|
d60d11fe7f2b6ec30443ca1cd6dfd57e4d227e37
|
02b8e4498a2c3d0b07d5718ab06934c9c812cffc
|
/pset1/test028.cc
|
fee5ad3e4ac3eaaa0a9f5916becab5be20f9622d
|
[] |
no_license
|
Ccolt/cs61
|
cbedb856fdc745c167b81adb4b84cf46545dee38
|
8f2076364cb5ad965746d69e64d3b55836cb88c6
|
refs/heads/master
| 2020-05-16T15:59:24.215495
| 2019-04-24T05:02:59
| 2019-04-24T05:02:59
| 183,148,059
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 506
|
cc
|
#include "m61.hh"
#include <stdio.h>
#include <assert.h>
#include <string.h>
// Memory leak report with no leaks.
struct node {
node* next;
};
int main() {
node* list = nullptr;
// create a list
for (int i = 0; i < 400; ++i) {
node* n = (node*) malloc(sizeof(node));
n->next = list;
list = n;
}
// free everything in it
while (node* n = list) {
list = n->next;
free(n);
}
m61_printleakreport();
printf("OK\n");
}
//! OK
|
[
"charlie.colt.simonds@gmail.com"
] |
charlie.colt.simonds@gmail.com
|
2446d40670afeb2af92ccf150c6a8688b7658e7e
|
fe39e4d1bca62d7bff7b6713b8b596d88f8aa354
|
/src/plugins/3rdparty/LLVM/tools/clang/lib/AST/VTTBuilder.cpp
|
24c1455df0ec1df99af9dba93f2ef6398a41e9c9
|
[] |
no_license
|
panpanSun/opencor
|
a29a806475f43adb0f64047631d4dc044f05e030
|
71449e1ecaa988ea8b6cfea7875d9f3593a8dc26
|
refs/heads/master
| 2020-12-24T11:53:33.902565
| 2013-04-20T18:59:29
| 2013-04-20T18:59:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,519
|
cpp
|
//===--- VTTBuilder.cpp - C++ VTT layout builder --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with generation of the layout of virtual table
// tables (VTT).
//
//===----------------------------------------------------------------------===//
#include "clang/AST/VTTBuilder.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/Support/Format.h"
#include <algorithm>
#include <cstdio>
using namespace clang;
#define DUMP_OVERRIDERS 0
VTTBuilder::VTTBuilder(ASTContext &Ctx,
const CXXRecordDecl *MostDerivedClass,
bool GenerateDefinition)
: Ctx(Ctx), MostDerivedClass(MostDerivedClass),
MostDerivedClassLayout(Ctx.getASTRecordLayout(MostDerivedClass)),
GenerateDefinition(GenerateDefinition) {
// Lay out this VTT.
LayoutVTT(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
/*BaseIsVirtual=*/false);
}
void VTTBuilder::AddVTablePointer(BaseSubobject Base, uint64_t VTableIndex,
const CXXRecordDecl *VTableClass) {
// Store the vtable pointer index if we're generating the primary VTT.
if (VTableClass == MostDerivedClass) {
assert(!SecondaryVirtualPointerIndices.count(Base) &&
"A virtual pointer index already exists for this base subobject!");
SecondaryVirtualPointerIndices[Base] = VTTComponents.size();
}
if (!GenerateDefinition) {
VTTComponents.push_back(VTTComponent());
return;
}
VTTComponents.push_back(VTTComponent(VTableIndex, Base));
}
void VTTBuilder::LayoutSecondaryVTTs(BaseSubobject Base) {
const CXXRecordDecl *RD = Base.getBase();
for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
E = RD->bases_end(); I != E; ++I) {
// Don't layout virtual bases.
if (I->isVirtual())
continue;
const CXXRecordDecl *BaseDecl =
cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
CharUnits BaseOffset = Base.getBaseOffset() +
Layout.getBaseClassOffset(BaseDecl);
// Layout the VTT for this base.
LayoutVTT(BaseSubobject(BaseDecl, BaseOffset), /*BaseIsVirtual=*/false);
}
}
void
VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base,
bool BaseIsMorallyVirtual,
uint64_t VTableIndex,
const CXXRecordDecl *VTableClass,
VisitedVirtualBasesSetTy &VBases) {
const CXXRecordDecl *RD = Base.getBase();
// We're not interested in bases that don't have virtual bases, and not
// morally virtual bases.
if (!RD->getNumVBases() && !BaseIsMorallyVirtual)
return;
for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
E = RD->bases_end(); I != E; ++I) {
const CXXRecordDecl *BaseDecl =
cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
// Itanium C++ ABI 2.6.2:
// Secondary virtual pointers are present for all bases with either
// virtual bases or virtual function declarations overridden along a
// virtual path.
//
// If the base class is not dynamic, we don't want to add it, nor any
// of its base classes.
if (!BaseDecl->isDynamicClass())
continue;
bool BaseDeclIsMorallyVirtual = BaseIsMorallyVirtual;
bool BaseDeclIsNonVirtualPrimaryBase = false;
CharUnits BaseOffset;
if (I->isVirtual()) {
// Ignore virtual bases that we've already visited.
if (!VBases.insert(BaseDecl))
continue;
BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
BaseDeclIsMorallyVirtual = true;
} else {
const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(RD);
BaseOffset = Base.getBaseOffset() +
Layout.getBaseClassOffset(BaseDecl);
if (!Layout.isPrimaryBaseVirtual() &&
Layout.getPrimaryBase() == BaseDecl)
BaseDeclIsNonVirtualPrimaryBase = true;
}
// Itanium C++ ABI 2.6.2:
// Secondary virtual pointers: for each base class X which (a) has virtual
// bases or is reachable along a virtual path from D, and (b) is not a
// non-virtual primary base, the address of the virtual table for X-in-D
// or an appropriate construction virtual table.
if (!BaseDeclIsNonVirtualPrimaryBase &&
(BaseDecl->getNumVBases() || BaseDeclIsMorallyVirtual)) {
// Add the vtable pointer.
AddVTablePointer(BaseSubobject(BaseDecl, BaseOffset), VTableIndex,
VTableClass);
}
// And lay out the secondary virtual pointers for the base class.
LayoutSecondaryVirtualPointers(BaseSubobject(BaseDecl, BaseOffset),
BaseDeclIsMorallyVirtual, VTableIndex,
VTableClass, VBases);
}
}
void
VTTBuilder::LayoutSecondaryVirtualPointers(BaseSubobject Base,
uint64_t VTableIndex) {
VisitedVirtualBasesSetTy VBases;
LayoutSecondaryVirtualPointers(Base, /*BaseIsMorallyVirtual=*/false,
VTableIndex, Base.getBase(), VBases);
}
void VTTBuilder::LayoutVirtualVTTs(const CXXRecordDecl *RD,
VisitedVirtualBasesSetTy &VBases) {
for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
E = RD->bases_end(); I != E; ++I) {
const CXXRecordDecl *BaseDecl =
cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
// Check if this is a virtual base.
if (I->isVirtual()) {
// Check if we've seen this base before.
if (!VBases.insert(BaseDecl))
continue;
CharUnits BaseOffset =
MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
LayoutVTT(BaseSubobject(BaseDecl, BaseOffset), /*BaseIsVirtual=*/true);
}
// We only need to layout virtual VTTs for this base if it actually has
// virtual bases.
if (BaseDecl->getNumVBases())
LayoutVirtualVTTs(BaseDecl, VBases);
}
}
void VTTBuilder::LayoutVTT(BaseSubobject Base, bool BaseIsVirtual) {
const CXXRecordDecl *RD = Base.getBase();
// Itanium C++ ABI 2.6.2:
// An array of virtual table addresses, called the VTT, is declared for
// each class type that has indirect or direct virtual base classes.
if (RD->getNumVBases() == 0)
return;
bool IsPrimaryVTT = Base.getBase() == MostDerivedClass;
if (!IsPrimaryVTT) {
// Remember the sub-VTT index.
SubVTTIndicies[Base] = VTTComponents.size();
}
uint64_t VTableIndex = VTTVTables.size();
VTTVTables.push_back(VTTVTable(Base, BaseIsVirtual));
// Add the primary vtable pointer.
AddVTablePointer(Base, VTableIndex, RD);
// Add the secondary VTTs.
LayoutSecondaryVTTs(Base);
// Add the secondary virtual pointers.
LayoutSecondaryVirtualPointers(Base, VTableIndex);
// If this is the primary VTT, we want to lay out virtual VTTs as well.
if (IsPrimaryVTT) {
VisitedVirtualBasesSetTy VBases;
LayoutVirtualVTTs(Base.getBase(), VBases);
}
}
|
[
"agarny@hellix.com"
] |
agarny@hellix.com
|
3668caf717d549c7f5ac6294f572325c009eaee3
|
35717ca2bb81d2c47d31e4cb9cc9fd8304aef09b
|
/CNN/layer.h
|
2f94956885a354dacf43435c96f791988ea3cf5f
|
[] |
no_license
|
advancer-debug/DECNN
|
05d4164f6999274c25369ad43a0a3a1519e43667
|
491c9af3591285f901adb2479303dce4a93575d1
|
refs/heads/master
| 2021-06-01T17:51:03.430121
| 2016-01-29T14:30:33
| 2016-01-29T14:30:33
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 7,145
|
h
|
/* FileName: layer.h */
#ifndef _LAYER_H_
#define _LAYER_H_
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "util.h"
using namespace std;
enum layer_type {
INPUT = 0,
CONV ,
POOL ,
FULLI,
HIDDEN ,
OUTPUT ,
};
class FeatureMap {
public:
double **_data;
int _c;
int _r;
FeatureMap() {}
void _set_size(int c, int r) {
_c = c;
_r = r;
_data = new double*[_r];
if ( NULL == _data ) {
cerr << "Error when allocate memory for FeatureMap!" << endl;
exit (0);
}
for ( int i = 0; i < r; i ++) {
_data[i] = new double[c];
if ( NULL == _data[i] ) {
cerr << "Error when allocate memory for FeatureMap!" << endl;
exit (0);
}
}
}
};
class Layer {
public:
FeatureMap* _o_fmap; // 输出FeatureMap
int _o_fmap_cnt; // 输出特征图数目
int _i_fmap_cnt; // 输入特征图数目
int _layer_type; // 层类型
double *_bias; // 输出特征图的偏置
int _o_fmap_r; // 输出FM的行
int _o_fmap_c; // 输出FeatureMap的列
/* FOR CONVOLUTION LAYER */
int _kernel_cnt; // 卷积核数量
int _kernel_c; // 卷积核行数
int _kernel_r; // 卷积核列数
double *** _kernel; // 卷积核
int **_connect_graph; // 输入FeatureMap和输出FeatureMap的连接图谱
/* FOR POOLING LAYER */
int _pool_r;
int _pool_c;
/* FOR FULLIN LAYER */
double *_full_input_v;
/* FOR OUTPUT LAYER */
int _i_neuo_cnt;
int _o_neuo_cnt; // 输出神经元数量
double **_w; // 输出层全连接权值
double *_o; // 输出
public:
Layer() {}
Layer(int i_fmap_cnt, int o_fmap_cnt, int o_fmap_r, int o_fmap_c) {
_o_fmap_cnt = o_fmap_cnt;
_i_fmap_cnt = i_fmap_cnt;
_o_fmap_r = o_fmap_r;
_o_fmap_c = o_fmap_c;
_o_fmap = new FeatureMap[_o_fmap_cnt];
for ( int i = 0; i < _o_fmap_cnt; i ++) {
_o_fmap[i]._set_size(_o_fmap_r, _o_fmap_c);
}
if ( NULL == _o_fmap ) {
cerr << "[ERROR] bad alloc for _io_con_index in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
}
~Layer() {
if ( NULL != _o_fmap ) {
delete[] _o_fmap;
_o_fmap = NULL;
}
}
FeatureMap*& _get_o_fmap() { return _o_fmap; }
int _get_o_fmap_cnt() const { return _o_fmap_cnt; }
int _get_i_fmap_cnt() const { return _i_fmap_cnt; }
/* FOR CONVOLUTION LAYER */
virtual void _init_connect_type(int** connect_graph) {} // 初始化连接方式
/* FOR INPUT LAYER */
virtual void _set_input_fmap(double *val) {}
virtual void _forward( Layer*& prior_layer) {}
};
class ConvolutionLayer : public Layer {
public:
~ConvolutionLayer() {}
ConvolutionLayer(
int kernel_r,
int kernel_c,
int o_fmap_r,
int o_fmap_c,
int o_fmap_cnt,
int i_fmap_cnt ) : Layer(i_fmap_cnt, o_fmap_cnt, o_fmap_r, o_fmap_c) {
_kernel_cnt = i_fmap_cnt * o_fmap_cnt;
_kernel_c = kernel_c;
_kernel_r = kernel_r;
_layer_type = CONV;
_kernel = new double**[_kernel_cnt];
if ( NULL == _kernel ) {
cerr << "[ERROR] bad alloc for _kernel in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
for ( int i = 0; i < _kernel_cnt; i ++) {
_kernel[i] = new double*[_kernel_r];
if ( NULL == _kernel[i] ) {
cerr << "[ERROR] bad alloc for _kernel[i] in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
for ( int j = 0; j < _kernel_r; j ++) {
_kernel[i][j] = new double[_kernel_c];
if ( NULL == _kernel[i][j] ) {
cerr << "[ERROR] bad alloc for _kernel[i][j] in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
}
}
_connect_graph = new int*[_o_fmap_cnt];
if ( NULL == _connect_graph ) {
cerr << "[ERROR] bad alloc for _connect_graph in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
for ( int i = 0; i < _o_fmap_cnt; i ++) {
_connect_graph[i] = new int[_i_fmap_cnt];
if ( NULL == _connect_graph[i] ) {
cerr << "[ERROR] bad alloc for _connect_graph in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
}
_bias = new double[_o_fmap_cnt];
if ( NULL == _bias ) {
cerr << "[ERROR] bad alloc for _bias in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
}
void _init_connect_type(int** connect_graph) ; // 初始化连接方式
void _forward( Layer*& prior_layer) ;
void _set_input_fmap(double *val) {}
};
class InputLayer : public Layer {
public:
InputLayer(
int o_fmap_r,
int o_fmap_c,
int o_fmap_cnt,
int i_fmap_cnt) : Layer(i_fmap_cnt, o_fmap_cnt, o_fmap_r, o_fmap_c) {
_layer_type = INPUT;
}
~InputLayer() {}
void _set_input_fmap(double *val) {
int pt = 0;
for ( int fcnt = 0; fcnt < _o_fmap_cnt; fcnt ++) {
for ( int i = 0; i < _o_fmap_r; i ++) {
for ( int j = 0; j < _o_fmap_c; j ++) {
_o_fmap[fcnt]._data[i][j] = val[pt ++];
}
}
}
}
void _init_connect_type(int** connect_graph) {} // 初始化连接方式
void _forward( Layer*& prior_layer) {}
};
class PoolingLayer : public Layer {
public:
PoolingLayer( int pool_r,
int pool_c,
int o_fmap_r,
int o_fmap_c,
int o_fmap_cnt,
int i_fmap_cnt) : Layer(i_fmap_cnt, o_fmap_cnt, o_fmap_r, o_fmap_c) {
_layer_type = POOL;
_pool_r = pool_r;
_pool_c = pool_c;
}
~PoolingLayer() {}
void _forward( Layer*& prior_layer) ;
void _init_connect_type(int** connect_graph) {} // 初始化连接方式
void _set_input_fmap(double *val) {}
};
// 全连接层的输入层
class FullInputLayer : public Layer {
public:
FullInputLayer() {
_layer_type = FULLI;
}
~FullInputLayer() {}
void _forward( Layer*& prior_layer) ;
void _init_connect_type(int** connect_graph) {} // 初始化连接方式
void _set_input_fmap(double *val) {}
};
class OutputLayer : public Layer {
public:
OutputLayer(int i_neuo_cnt,
int o_neuo_cnt) {
_i_neuo_cnt = i_neuo_cnt;
_o_neuo_cnt = o_neuo_cnt;
_o = new double[_o_neuo_cnt];
if ( NULL == _o ) {
cerr << "[ERROR] bad alloc for _o in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
_w = new double*[_i_neuo_cnt];
_layer_type = OUTPUT;
if ( NULL == _w ) {
cerr << "[ERROR] bad alloc for _w in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
for ( int i = 0; i < _i_neuo_cnt; i ++) {
_w[i] = new double[_o_neuo_cnt];
if ( NULL == _w[i] ) {
cerr << "[ERROR] bad alloc for _w[i] in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
}
_bias = new double[_o_neuo_cnt];
if ( NULL == _bias ) {
cerr << "[ERROR] bad alloc for _b in line:" << __LINE__ << " in file layer.h" << endl;
exit(0);
}
}
~ OutputLayer() {}
void _forward( Layer*& prior_layer) ;
void _init_connect_type(int** connect_graph) {} // 初始化连接方式
void _set_input_fmap(double *val) {}
};
#endif
|
[
"aron@aron-Precision-T1700.(none)"
] |
aron@aron-Precision-T1700.(none)
|
88efcf6033cddaf529613fd6665179e402d0ce7d
|
cae9a5e136cf191e3f71b48f70cae2d3f6a52bc8
|
/GroupGameDevTeam5/GroupGameDevTeam5/ImGui/imgui_widgets.cpp
|
1ace2ae85366c097533d40f694238ac8caa32f67
|
[
"MIT"
] |
permissive
|
DevDylans/GroupGameDevTeam5
|
2caf80415e3b8df1163b170b1e19fd197d9891ca
|
d11d3102e81e39ab41399dc90fbc93c7e8a8575e
|
refs/heads/master
| 2022-10-21T17:08:46.022139
| 2020-06-12T16:37:19
| 2020-06-12T16:37:19
| 259,376,325
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 372,520
|
cpp
|
// dear imgui, v1.77 WIP
// (widgets code)
/*
Index of this file:
// [SECTION] Forward Declarations
// [SECTION] Widgets: Text, etc.
// [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.)
// [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.)
// [SECTION] Widgets: ComboBox
// [SECTION] Data Type and Data Formatting Helpers
// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
// [SECTION] Widgets: InputText, InputTextMultiline
// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
// [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
// [SECTION] Widgets: Selectable
// [SECTION] Widgets: ListBox
// [SECTION] Widgets: PlotLines, PlotHistogram
// [SECTION] Widgets: Value helpers
// [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc.
// [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
// [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "pch.h"
#include "imgui.h"
#ifndef IMGUI_DISABLE
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include <ctype.h> // toupper
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
#endif
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
#endif
#if __has_warning("-Wdouble-promotion")
#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.
#endif
#if __has_warning("-Wdeprecated-enum-enum-conversion")
#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
//-------------------------------------------------------------------------
// Data
//-------------------------------------------------------------------------
// Those MIN/MAX values are not define because we need to point to them
static const signed char IM_S8_MIN = -128;
static const signed char IM_S8_MAX = 127;
static const unsigned char IM_U8_MIN = 0;
static const unsigned char IM_U8_MAX = 0xFF;
static const signed short IM_S16_MIN = -32768;
static const signed short IM_S16_MAX = 32767;
static const unsigned short IM_U16_MIN = 0;
static const unsigned short IM_U16_MAX = 0xFFFF;
static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000);
static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF)
static const ImU32 IM_U32_MIN = 0;
static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF)
#ifdef LLONG_MIN
static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll);
static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll);
#else
static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1;
static const ImS64 IM_S64_MAX = 9223372036854775807LL;
#endif
static const ImU64 IM_U64_MIN = 0;
#ifdef ULLONG_MAX
static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull);
#else
static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1);
#endif
//-------------------------------------------------------------------------
// [SECTION] Forward Declarations
//-------------------------------------------------------------------------
// For InputTextEx()
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data);
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
//-------------------------------------------------------------------------
// [SECTION] Widgets: Text, etc.
//-------------------------------------------------------------------------
// - TextEx() [Internal]
// - TextUnformatted()
// - Text()
// - TextV()
// - TextColored()
// - TextColoredV()
// - TextDisabled()
// - TextDisabledV()
// - TextWrapped()
// - TextWrappedV()
// - LabelText()
// - LabelTextV()
// - BulletText()
// - BulletTextV()
//-------------------------------------------------------------------------
void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
IM_ASSERT(text != NULL);
const char* text_begin = text;
if (text_end == NULL)
text_end = text + strlen(text); // FIXME-OPT
const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
const float wrap_pos_x = window->DC.TextWrapPos;
const bool wrap_enabled = (wrap_pos_x >= 0.0f);
if (text_end - text > 2000 && !wrap_enabled)
{
// Long text!
// Perform manual coarse clipping to optimize for long multi-line text
// - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
// - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
// - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
const char* line = text;
const float line_height = GetTextLineHeight();
ImVec2 text_size(0,0);
// Lines to skip (can't skip when logging text)
ImVec2 pos = text_pos;
if (!g.LogEnabled)
{
int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height);
if (lines_skippable > 0)
{
int lines_skipped = 0;
while (line < text_end && lines_skipped < lines_skippable)
{
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
line = line_end + 1;
lines_skipped++;
}
pos.y += lines_skipped * line_height;
}
}
// Lines to render
if (line < text_end)
{
ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
while (line < text_end)
{
if (IsClippedEx(line_rect, 0, false))
break;
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
RenderText(pos, line, line_end, false);
line = line_end + 1;
line_rect.Min.y += line_height;
line_rect.Max.y += line_height;
pos.y += line_height;
}
// Count remaining lines
int lines_skipped = 0;
while (line < text_end)
{
const char* line_end = (const char*)memchr(line, '\n', text_end - line);
if (!line_end)
line_end = text_end;
if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
line = line_end + 1;
lines_skipped++;
}
pos.y += lines_skipped * line_height;
}
text_size.y = (pos - text_pos).y;
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size, 0.0f);
ItemAdd(bb, 0);
}
else
{
const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size, 0.0f);
if (!ItemAdd(bb, 0))
return;
// Render (we don't hide text after ## in this end-user function)
RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
}
}
void ImGui::TextUnformatted(const char* text, const char* text_end)
{
TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
}
void ImGui::Text(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextV(fmt, args);
va_end(args);
}
void ImGui::TextV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
TextEx(g.TempBuffer, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
}
void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextColoredV(col, fmt, args);
va_end(args);
}
void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, col);
TextV(fmt, args);
PopStyleColor();
}
void ImGui::TextDisabled(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextDisabledV(fmt, args);
va_end(args);
}
void ImGui::TextDisabledV(const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
TextV(fmt, args);
PopStyleColor();
}
void ImGui::TextWrapped(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextWrappedV(fmt, args);
va_end(args);
}
void ImGui::TextWrappedV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
bool need_backup = (window->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set
if (need_backup)
PushTextWrapPos(0.0f);
TextV(fmt, args);
if (need_backup)
PopTextWrapPos();
}
void ImGui::LabelText(const char* label, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
LabelTextV(label, fmt, args);
va_end(args);
}
// Add a label+text combo aligned to other label+value widgets
void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size);
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0))
return;
// Render
const char* value_text_begin = &g.TempBuffer[0];
const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
}
void ImGui::BulletText(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
BulletTextV(fmt, args);
va_end(args);
}
// Text with a little bullet aligned to the typical tree node.
void ImGui::BulletTextV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const char* text_begin = g.TempBuffer;
const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
const ImVec2 total_size = ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x * 2) : 0.0f), label_size.y); // Empty text doesn't add padding
ImVec2 pos = window->DC.CursorPos;
pos.y += window->DC.CurrLineTextBaseOffset;
ItemSize(total_size, 0.0f);
const ImRect bb(pos, pos + total_size);
if (!ItemAdd(bb, 0))
return;
// Render
ImU32 text_col = GetColorU32(ImGuiCol_Text);
RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, g.FontSize*0.5f), text_col);
RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Main
//-------------------------------------------------------------------------
// - ButtonBehavior() [Internal]
// - Button()
// - SmallButton()
// - InvisibleButton()
// - ArrowButton()
// - CloseButton() [Internal]
// - CollapseButton() [Internal]
// - GetWindowScrollbarID() [Internal]
// - GetWindowScrollbarRect() [Internal]
// - Scrollbar() [Internal]
// - ScrollbarEx() [Internal]
// - Image()
// - ImageButton()
// - Checkbox()
// - CheckboxFlags()
// - RadioButton()
// - ProgressBar()
// - Bullet()
//-------------------------------------------------------------------------
// The ButtonBehavior() function is key to many interactions and used by many/most widgets.
// Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_),
// this code is a little complex.
// By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior.
// See the series of events below and the corresponding state reported by dear imgui:
//------------------------------------------------------------------------------------------------------------------------------------------------
// with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
// Frame N+0 (mouse is outside bb) - - - - - -
// Frame N+1 (mouse moves inside bb) - true - - - -
// Frame N+2 (mouse button is down) - true true true - true
// Frame N+3 (mouse button is down) - true true - - -
// Frame N+4 (mouse moves outside bb) - - true - - -
// Frame N+5 (mouse moves inside bb) - true true - - -
// Frame N+6 (mouse button is released) true true - - true -
// Frame N+7 (mouse button is released) - true - - - -
// Frame N+8 (mouse moves outside bb) - - - - - -
//------------------------------------------------------------------------------------------------------------------------------------------------
// with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
// Frame N+2 (mouse button is down) true true true true - true
// Frame N+3 (mouse button is down) - true true - - -
// Frame N+6 (mouse button is released) - true - - true -
// Frame N+7 (mouse button is released) - true - - - -
//------------------------------------------------------------------------------------------------------------------------------------------------
// with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
// Frame N+2 (mouse button is down) - true - - - true
// Frame N+3 (mouse button is down) - true - - - -
// Frame N+6 (mouse button is released) true true - - - -
// Frame N+7 (mouse button is released) - true - - - -
//------------------------------------------------------------------------------------------------------------------------------------------------
// with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
// Frame N+0 (mouse button is down) - true - - - true
// Frame N+1 (mouse button is down) - true - - - -
// Frame N+2 (mouse button is released) - true - - - -
// Frame N+3 (mouse button is released) - true - - - -
// Frame N+4 (mouse button is down) true true true true - true
// Frame N+5 (mouse button is down) - true true - - -
// Frame N+6 (mouse button is released) - true - - true -
// Frame N+7 (mouse button is released) - true - - - -
//------------------------------------------------------------------------------------------------------------------------------------------------
// Note that some combinations are supported,
// - PressedOnDragDropHold can generally be associated with any flag.
// - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported.
//------------------------------------------------------------------------------------------------------------------------------------------------
// The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set:
// Repeat+ Repeat+ Repeat+ Repeat+
// PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick
//-------------------------------------------------------------------------------------------------------------------------------------------------
// Frame N+0 (mouse button is down) - true - true
// ... - - - -
// Frame N + RepeatDelay true true - true
// ... - - - -
// Frame N + RepeatDelay + RepeatRate*N true true - true
//-------------------------------------------------------------------------------------------------------------------------------------------------
bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (flags & ImGuiButtonFlags_Disabled)
{
if (out_hovered) *out_hovered = false;
if (out_held) *out_held = false;
if (g.ActiveId == id) ClearActiveID();
return false;
}
// Default only reacts to left mouse button
if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0)
flags |= ImGuiButtonFlags_MouseButtonDefault_;
// Default behavior requires click + release inside bounding box
if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0)
flags |= ImGuiButtonFlags_PressedOnDefault_;
ImGuiWindow* backup_hovered_window = g.HoveredWindow;
const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window;
if (flatten_hovered_children)
g.HoveredWindow = window;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0 && window->DC.LastItemId != id)
IMGUI_TEST_ENGINE_ITEM_ADD(bb, id);
#endif
bool pressed = false;
bool hovered = ItemHoverable(bb, id);
// Drag source doesn't report as hovered
if (hovered && g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
hovered = false;
// Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
{
const float DRAG_DROP_HOLD_TIMER = 0.70f;
hovered = true;
SetHoveredID(id);
if (CalcTypematicRepeatAmount(g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, g.HoveredIdTimer + 0.0001f, DRAG_DROP_HOLD_TIMER, 0.00f))
{
pressed = true;
g.DragDropHoldJustPressedId = id;
FocusWindow(window);
}
}
if (flatten_hovered_children)
g.HoveredWindow = backup_hovered_window;
// AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
hovered = false;
// Mouse handling
if (hovered)
{
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
// Poll buttons
int mouse_button_clicked = -1;
int mouse_button_released = -1;
if ((flags & ImGuiButtonFlags_MouseButtonLeft) && g.IO.MouseClicked[0]) { mouse_button_clicked = 0; }
else if ((flags & ImGuiButtonFlags_MouseButtonRight) && g.IO.MouseClicked[1]) { mouse_button_clicked = 1; }
else if ((flags & ImGuiButtonFlags_MouseButtonMiddle) && g.IO.MouseClicked[2]) { mouse_button_clicked = 2; }
if ((flags & ImGuiButtonFlags_MouseButtonLeft) && g.IO.MouseReleased[0]) { mouse_button_released = 0; }
else if ((flags & ImGuiButtonFlags_MouseButtonRight) && g.IO.MouseReleased[1]) { mouse_button_released = 1; }
else if ((flags & ImGuiButtonFlags_MouseButtonMiddle) && g.IO.MouseReleased[2]) { mouse_button_released = 2; }
if (mouse_button_clicked != -1 && g.ActiveId != id)
{
if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere))
{
SetActiveID(id, window);
g.ActiveIdMouseButton = mouse_button_clicked;
if (!(flags & ImGuiButtonFlags_NoNavFocus))
SetFocusID(id, window);
FocusWindow(window);
}
if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[mouse_button_clicked]))
{
pressed = true;
if (flags & ImGuiButtonFlags_NoHoldingActiveId)
ClearActiveID();
else
SetActiveID(id, window); // Hold on ID
g.ActiveIdMouseButton = mouse_button_clicked;
FocusWindow(window);
}
}
if ((flags & ImGuiButtonFlags_PressedOnRelease) && mouse_button_released != -1)
{
// Repeat mode trumps on release behavior
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay))
pressed = true;
ClearActiveID();
}
// 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
// Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
if (g.ActiveId == id && (flags & ImGuiButtonFlags_Repeat))
if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, true))
pressed = true;
}
if (pressed)
g.NavDisableHighlight = true;
}
// Gamepad/Keyboard navigation
// We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse.
if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId))
if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))
hovered = true;
if (g.NavActivateDownId == id)
{
bool nav_activated_by_code = (g.NavActivateId == id);
bool nav_activated_by_inputs = IsNavInputTest(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed);
if (nav_activated_by_code || nav_activated_by_inputs)
pressed = true;
if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id)
{
// Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
g.NavActivateId = id; // This is so SetActiveId assign a Nav source
SetActiveID(id, window);
if ((nav_activated_by_code || nav_activated_by_inputs) && !(flags & ImGuiButtonFlags_NoNavFocus))
SetFocusID(id, window);
}
}
bool held = false;
if (g.ActiveId == id)
{
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (g.ActiveIdIsJustActivated)
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
const int mouse_button = g.ActiveIdMouseButton;
IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
if (g.IO.MouseDown[mouse_button])
{
held = true;
}
else
{
bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0;
bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0;
if ((release_in || release_anywhere) && !g.DragDropActive)
{
bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDownWasDoubleClick[mouse_button];
bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps <on release>
if (!is_double_click_release && !is_repeating_already)
pressed = true;
}
ClearActiveID();
}
if (!(flags & ImGuiButtonFlags_NoNavFocus))
g.NavDisableHighlight = true;
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
if (g.NavActivateDownId != id)
ClearActiveID();
}
if (pressed)
g.ActiveIdHasBeenPressedBefore = true;
}
if (out_hovered) *out_hovered = hovered;
if (out_held) *out_held = held;
return pressed;
}
bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y;
ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
const ImRect bb(pos, pos + size);
ItemSize(size, style.FramePadding.y);
if (!ItemAdd(bb, id))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed;
}
bool ImGui::Button(const char* label, const ImVec2& size_arg)
{
return ButtonEx(label, size_arg, 0);
}
// Small buttons fits within text without additional vertical spacing.
bool ImGui::SmallButton(const char* label)
{
ImGuiContext& g = *GImGui;
float backup_padding_y = g.Style.FramePadding.y;
g.Style.FramePadding.y = 0.0f;
bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine);
g.Style.FramePadding.y = backup_padding_y;
return pressed;
}
// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
// Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size.
IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f);
const ImGuiID id = window->GetID(str_id);
ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(size);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
return pressed;
}
bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(str_id);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
const float default_size = GetFrameHeight();
ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : -1.0f);
if (!ItemAdd(bb, id))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
const ImU32 text_col = GetColorU32(ImGuiCol_Text);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding);
RenderArrow(window->DrawList, bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), text_col, dir);
return pressed;
}
bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
{
float sz = GetFrameHeight();
return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None);
}
// Button to close a window
bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)//, float size)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window.
// (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible).
const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f);
bool is_clipped = !ItemAdd(bb, id);
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
if (is_clipped)
return pressed;
// Render
ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered);
ImVec2 center = bb.GetCenter();
if (hovered)
window->DrawList->AddCircleFilled(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col, 12);
float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;
ImU32 cross_col = GetColorU32(ImGuiCol_Text);
center -= ImVec2(0.5f, 0.5f);
window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f);
window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f);
return pressed;
}
bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f);
ItemAdd(bb, id);
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);
// Render
ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
ImU32 text_col = GetColorU32(ImGuiCol_Text);
ImVec2 center = bb.GetCenter();
if (hovered || held)
window->DrawList->AddCircleFilled(center/*+ ImVec2(0.0f, -0.5f)*/, g.FontSize * 0.5f + 1.0f, bg_col, 12);
RenderArrow(window->DrawList, bb.Min + g.Style.FramePadding, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
// Switch to moving the window after mouse is moved beyond the initial drag threshold
if (IsItemActive() && IsMouseDragging(0))
StartMouseMovingWindow(window);
return pressed;
}
ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
{
return window->GetIDNoKeepAlive(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY");
}
// Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set.
ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis)
{
const ImRect outer_rect = window->Rect();
const ImRect inner_rect = window->InnerRect;
const float border_size = window->WindowBorderSize;
const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar)
IM_ASSERT(scrollbar_size > 0.0f);
if (axis == ImGuiAxis_X)
return ImRect(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x, outer_rect.Max.y);
else
return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y, outer_rect.Max.x, inner_rect.Max.y);
}
void ImGui::Scrollbar(ImGuiAxis axis)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = GetWindowScrollbarID(window, axis);
KeepAliveID(id);
// Calculate scrollbar bounding box
ImRect bb = GetWindowScrollbarRect(window, axis);
ImDrawCornerFlags rounding_corners = 0;
if (axis == ImGuiAxis_X)
{
rounding_corners |= ImDrawCornerFlags_BotLeft;
if (!window->ScrollbarY)
rounding_corners |= ImDrawCornerFlags_BotRight;
}
else
{
if ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar))
rounding_corners |= ImDrawCornerFlags_TopRight;
if (!window->ScrollbarX)
rounding_corners |= ImDrawCornerFlags_BotRight;
}
float size_avail = window->InnerRect.Max[axis] - window->InnerRect.Min[axis];
float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f;
ScrollbarEx(bb, id, axis, &window->Scroll[axis], size_avail, size_contents, rounding_corners);
}
// Vertical/Horizontal scrollbar
// The entire piece of code below is rather confusing because:
// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
// Still, the code should probably be made simpler..
bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, float* p_scroll_v, float size_avail_v, float size_contents_v, ImDrawCornerFlags rounding_corners)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
const float bb_frame_width = bb_frame.GetWidth();
const float bb_frame_height = bb_frame.GetHeight();
if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f)
return false;
// When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the window resize grab)
float alpha = 1.0f;
if ((axis == ImGuiAxis_Y) && bb_frame_height < g.FontSize + g.Style.FramePadding.y * 2.0f)
alpha = ImSaturate((bb_frame_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f));
if (alpha <= 0.0f)
return false;
const ImGuiStyle& style = g.Style;
const bool allow_interaction = (alpha >= 1.0f);
ImRect bb = bb_frame;
bb.Expand(ImVec2(-ImClamp(IM_FLOOR((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_FLOOR((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f)));
// V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight();
// Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
// But we maintain a minimum size in pixel to allow for the user to still aim inside.
IM_ASSERT(ImMax(size_contents_v, size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
const float win_size_v = ImMax(ImMax(size_contents_v, size_avail_v), 1.0f);
const float grab_h_pixels = ImClamp(scrollbar_size_v * (size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v);
const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
// Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
bool held = false;
bool hovered = false;
ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
float scroll_max = ImMax(1.0f, size_contents_v - size_avail_v);
float scroll_ratio = ImSaturate(*p_scroll_v / scroll_max);
float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Grab position in normalized space
if (held && allow_interaction && grab_h_norm < 1.0f)
{
float scrollbar_pos_v = bb.Min[axis];
float mouse_pos_v = g.IO.MousePos[axis];
// Click position in scrollbar normalized space (0.0f->1.0f)
const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
SetHoveredID(id);
bool seek_absolute = false;
if (g.ActiveIdIsJustActivated)
{
// On initial click calculate the distance between mouse and the center of the grab
seek_absolute = (clicked_v_norm < grab_v_norm || clicked_v_norm > grab_v_norm + grab_h_norm);
if (seek_absolute)
g.ScrollbarClickDeltaToGrabCenter = 0.0f;
else
g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;
}
// Apply scroll (p_scroll_v will generally point on one member of window->Scroll)
// It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position
const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm));
*p_scroll_v = IM_ROUND(scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
// Update values for rendering
scroll_ratio = ImSaturate(*p_scroll_v / scroll_max);
grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
// Update distance to grab now that we have seeked and saturated
if (seek_absolute)
g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;
}
// Render
const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg);
const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);
window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, rounding_corners);
ImRect grab_rect;
if (axis == ImGuiAxis_X)
grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y);
else
grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels);
window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
return held;
}
void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
if (border_col.w > 0.0f)
bb.Max += ImVec2(2, 2);
ItemSize(bb);
if (!ItemAdd(bb, 0))
return;
if (border_col.w > 0.0f)
{
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col));
}
else
{
window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
}
}
// frame_padding < 0: uses FramePadding from style (default)
// frame_padding = 0: no framing
// frame_padding > 0: set framing size
// The color used are the button colors.
bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
// Default to using texture ID as ID. User can still push string/integer prefixes.
// We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
PushID((void*)(intptr_t)user_texture_id);
const ImGuiID id = window->GetID("#image");
PopID();
const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2);
const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
if (bg_col.w > 0.0f)
window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
return pressed;
}
bool ImGui::Checkbox(const char* label, bool* v)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float square_sz = GetFrameHeight();
const ImVec2 pos = window->DC.CursorPos;
const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
{
*v = !(*v);
MarkItemEdited(id);
}
const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
RenderNavHighlight(total_bb, id);
RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
ImU32 check_col = GetColorU32(ImGuiCol_CheckMark);
if (window->DC.ItemFlags & ImGuiItemFlags_MixedValue)
{
// Undocumented tristate/mixed/indeterminate checkbox (#2644)
ImVec2 pad(ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)), ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)));
window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding);
}
else if (*v)
{
const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f));
RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad*2.0f);
}
if (g.LogEnabled)
LogRenderedText(&total_bb.Min, *v ? "[x]" : "[ ]");
if (label_size.x > 0.0f)
RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
return pressed;
}
bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
{
bool v = ((*flags & flags_value) == flags_value);
bool pressed = Checkbox(label, &v);
if (pressed)
{
if (v)
*flags |= flags_value;
else
*flags &= ~flags_value;
}
return pressed;
}
bool ImGui::RadioButton(const char* label, bool active)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float square_sz = GetFrameHeight();
const ImVec2 pos = window->DC.CursorPos;
const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id))
return false;
ImVec2 center = check_bb.GetCenter();
center.x = IM_ROUND(center.x);
center.y = IM_ROUND(center.y);
const float radius = (square_sz - 1.0f) * 0.5f;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
MarkItemEdited(id);
RenderNavHighlight(total_bb, id);
window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
if (active)
{
const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f));
window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark), 16);
}
if (style.FrameBorderSize > 0.0f)
{
window->DrawList->AddCircle(center + ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);
window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize);
}
if (g.LogEnabled)
LogRenderedText(&total_bb.Min, active ? "(x)" : "( )");
if (label_size.x > 0.0f)
RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return pressed;
}
// FIXME: This would work nicely if it was a public template, e.g. 'template<T> RadioButton(const char* label, T* v, T v_button)', but I'm not sure how we would expose it..
bool ImGui::RadioButton(const char* label, int* v, int v_button)
{
const bool pressed = RadioButton(label, *v == v_button);
if (pressed)
*v = v_button;
return pressed;
}
// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f);
ImRect bb(pos, pos + size);
ItemSize(size, style.FramePadding.y);
if (!ItemAdd(bb, 0))
return;
// Render
fraction = ImSaturate(fraction);
RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);
// Default displaying the fraction as percentage string, but user can override it
char overlay_buf[32];
if (!overlay)
{
ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
overlay = overlay_buf;
}
ImVec2 overlay_size = CalcTextSize(overlay, NULL);
if (overlay_size.x > 0.0f)
RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb);
}
void ImGui::Bullet()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
ItemSize(bb);
if (!ItemAdd(bb, 0))
{
SameLine(0, style.FramePadding.x*2);
return;
}
// Render and stay on same line
ImU32 text_col = GetColorU32(ImGuiCol_Text);
RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f), text_col);
SameLine(0, style.FramePadding.x * 2.0f);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Low-level Layout helpers
//-------------------------------------------------------------------------
// - Spacing()
// - Dummy()
// - NewLine()
// - AlignTextToFramePadding()
// - SeparatorEx() [Internal]
// - Separator()
// - SplitterBehavior() [Internal]
// - ShrinkWidths() [Internal]
//-------------------------------------------------------------------------
void ImGui::Spacing()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ItemSize(ImVec2(0,0));
}
void ImGui::Dummy(const ImVec2& size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(size);
ItemAdd(bb, 0);
}
void ImGui::NewLine()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
ItemSize(ImVec2(0,0));
else
ItemSize(ImVec2(0.0f, g.FontSize));
window->DC.LayoutType = backup_layout_type;
}
void ImGui::AlignTextToFramePadding()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2);
window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y);
}
// Horizontal/vertical separating line
void ImGui::SeparatorEx(ImGuiSeparatorFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected
float thickness_draw = 1.0f;
float thickness_layout = 0.0f;
if (flags & ImGuiSeparatorFlags_Vertical)
{
// Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout.
float y1 = window->DC.CursorPos.y;
float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y;
const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness_draw, y2));
ItemSize(ImVec2(thickness_layout, 0.0f));
if (!ItemAdd(bb, 0))
return;
// Draw
window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator));
if (g.LogEnabled)
LogText(" |");
}
else if (flags & ImGuiSeparatorFlags_Horizontal)
{
// Horizontal Separator
float x1 = window->Pos.x;
float x2 = window->Pos.x + window->Size.x;
if (!window->DC.GroupStack.empty())
x1 += window->DC.Indent.x;
ImGuiColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL;
if (columns)
PushColumnsBackground();
// We don't provide our width to the layout so that it doesn't get feed back into AutoFit
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness_draw));
ItemSize(ImVec2(0.0f, thickness_layout));
const bool item_visible = ItemAdd(bb, 0);
if (item_visible)
{
// Draw
window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), GetColorU32(ImGuiCol_Separator));
if (g.LogEnabled)
LogRenderedText(&bb.Min, "--------------------------------");
}
if (columns)
{
PopColumnsBackground();
columns->LineMinY = window->DC.CursorPos.y;
}
}
}
void ImGui::Separator()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// Those flags should eventually be overridable by the user
ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
flags |= ImGuiSeparatorFlags_SpanAllColumns;
SeparatorEx(flags);
}
// Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise.
bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;
bool item_add = ItemAdd(bb, id);
window->DC.ItemFlags = item_flags_backup;
if (!item_add)
return false;
bool hovered, held;
ImRect bb_interact = bb;
bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap);
if (g.ActiveId != id)
SetItemAllowOverlap();
if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay))
SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
ImRect bb_render = bb;
if (held)
{
ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min;
float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x;
// Minimum pane size
float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1);
float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2);
if (mouse_delta < -size_1_maximum_delta)
mouse_delta = -size_1_maximum_delta;
if (mouse_delta > size_2_maximum_delta)
mouse_delta = size_2_maximum_delta;
// Apply resize
if (mouse_delta != 0.0f)
{
if (mouse_delta < 0.0f)
IM_ASSERT(*size1 + mouse_delta >= min_size1);
if (mouse_delta > 0.0f)
IM_ASSERT(*size2 - mouse_delta >= min_size2);
*size1 += mouse_delta;
*size2 -= mouse_delta;
bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
MarkItemEdited(id);
}
}
// Render
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, 0.0f);
return held;
}
static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs)
{
const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs;
const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs;
if (int d = (int)(b->Width - a->Width))
return d;
return (b->Index - a->Index);
}
// Shrink excess width from a set of item, by removing width from the larger items first.
void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess)
{
if (count == 1)
{
items[0].Width = ImMax(items[0].Width - width_excess, 1.0f);
return;
}
ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer);
int count_same_width = 1;
while (width_excess > 0.0f && count_same_width < count)
{
while (count_same_width < count && items[0].Width <= items[count_same_width].Width)
count_same_width++;
float max_width_to_remove_per_item = (count_same_width < count) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f);
float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item);
for (int item_n = 0; item_n < count_same_width; item_n++)
items[item_n].Width -= width_to_remove_per_item;
width_excess -= width_to_remove_per_item * count_same_width;
}
// Round width and redistribute remainder left-to-right (could make it an option of the function?)
// Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator.
width_excess = 0.0f;
for (int n = 0; n < count; n++)
{
float width_rounded = ImFloor(items[n].Width);
width_excess += items[n].Width - width_rounded;
items[n].Width = width_rounded;
}
if (width_excess > 0.0f)
for (int n = 0; n < count; n++)
if (items[n].Index < (int)(width_excess + 0.01f))
items[n].Width += 1.0f;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ComboBox
//-------------------------------------------------------------------------
// - BeginCombo()
// - EndCombo()
// - Combo()
//-------------------------------------------------------------------------
static float CalcMaxPopupHeightFromItemCount(int items_count)
{
ImGuiContext& g = *GImGui;
if (items_count <= 0)
return FLT_MAX;
return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
}
bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
{
// Always consume the SetNextWindowSizeConstraint() call in our early return paths
ImGuiContext& g = *GImGui;
bool has_window_size_constraint = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint) != 0;
g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float expected_w = CalcItemWidth();
const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : expected_w;
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
bool popup_open = IsPopupOpen(id);
const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
const float value_x2 = ImMax(frame_bb.Min.x, frame_bb.Max.x - arrow_size);
RenderNavHighlight(frame_bb, id);
if (!(flags & ImGuiComboFlags_NoPreview))
window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(value_x2, frame_bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Left);
if (!(flags & ImGuiComboFlags_NoArrowButton))
{
ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
ImU32 text_col = GetColorU32(ImGuiCol_Text);
window->DrawList->AddRectFilled(ImVec2(value_x2, frame_bb.Min.y), frame_bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right);
if (value_x2 + arrow_size - style.FramePadding.x <= frame_bb.Max.x)
RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f);
}
RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding);
if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
RenderTextClipped(frame_bb.Min + style.FramePadding, ImVec2(value_x2, frame_bb.Max.y), preview_value, NULL, NULL, ImVec2(0.0f,0.0f));
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if ((pressed || g.NavActivateId == id) && !popup_open)
{
if (window->DC.NavLayerCurrent == 0)
window->NavLastIds[0] = id;
OpenPopupEx(id);
popup_open = true;
}
if (!popup_open)
return false;
if (has_window_size_constraint)
{
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
}
else
{
if ((flags & ImGuiComboFlags_HeightMask_) == 0)
flags |= ImGuiComboFlags_HeightRegular;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
int popup_max_height_in_items = -1;
if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
}
char name[16];
ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
// Peak into expected window size so we can position it
if (ImGuiWindow* popup_window = FindWindowByName(name))
if (popup_window->WasActive)
{
ImVec2 size_expected = CalcWindowExpectedSize(popup_window);
if (flags & ImGuiComboFlags_PopupAlignLeft)
popup_window->AutoPosLastDirection = ImGuiDir_Left;
ImRect r_outer = GetWindowAllowedExtentRect(popup_window);
ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
SetNextWindowPos(pos);
}
// We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx()
ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove;
// Horizontally align ourselves with the framed text
PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(style.FramePadding.x, style.WindowPadding.y));
bool ret = Begin(name, NULL, window_flags);
PopStyleVar();
if (!ret)
{
EndPopup();
IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
return false;
}
return true;
}
void ImGui::EndCombo()
{
EndPopup();
}
// Getter for the old Combo() API: const char*[]
static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
{
const char* const* items = (const char* const*)data;
if (out_text)
*out_text = items[idx];
return true;
}
// Getter for the old Combo() API: "item1\0item2\0item3\0"
static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
{
// FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
const char* items_separated_by_zeros = (const char*)data;
int items_count = 0;
const char* p = items_separated_by_zeros;
while (*p)
{
if (idx == items_count)
break;
p += strlen(p) + 1;
items_count++;
}
if (!*p)
return false;
if (out_text)
*out_text = p;
return true;
}
// Old API, prefer using BeginCombo() nowadays if you can.
bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items)
{
ImGuiContext& g = *GImGui;
// Call the getter to obtain the preview string which is a parameter to BeginCombo()
const char* preview_value = NULL;
if (*current_item >= 0 && *current_item < items_count)
items_getter(data, *current_item, &preview_value);
// The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here.
if (popup_max_height_in_items != -1 && !(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint))
SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))
return false;
// Display items
// FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed)
bool value_changed = false;
for (int i = 0; i < items_count; i++)
{
PushID((void*)(intptr_t)i);
const bool item_selected = (i == *current_item);
const char* item_text;
if (!items_getter(data, i, &item_text))
item_text = "*Unknown item*";
if (Selectable(item_text, item_selected))
{
value_changed = true;
*current_item = i;
}
if (item_selected)
SetItemDefaultFocus();
PopID();
}
EndCombo();
return value_changed;
}
// Combo box helper allowing to pass an array of strings.
bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
{
const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
return value_changed;
}
// Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0"
bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
{
int items_count = 0;
const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
while (*p)
{
p += strlen(p) + 1;
items_count++;
}
bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Data Type and Data Formatting Helpers [Internal]
//-------------------------------------------------------------------------
// - PatchFormatStringFloatToInt()
// - DataTypeGetInfo()
// - DataTypeFormatString()
// - DataTypeApplyOp()
// - DataTypeApplyOpFromText()
// - DataTypeClamp()
// - GetMinimumStepAtDecimalPrecision
// - RoundScalarWithFormat<>()
//-------------------------------------------------------------------------
static const ImGuiDataTypeInfo GDataTypeInfo[] =
{
{ sizeof(char), "%d", "%d" }, // ImGuiDataType_S8
{ sizeof(unsigned char), "%u", "%u" },
{ sizeof(short), "%d", "%d" }, // ImGuiDataType_S16
{ sizeof(unsigned short), "%u", "%u" },
{ sizeof(int), "%d", "%d" }, // ImGuiDataType_S32
{ sizeof(unsigned int), "%u", "%u" },
#ifdef _MSC_VER
{ sizeof(ImS64), "%I64d","%I64d" }, // ImGuiDataType_S64
{ sizeof(ImU64), "%I64u","%I64u" },
#else
{ sizeof(ImS64), "%lld", "%lld" }, // ImGuiDataType_S64
{ sizeof(ImU64), "%llu", "%llu" },
#endif
{ sizeof(float), "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
{ sizeof(double), "%f", "%lf" }, // ImGuiDataType_Double
};
IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);
// FIXME-LEGACY: Prior to 1.61 our DragInt() function internally used floats and because of this the compile-time default value for format was "%.0f".
// Even though we changed the compile-time default, we expect users to have carried %f around, which would break the display of DragInt() calls.
// To honor backward compatibility we are rewriting the format string, unless IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled. What could possibly go wrong?!
static const char* PatchFormatStringFloatToInt(const char* fmt)
{
if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '0' && fmt[3] == 'f' && fmt[4] == 0) // Fast legacy path for "%.0f" which is expected to be the most common case.
return "%d";
const char* fmt_start = ImParseFormatFindStart(fmt); // Find % (if any, and ignore %%)
const char* fmt_end = ImParseFormatFindEnd(fmt_start); // Find end of format specifier, which itself is an exercise of confidence/recklessness (because snprintf is dependent on libc or user).
if (fmt_end > fmt_start && fmt_end[-1] == 'f')
{
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (fmt_start == fmt && fmt_end[0] == 0)
return "%d";
ImGuiContext& g = *GImGui;
ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%.*s%%d%s", (int)(fmt_start - fmt), fmt, fmt_end); // Honor leading and trailing decorations, but lose alignment/precision.
return g.TempBuffer;
#else
IM_ASSERT(0 && "DragInt(): Invalid format string!"); // Old versions used a default parameter of "%.0f", please replace with e.g. "%d"
#endif
}
return fmt;
}
const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type)
{
IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
return &GDataTypeInfo[data_type];
}
int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format)
{
// Signedness doesn't matter when pushing integer arguments
if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32)
return ImFormatString(buf, buf_size, format, *(const ImU32*)p_data);
if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
return ImFormatString(buf, buf_size, format, *(const ImU64*)p_data);
if (data_type == ImGuiDataType_Float)
return ImFormatString(buf, buf_size, format, *(const float*)p_data);
if (data_type == ImGuiDataType_Double)
return ImFormatString(buf, buf_size, format, *(const double*)p_data);
if (data_type == ImGuiDataType_S8)
return ImFormatString(buf, buf_size, format, *(const ImS8*)p_data);
if (data_type == ImGuiDataType_U8)
return ImFormatString(buf, buf_size, format, *(const ImU8*)p_data);
if (data_type == ImGuiDataType_S16)
return ImFormatString(buf, buf_size, format, *(const ImS16*)p_data);
if (data_type == ImGuiDataType_U16)
return ImFormatString(buf, buf_size, format, *(const ImU16*)p_data);
IM_ASSERT(0);
return 0;
}
void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2)
{
IM_ASSERT(op == '+' || op == '-');
switch (data_type)
{
case ImGuiDataType_S8:
if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
return;
case ImGuiDataType_U8:
if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
return;
case ImGuiDataType_S16:
if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
return;
case ImGuiDataType_U16:
if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
return;
case ImGuiDataType_S32:
if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
return;
case ImGuiDataType_U32:
if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
return;
case ImGuiDataType_S64:
if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
return;
case ImGuiDataType_U64:
if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
return;
case ImGuiDataType_Float:
if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; }
if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; }
return;
case ImGuiDataType_Double:
if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; }
if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; }
return;
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
}
// User can input math operators (e.g. +100) to edit a numerical values.
// NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess..
bool ImGui::DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* p_data, const char* format)
{
while (ImCharIsBlankA(*buf))
buf++;
// We don't support '-' op because it would conflict with inputing negative value.
// Instead you can use +-100 to subtract from an existing value
char op = buf[0];
if (op == '+' || op == '*' || op == '/')
{
buf++;
while (ImCharIsBlankA(*buf))
buf++;
}
else
{
op = 0;
}
if (!buf[0])
return false;
// Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all.
const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
ImGuiDataTypeTempStorage data_backup;
memcpy(&data_backup, p_data, type_info->Size);
if (format == NULL)
format = type_info->ScanFmt;
// FIXME-LEGACY: The aim is to remove those operators and write a proper expression evaluator at some point..
int arg1i = 0;
if (data_type == ImGuiDataType_S32)
{
int* v = (int*)p_data;
int arg0i = *v;
float arg1f = 0.0f;
if (op && sscanf(initial_value_buf, format, &arg0i) < 1)
return false;
// Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
if (op == '+') { if (sscanf(buf, "%d", &arg1i)) *v = (int)(arg0i + arg1i); } // Add (use "+-" to subtract)
else if (op == '*') { if (sscanf(buf, "%f", &arg1f)) *v = (int)(arg0i * arg1f); } // Multiply
else if (op == '/') { if (sscanf(buf, "%f", &arg1f) && arg1f != 0.0f) *v = (int)(arg0i / arg1f); } // Divide
else { if (sscanf(buf, format, &arg1i) == 1) *v = arg1i; } // Assign constant
}
else if (data_type == ImGuiDataType_Float)
{
// For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
format = "%f";
float* v = (float*)p_data;
float arg0f = *v, arg1f = 0.0f;
if (op && sscanf(initial_value_buf, format, &arg0f) < 1)
return false;
if (sscanf(buf, format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
}
else if (data_type == ImGuiDataType_Double)
{
format = "%lf"; // scanf differentiate float/double unlike printf which forces everything to double because of ellipsis
double* v = (double*)p_data;
double arg0f = *v, arg1f = 0.0;
if (op && sscanf(initial_value_buf, format, &arg0f) < 1)
return false;
if (sscanf(buf, format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
}
else if (data_type == ImGuiDataType_U32 || data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
{
// All other types assign constant
// We don't bother handling support for legacy operators since they are a little too crappy. Instead we will later implement a proper expression evaluator in the future.
sscanf(buf, format, p_data);
}
else
{
// Small types need a 32-bit buffer to receive the result from scanf()
int v32;
sscanf(buf, format, &v32);
if (data_type == ImGuiDataType_S8)
*(ImS8*)p_data = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX);
else if (data_type == ImGuiDataType_U8)
*(ImU8*)p_data = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX);
else if (data_type == ImGuiDataType_S16)
*(ImS16*)p_data = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX);
else if (data_type == ImGuiDataType_U16)
*(ImU16*)p_data = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX);
else
IM_ASSERT(0);
}
return memcmp(&data_backup, p_data, type_info->Size) != 0;
}
template<typename T>
static bool ClampBehaviorT(T* v, T v_min, T v_max)
{
if (*v < v_min) { *v = v_min; return true; }
if (*v > v_max) { *v = v_max; return true; }
return false;
}
bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max)
{
switch (data_type)
{
case ImGuiDataType_S8: return ClampBehaviorT<ImS8 >((ImS8* )p_data, *(const ImS8* )p_min, *(const ImS8* )p_max);
case ImGuiDataType_U8: return ClampBehaviorT<ImU8 >((ImU8* )p_data, *(const ImU8* )p_min, *(const ImU8* )p_max);
case ImGuiDataType_S16: return ClampBehaviorT<ImS16 >((ImS16* )p_data, *(const ImS16* )p_min, *(const ImS16* )p_max);
case ImGuiDataType_U16: return ClampBehaviorT<ImU16 >((ImU16* )p_data, *(const ImU16* )p_min, *(const ImU16* )p_max);
case ImGuiDataType_S32: return ClampBehaviorT<ImS32 >((ImS32* )p_data, *(const ImS32* )p_min, *(const ImS32* )p_max);
case ImGuiDataType_U32: return ClampBehaviorT<ImU32 >((ImU32* )p_data, *(const ImU32* )p_min, *(const ImU32* )p_max);
case ImGuiDataType_S64: return ClampBehaviorT<ImS64 >((ImS64* )p_data, *(const ImS64* )p_min, *(const ImS64* )p_max);
case ImGuiDataType_U64: return ClampBehaviorT<ImU64 >((ImU64* )p_data, *(const ImU64* )p_min, *(const ImU64* )p_max);
case ImGuiDataType_Float: return ClampBehaviorT<float >((float* )p_data, *(const float* )p_min, *(const float* )p_max);
case ImGuiDataType_Double: return ClampBehaviorT<double>((double*)p_data, *(const double*)p_min, *(const double*)p_max);
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
return false;
}
static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
{
static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
if (decimal_precision < 0)
return FLT_MIN;
return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision);
}
template<typename TYPE>
static const char* ImAtoi(const char* src, TYPE* output)
{
int negative = 0;
if (*src == '-') { negative = 1; src++; }
if (*src == '+') { src++; }
TYPE v = 0;
while (*src >= '0' && *src <= '9')
v = (v * 10) + (*src++ - '0');
*output = negative ? -v : v;
return src;
}
template<typename TYPE, typename SIGNEDTYPE>
TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v)
{
const char* fmt_start = ImParseFormatFindStart(format);
if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string
return v;
char v_str[64];
ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v);
const char* p = v_str;
while (*p == ' ')
p++;
if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)
v = (TYPE)ImAtof(p);
else
ImAtoi(p, (SIGNEDTYPE*)&v);
return v;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
//-------------------------------------------------------------------------
// - DragBehaviorT<>() [Internal]
// - DragBehavior() [Internal]
// - DragScalar()
// - DragScalarN()
// - DragFloat()
// - DragFloat2()
// - DragFloat3()
// - DragFloat4()
// - DragFloatRange2()
// - DragInt()
// - DragInt2()
// - DragInt3()
// - DragInt4()
// - DragIntRange2()
//-------------------------------------------------------------------------
// This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)
template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
const bool is_clamped = (v_min < v_max);
const bool is_power = (power != 1.0f && is_decimal && is_clamped && (v_max - v_min < FLT_MAX));
const bool is_locked = (v_min > v_max);
if (is_locked)
return false;
// Default tweak speed
if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX))
v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio);
// Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings
float adjust_delta = 0.0f;
if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f*1.0f)
{
adjust_delta = g.IO.MouseDelta[axis];
if (g.IO.KeyAlt)
adjust_delta *= 1.0f / 100.0f;
if (g.IO.KeyShift)
adjust_delta *= 10.0f;
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0;
adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f / 10.0f, 10.0f)[axis];
v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
}
adjust_delta *= v_speed;
// For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter.
if (axis == ImGuiAxis_Y)
adjust_delta = -adjust_delta;
// Clear current value on activation
// Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300.
bool is_just_activated = g.ActiveIdIsJustActivated;
bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f));
bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0));
if (is_just_activated || is_already_past_limits_and_pushing_outward || is_drag_direction_change_with_power)
{
g.DragCurrentAccum = 0.0f;
g.DragCurrentAccumDirty = false;
}
else if (adjust_delta != 0.0f)
{
g.DragCurrentAccum += adjust_delta;
g.DragCurrentAccumDirty = true;
}
if (!g.DragCurrentAccumDirty)
return false;
TYPE v_cur = *v;
FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f;
if (is_power)
{
// Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range
FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power);
FLOATTYPE v_new_norm_curved = v_old_norm_curved + (g.DragCurrentAccum / (v_max - v_min));
v_cur = v_min + (SIGNEDTYPE)ImPow(ImSaturate((float)v_new_norm_curved), power) * (v_max - v_min);
v_old_ref_for_accum_remainder = v_old_norm_curved;
}
else
{
v_cur += (SIGNEDTYPE)g.DragCurrentAccum;
}
// Round to user desired precision based on format string
v_cur = RoundScalarWithFormatT<TYPE, SIGNEDTYPE>(format, data_type, v_cur);
// Preserve remainder after rounding has been applied. This also allow slow tweaking of values.
g.DragCurrentAccumDirty = false;
if (is_power)
{
FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power);
g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder);
}
else
{
g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v);
}
// Lose zero sign for float/double
if (v_cur == (TYPE)-0)
v_cur = (TYPE)0;
// Clamp values (+ handle overflow/wrap-around for integer types)
if (*v != v_cur && is_clamped)
{
if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_decimal))
v_cur = v_min;
if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_decimal))
v_cur = v_max;
}
// Apply result
if (*v == v_cur)
return false;
*v = v_cur;
return true;
}
bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, float power, ImGuiDragFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
{
if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
ClearActiveID();
else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
ClearActiveID();
}
if (g.ActiveId != id)
return false;
switch (data_type)
{
case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT<ImS32, ImS32, float>(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; }
case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT<ImU32, ImS32, float>(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; }
case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT<ImS32, ImS32, float>(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; }
case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT<ImU32, ImS32, float>(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; }
case ImGuiDataType_S32: return DragBehaviorT<ImS32, ImS32, float >(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, power, flags);
case ImGuiDataType_U32: return DragBehaviorT<ImU32, ImS32, float >(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, power, flags);
case ImGuiDataType_S64: return DragBehaviorT<ImS64, ImS64, double>(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, power, flags);
case ImGuiDataType_U64: return DragBehaviorT<ImU64, ImS64, double>(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, power, flags);
case ImGuiDataType_Float: return DragBehaviorT<float, float, float >(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, power, flags);
case ImGuiDataType_Double: return DragBehaviorT<double,double,double>(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, power, flags);
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
return false;
}
// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional.
// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (power != 1.0f)
IM_ASSERT(p_min != NULL && p_max != NULL); // When using a power curve the drag needs to have known bounds
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
// Default format string when passing NULL
if (format == NULL)
format = DataTypeGetInfo(data_type)->PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.)
format = PatchFormatStringFloatToInt(format);
// Tabbing or CTRL-clicking on Drag turns it into an input box
const bool hovered = ItemHoverable(frame_bb, id);
bool temp_input_is_active = TempInputIsActive(id);
bool temp_input_start = false;
if (!temp_input_is_active)
{
const bool focus_requested = FocusableItemRegister(window, id);
const bool clicked = (hovered && g.IO.MouseClicked[0]);
const bool double_clicked = (hovered && g.IO.MouseDoubleClicked[0]);
if (focus_requested || clicked || double_clicked || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
if (focus_requested || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavInputId == id)
{
temp_input_start = true;
FocusableItemUnregister(window);
}
}
}
// Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that..
if (temp_input_is_active || temp_input_start)
return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max);
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
// Drag behavior
const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, power, ImGuiDragFlags_None);
if (value_changed)
MarkItemEdited(id);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return value_changed;
}
bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components, CalcItemWidth());
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
if (i > 0)
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, power);
PopID();
PopItemWidth();
p_data = (void*)((char*)p_data + type_size);
}
PopID();
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
EndGroup();
return value_changed;
}
bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power)
{
return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power);
}
bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2, CalcItemWidth());
bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, format_max ? format_max : format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
// NB: v_speed is float to allow adjusting the drag speed with more precision
bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format)
{
return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format)
{
return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format);
}
bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2, CalcItemWidth());
bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, format_max ? format_max : format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
//-------------------------------------------------------------------------
// - SliderBehaviorT<>() [Internal]
// - SliderBehavior() [Internal]
// - SliderScalar()
// - SliderScalarN()
// - SliderFloat()
// - SliderFloat2()
// - SliderFloat3()
// - SliderFloat4()
// - SliderAngle()
// - SliderInt()
// - SliderInt2()
// - SliderInt3()
// - SliderInt4()
// - VSliderScalar()
// - VSliderFloat()
// - VSliderInt()
//-------------------------------------------------------------------------
template<typename TYPE, typename FLOATTYPE>
float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos)
{
if (v_min == v_max)
return 0.0f;
const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double);
const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
if (is_power)
{
if (v_clamped < 0.0f)
{
const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min));
return (1.0f - ImPow(f, 1.0f/power)) * linear_zero_pos;
}
else
{
const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min)));
return linear_zero_pos + ImPow(f, 1.0f/power) * (1.0f - linear_zero_pos);
}
}
// Linear slider
return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min));
}
// FIXME: Move some of the code into SliderBehavior(). Current responsibility is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc.
template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
const bool is_power = (power != 1.0f) && is_decimal;
const float grab_padding = 2.0f;
const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f;
float grab_sz = style.GrabMinSize;
SIGNEDTYPE v_range = (v_min < v_max ? v_max - v_min : v_min - v_max);
if (!is_decimal && v_range >= 0) // v_range < 0 may happen on integer overflows
grab_sz = ImMax((float)(slider_sz / (v_range + 1)), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit
grab_sz = ImMin(grab_sz, slider_sz);
const float slider_usable_sz = slider_sz - grab_sz;
const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f;
const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f;
// For power curve sliders that cross over sign boundary we want the curve to be symmetric around 0.0f
float linear_zero_pos; // 0.0->1.0f
if (is_power && v_min * v_max < 0.0f)
{
// Different sign
const FLOATTYPE linear_dist_min_to_0 = ImPow(v_min >= 0 ? (FLOATTYPE)v_min : -(FLOATTYPE)v_min, (FLOATTYPE)1.0f / power);
const FLOATTYPE linear_dist_max_to_0 = ImPow(v_max >= 0 ? (FLOATTYPE)v_max : -(FLOATTYPE)v_max, (FLOATTYPE)1.0f / power);
linear_zero_pos = (float)(linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0));
}
else
{
// Same sign
linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
}
// Process interacting with the slider
bool value_changed = false;
if (g.ActiveId == id)
{
bool set_new_value = false;
float clicked_t = 0.0f;
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (!g.IO.MouseDown[0])
{
ClearActiveID();
}
else
{
const float mouse_abs_pos = g.IO.MousePos[axis];
clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
if (axis == ImGuiAxis_Y)
clicked_t = 1.0f - clicked_t;
set_new_value = true;
}
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f);
float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y;
if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
{
ClearActiveID();
}
else if (delta != 0.0f)
{
clicked_t = SliderCalcRatioFromValueT<TYPE,FLOATTYPE>(data_type, *v, v_min, v_max, power, linear_zero_pos);
const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0;
if ((decimal_precision > 0) || is_power)
{
delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds
if (IsNavInputDown(ImGuiNavInput_TweakSlow))
delta /= 10.0f;
}
else
{
if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow))
delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps
else
delta /= 100.0f;
}
if (IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= 10.0f;
set_new_value = true;
if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits
set_new_value = false;
else
clicked_t = ImSaturate(clicked_t + delta);
}
}
if (set_new_value)
{
TYPE v_new;
if (is_power)
{
// Account for power curve scale on both sides of the zero
if (clicked_t < linear_zero_pos)
{
// Negative: rescale to the negative range before powering
float a = 1.0f - (clicked_t / linear_zero_pos);
a = ImPow(a, power);
v_new = ImLerp(ImMin(v_max, (TYPE)0), v_min, a);
}
else
{
// Positive: rescale to the positive range before powering
float a;
if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f)
a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos);
else
a = clicked_t;
a = ImPow(a, power);
v_new = ImLerp(ImMax(v_min, (TYPE)0), v_max, a);
}
}
else
{
// Linear slider
if (is_decimal)
{
v_new = ImLerp(v_min, v_max, clicked_t);
}
else
{
// For integer values we want the clicking position to match the grab box so we round above
// This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property..
FLOATTYPE v_new_off_f = (v_max - v_min) * clicked_t;
TYPE v_new_off_floor = (TYPE)(v_new_off_f);
TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5);
if (v_new_off_floor < v_new_off_round)
v_new = v_min + v_new_off_round;
else
v_new = v_min + v_new_off_floor;
}
}
// Round to user desired precision based on format string
v_new = RoundScalarWithFormatT<TYPE,SIGNEDTYPE>(format, data_type, v_new);
// Apply result
if (*v != v_new)
{
*v = v_new;
value_changed = true;
}
}
}
if (slider_sz < 1.0f)
{
*out_grab_bb = ImRect(bb.Min, bb.Min);
}
else
{
// Output grab position so it can be displayed by the caller
float grab_t = SliderCalcRatioFromValueT<TYPE, FLOATTYPE>(data_type, *v, v_min, v_max, power, linear_zero_pos);
if (axis == ImGuiAxis_Y)
grab_t = 1.0f - grab_t;
const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
if (axis == ImGuiAxis_X)
*out_grab_bb = ImRect(grab_pos - grab_sz * 0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz * 0.5f, bb.Max.y - grab_padding);
else
*out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz * 0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz * 0.5f);
}
return value_changed;
}
// For 32-bit and larger types, slider bounds are limited to half the natural type range.
// So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok.
// It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders.
bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb)
{
switch (data_type)
{
case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT<ImS32, ImS32, float>(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; }
case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = SliderBehaviorT<ImU32, ImS32, float>(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min, *(const ImU8*)p_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)p_v = (ImU8)v32; return r; }
case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT<ImS32, ImS32, float>(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; }
case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT<ImU32, ImS32, float>(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; }
case ImGuiDataType_S32:
IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN/2 && *(const ImS32*)p_max <= IM_S32_MAX/2);
return SliderBehaviorT<ImS32, ImS32, float >(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, power, flags, out_grab_bb);
case ImGuiDataType_U32:
IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX/2);
return SliderBehaviorT<ImU32, ImS32, float >(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, power, flags, out_grab_bb);
case ImGuiDataType_S64:
IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN/2 && *(const ImS64*)p_max <= IM_S64_MAX/2);
return SliderBehaviorT<ImS64, ImS64, double>(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, power, flags, out_grab_bb);
case ImGuiDataType_U64:
IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX/2);
return SliderBehaviorT<ImU64, ImS64, double>(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, power, flags, out_grab_bb);
case ImGuiDataType_Float:
IM_ASSERT(*(const float*)p_min >= -FLT_MAX/2.0f && *(const float*)p_max <= FLT_MAX/2.0f);
return SliderBehaviorT<float, float, float >(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, power, flags, out_grab_bb);
case ImGuiDataType_Double:
IM_ASSERT(*(const double*)p_min >= -DBL_MAX/2.0f && *(const double*)p_max <= DBL_MAX/2.0f);
return SliderBehaviorT<double,double,double>(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, power, flags, out_grab_bb);
case ImGuiDataType_COUNT: break;
}
IM_ASSERT(0);
return false;
}
// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required.
// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
// Default format string when passing NULL
if (format == NULL)
format = DataTypeGetInfo(data_type)->PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.)
format = PatchFormatStringFloatToInt(format);
// Tabbing or CTRL-clicking on Slider turns it into an input box
const bool hovered = ItemHoverable(frame_bb, id);
bool temp_input_is_active = TempInputIsActive(id);
bool temp_input_start = false;
if (!temp_input_is_active)
{
const bool focus_requested = FocusableItemRegister(window, id);
const bool clicked = (hovered && g.IO.MouseClicked[0]);
if (focus_requested || clicked || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
if (focus_requested || (clicked && g.IO.KeyCtrl) || g.NavInputId == id)
{
temp_input_start = true;
FocusableItemUnregister(window);
}
}
}
// Our current specs do NOT clamp when using CTRL+Click manual input, but we should eventually add a flag for that..
if (temp_input_is_active || temp_input_start)
return TempInputScalar(frame_bb, id, label, data_type, p_data, format);// , p_min, p_max);
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
// Slider behavior
ImRect grab_bb;
const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, ImGuiSliderFlags_None, &grab_bb);
if (value_changed)
MarkItemEdited(id);
// Render grab
if (grab_bb.Max.x > grab_bb.Min.x)
window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return value_changed;
}
// Add multiple sliders on 1 line for compact edition of multiple components
bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components, CalcItemWidth());
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
if (i > 0)
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power);
PopID();
PopItemWidth();
v = (void*)((char*)v + type_size);
}
PopID();
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0, g.Style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
EndGroup();
return value_changed;
}
bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power)
{
return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power);
}
bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power)
{
return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power);
}
bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format)
{
if (format == NULL)
format = "%.0f deg";
float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f);
*v_rad = v_deg * (2*IM_PI) / 360.0f;
return value_changed;
}
bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format)
{
return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format);
}
bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format);
}
bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format);
}
bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format)
{
return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format);
}
bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(frame_bb, id))
return false;
// Default format string when passing NULL
if (format == NULL)
format = DataTypeGetInfo(data_type)->PrintFmt;
else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) // (FIXME-LEGACY: Patch old "%.0f" format string to use "%d", read function more details.)
format = PatchFormatStringFloatToInt(format);
const bool hovered = ItemHoverable(frame_bb, id);
if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
}
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
// Slider behavior
ImRect grab_bb;
const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, power, ImGuiSliderFlags_Vertical, &grab_bb);
if (value_changed)
MarkItemEdited(id);
// Render grab
if (grab_bb.Max.y > grab_bb.Min.y)
window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
// For the vertical slider we allow centered text to overlap the frame padding
char value_buf[64];
const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
return value_changed;
}
bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power)
{
return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power);
}
bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format)
{
return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
//-------------------------------------------------------------------------
// - ImParseFormatFindStart() [Internal]
// - ImParseFormatFindEnd() [Internal]
// - ImParseFormatTrimDecorations() [Internal]
// - ImParseFormatPrecision() [Internal]
// - TempInputTextScalar() [Internal]
// - InputScalar()
// - InputScalarN()
// - InputFloat()
// - InputFloat2()
// - InputFloat3()
// - InputFloat4()
// - InputInt()
// - InputInt2()
// - InputInt3()
// - InputInt4()
// - InputDouble()
//-------------------------------------------------------------------------
// We don't use strchr() because our strings are usually very short and often start with '%'
const char* ImParseFormatFindStart(const char* fmt)
{
while (char c = fmt[0])
{
if (c == '%' && fmt[1] != '%')
return fmt;
else if (c == '%')
fmt++;
fmt++;
}
return fmt;
}
const char* ImParseFormatFindEnd(const char* fmt)
{
// Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format.
if (fmt[0] != '%')
return fmt;
const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A'));
const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a'));
for (char c; (c = *fmt) != 0; fmt++)
{
if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0)
return fmt + 1;
if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0)
return fmt + 1;
}
return fmt;
}
// Extract the format out of a format string with leading or trailing decorations
// fmt = "blah blah" -> return fmt
// fmt = "%.3f" -> return fmt
// fmt = "hello %.3f" -> return fmt + 6
// fmt = "%.3f hello" -> return buf written with "%.3f"
const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size)
{
const char* fmt_start = ImParseFormatFindStart(fmt);
if (fmt_start[0] != '%')
return fmt;
const char* fmt_end = ImParseFormatFindEnd(fmt_start);
if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data.
return fmt_start;
ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size));
return buf;
}
// Parse display precision back from the display format string
// FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed.
int ImParseFormatPrecision(const char* fmt, int default_precision)
{
fmt = ImParseFormatFindStart(fmt);
if (fmt[0] != '%')
return default_precision;
fmt++;
while (*fmt >= '0' && *fmt <= '9')
fmt++;
int precision = INT_MAX;
if (*fmt == '.')
{
fmt = ImAtoi<int>(fmt + 1, &precision);
if (precision < 0 || precision > 99)
precision = default_precision;
}
if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
precision = -1;
if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX)
precision = -1;
return (precision == INT_MAX) ? default_precision : precision;
}
// Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets)
// FIXME: Facilitate using this in variety of other situations.
bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags)
{
// On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id.
// We clear ActiveID on the first frame to allow the InputText() taking it back.
ImGuiContext& g = *GImGui;
const bool init = (g.TempInputId != id);
if (init)
ClearActiveID();
g.CurrentWindow->DC.CursorPos = bb.Min;
bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags);
if (init)
{
// First frame we started displaying the InputText widget, we expect it to take the active id.
IM_ASSERT(g.ActiveId == id);
g.TempInputId = g.ActiveId;
}
return value_changed;
}
// Note that Drag/Slider functions are currently NOT forwarding the min/max values clamping values!
// This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility.
// However this may not be ideal for all uses, as some user code may break on out of bound values.
// In the future we should add flags to Slider/Drag to specify how to enforce min/max values with CTRL+Click.
// See GitHub issues #1829 and #3209
// In the meanwhile, you can easily "wrap" those functions to enforce clamping, using wrapper functions, e.g.
// bool SliderFloatClamp(const char* label, float* v, float v_min, float v_max)
// {
// float v_backup = *v;
// if (!SliderFloat(label, v, v_min, v_max))
// return false;
// *v = ImClamp(*v, v_min, v_max);
// return v_backup != *v;
// }
bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max)
{
ImGuiContext& g = *GImGui;
char fmt_buf[32];
char data_buf[32];
format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf));
DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format);
ImStrTrimBlanks(data_buf);
ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited;
flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal);
bool value_changed = false;
if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags))
{
// Backup old value
size_t data_type_size = DataTypeGetInfo(data_type)->Size;
ImGuiDataTypeTempStorage data_backup;
memcpy(&data_backup, p_data, data_type_size);
// Apply new value (or operations) then clamp
DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, p_data, NULL);
if (p_clamp_min && p_clamp_max)
DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max);
// Only mark as edited if new value is different
value_changed = memcmp(&data_backup, p_data, data_type_size) != 0;
if (value_changed)
MarkItemEdited(id);
}
return value_changed;
}
// Note: p_data, p_step, p_step_fast are _pointers_ to a memory address holding the data. For an Input widget, p_step and p_step_fast are optional.
// Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
if (format == NULL)
format = DataTypeGetInfo(data_type)->PrintFmt;
char buf[64];
DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format);
bool value_changed = false;
if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0)
flags |= ImGuiInputTextFlags_CharsDecimal;
flags |= ImGuiInputTextFlags_AutoSelectAll;
flags |= ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string.
if (p_step != NULL)
{
const float button_size = GetFrameHeight();
BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive()
PushID(label);
SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2));
if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view
value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, p_data, format);
// Step buttons
const ImVec2 backup_frame_padding = style.FramePadding;
style.FramePadding.x = style.FramePadding.y;
ImGuiButtonFlags button_flags = ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups;
if (flags & ImGuiInputTextFlags_ReadOnly)
button_flags |= ImGuiButtonFlags_Disabled;
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("-", ImVec2(button_size, button_size), button_flags))
{
DataTypeApplyOp(data_type, '-', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
value_changed = true;
}
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("+", ImVec2(button_size, button_size), button_flags))
{
DataTypeApplyOp(data_type, '+', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
value_changed = true;
}
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0, style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
style.FramePadding = backup_frame_padding;
PopID();
EndGroup();
}
else
{
if (InputText(label, buf, IM_ARRAYSIZE(buf), flags))
value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, p_data, format);
}
if (value_changed)
MarkItemEdited(window->DC.LastItemId);
return value_changed;
}
bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components, CalcItemWidth());
size_t type_size = GDataTypeInfo[data_type].Size;
for (int i = 0; i < components; i++)
{
PushID(i);
if (i > 0)
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= InputScalar("", data_type, p_data, p_step, p_step_fast, format, flags);
PopID();
PopItemWidth();
p_data = (void*)((char*)p_data + type_size);
}
PopID();
const char* label_end = FindRenderedTextEnd(label);
if (label != label_end)
{
SameLine(0.0f, g.Style.ItemInnerSpacing.x);
TextEx(label, label_end);
}
EndGroup();
return value_changed;
}
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags)
{
flags |= ImGuiInputTextFlags_CharsScientific;
return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), format, flags);
}
bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
}
bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
}
bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
}
// Prefer using "const char* format" directly, which is more flexible and consistent with other API.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputFloat(label, v, step, step_fast, format, flags);
}
bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
}
bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
}
bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags)
{
char format[16] = "%f";
if (decimal_precision >= 0)
ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision);
return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags)
{
// Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), format, flags);
}
bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags);
}
bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags);
}
bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags)
{
return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags);
}
bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags)
{
flags |= ImGuiInputTextFlags_CharsScientific;
return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), format, flags);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint
//-------------------------------------------------------------------------
// - InputText()
// - InputTextWithHint()
// - InputTextMultiline()
// - InputTextEx() [Internal]
//-------------------------------------------------------------------------
bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
}
bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
}
bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
}
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
{
int line_count = 0;
const char* s = text_begin;
while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
if (c == '\n')
line_count++;
s--;
if (s[0] != '\n' && s[0] != '\r')
line_count++;
*out_text_end = s;
return line_count;
}
static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
{
ImGuiContext& g = *GImGui;
ImFont* font = g.Font;
const float line_height = g.FontSize;
const float scale = line_height / font->FontSize;
ImVec2 text_size = ImVec2(0,0);
float line_width = 0.0f;
const ImWchar* s = text_begin;
while (s < text_end)
{
unsigned int c = (unsigned int)(*s++);
if (c == '\n')
{
text_size.x = ImMax(text_size.x, line_width);
text_size.y += line_height;
line_width = 0.0f;
if (stop_on_new_line)
break;
continue;
}
if (c == '\r')
continue;
const float char_width = font->GetCharAdvance((ImWchar)c) * scale;
line_width += char_width;
}
if (text_size.x < line_width)
text_size.x = line_width;
if (out_offset)
*out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
text_size.y += line_height;
if (remaining)
*remaining = s;
return text_size;
}
// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
namespace ImStb
{
static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->TextW[idx]; }
static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *GImGui; return g.Font->GetCharAdvance(c) * (g.FontSize / g.Font->FontSize); }
static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x200000 ? 0 : key; }
static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
{
const ImWchar* text = obj->TextW.Data;
const ImWchar* text_remaining = NULL;
const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
r->x0 = 0.0f;
r->x1 = size.x;
r->baseline_y_delta = size.y;
r->ymin = 0.0f;
r->ymax = size.y;
r->num_chars = (int)(text_remaining - (text + line_start_idx));
}
static bool is_separator(unsigned int c) { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; }
static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->TextW[idx-1] ) && !is_separator( obj->TextW[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
#ifdef __APPLE__ // FIXME: Move setting to IO structure
static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->TextW[idx-1] ) && is_separator( obj->TextW[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
#else
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
#endif
#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
{
ImWchar* dst = obj->TextW.Data + pos;
// We maintain our buffer length in both UTF-8 and wchar formats
obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
obj->CurLenW -= n;
// Offset remaining text (FIXME-OPT: Use memmove)
const ImWchar* src = obj->TextW.Data + pos + n;
while (ImWchar c = *src++)
*dst++ = c;
*dst = '\0';
}
static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
{
const bool is_resizable = (obj->UserFlags & ImGuiInputTextFlags_CallbackResize) != 0;
const int text_len = obj->CurLenW;
IM_ASSERT(pos <= text_len);
const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
if (!is_resizable && (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufCapacityA))
return false;
// Grow internal buffer if needed
if (new_text_len + text_len + 1 > obj->TextW.Size)
{
if (!is_resizable)
return false;
IM_ASSERT(text_len < obj->TextW.Size);
obj->TextW.resize(text_len + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1);
}
ImWchar* text = obj->TextW.Data;
if (pos != text_len)
memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
obj->CurLenW += new_text_len;
obj->CurLenA += new_text_len_utf8;
obj->TextW[obj->CurLenW] = '\0';
return true;
}
// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)
#define STB_TEXTEDIT_K_LEFT 0x200000 // keyboard input to move cursor left
#define STB_TEXTEDIT_K_RIGHT 0x200001 // keyboard input to move cursor right
#define STB_TEXTEDIT_K_UP 0x200002 // keyboard input to move cursor up
#define STB_TEXTEDIT_K_DOWN 0x200003 // keyboard input to move cursor down
#define STB_TEXTEDIT_K_LINESTART 0x200004 // keyboard input to move cursor to start of line
#define STB_TEXTEDIT_K_LINEEND 0x200005 // keyboard input to move cursor to end of line
#define STB_TEXTEDIT_K_TEXTSTART 0x200006 // keyboard input to move cursor to start of text
#define STB_TEXTEDIT_K_TEXTEND 0x200007 // keyboard input to move cursor to end of text
#define STB_TEXTEDIT_K_DELETE 0x200008 // keyboard input to delete selection or character under cursor
#define STB_TEXTEDIT_K_BACKSPACE 0x200009 // keyboard input to delete selection or character left of cursor
#define STB_TEXTEDIT_K_UNDO 0x20000A // keyboard input to perform undo
#define STB_TEXTEDIT_K_REDO 0x20000B // keyboard input to perform redo
#define STB_TEXTEDIT_K_WORDLEFT 0x20000C // keyboard input to move cursor left one word
#define STB_TEXTEDIT_K_WORDRIGHT 0x20000D // keyboard input to move cursor right one word
#define STB_TEXTEDIT_K_SHIFT 0x400000
#define STB_TEXTEDIT_IMPLEMENTATION
#include "imstb_textedit.h"
// stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling
// the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?)
static void stb_textedit_replace(STB_TEXTEDIT_STRING* str, STB_TexteditState* state, const STB_TEXTEDIT_CHARTYPE* text, int text_len)
{
stb_text_makeundo_replace(str, state, 0, str->CurLenW, text_len);
ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->CurLenW);
if (text_len <= 0)
return;
if (ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len))
{
state->cursor = text_len;
state->has_preferred_x = 0;
return;
}
IM_ASSERT(0); // Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace()
}
} // namespace ImStb
void ImGuiInputTextState::OnKeyPressed(int key)
{
stb_textedit_key(this, &Stb, key);
CursorFollow = true;
CursorAnimReset();
}
ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
{
memset(this, 0, sizeof(*this));
}
// Public API to manipulate UTF-8 text
// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
// FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)
{
IM_ASSERT(pos + bytes_count <= BufTextLen);
char* dst = Buf + pos;
const char* src = Buf + pos + bytes_count;
while (char c = *src++)
*dst++ = c;
*dst = '\0';
if (CursorPos + bytes_count >= pos)
CursorPos -= bytes_count;
else if (CursorPos >= pos)
CursorPos = pos;
SelectionStart = SelectionEnd = CursorPos;
BufDirty = true;
BufTextLen -= bytes_count;
}
void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
{
const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;
const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
if (new_text_len + BufTextLen >= BufSize)
{
if (!is_resizable)
return;
// Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the mildly similar code (until we remove the U16 buffer altogether!)
ImGuiContext& g = *GImGui;
ImGuiInputTextState* edit_state = &g.InputTextState;
IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID);
IM_ASSERT(Buf == edit_state->TextA.Data);
int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
edit_state->TextA.reserve(new_buf_size + 1);
Buf = edit_state->TextA.Data;
BufSize = edit_state->BufCapacityA = new_buf_size;
}
if (BufTextLen != pos)
memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
Buf[BufTextLen + new_text_len] = '\0';
if (CursorPos >= pos)
CursorPos += new_text_len;
SelectionStart = SelectionEnd = CursorPos;
BufDirty = true;
BufTextLen += new_text_len;
}
// Return false to discard a character.
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
{
unsigned int c = *p_char;
// Filter non-printable (NB: isprint is unreliable! see #2467)
if (c < 0x20)
{
bool pass = false;
pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
if (!pass)
return false;
}
// We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817)
if (c == 127)
return false;
// Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME)
if (c >= 0xE000 && c <= 0xF8FF)
return false;
// Filter Unicode ranges we are not handling in this build.
if (c > IM_UNICODE_CODEPOINT_MAX)
return false;
// Generic named filters
if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific))
{
if (flags & ImGuiInputTextFlags_CharsDecimal)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
return false;
if (flags & ImGuiInputTextFlags_CharsScientific)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))
return false;
if (flags & ImGuiInputTextFlags_CharsHexadecimal)
if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
return false;
if (flags & ImGuiInputTextFlags_CharsUppercase)
if (c >= 'a' && c <= 'z')
*p_char = (c += (unsigned int)('A'-'a'));
if (flags & ImGuiInputTextFlags_CharsNoBlank)
if (ImCharIsBlankW(c))
return false;
}
// Custom callback filter
if (flags & ImGuiInputTextFlags_CallbackCharFilter)
{
ImGuiInputTextCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData));
callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
callback_data.EventChar = (ImWchar)c;
callback_data.Flags = flags;
callback_data.UserData = user_data;
if (callback(&callback_data) != 0)
return false;
*p_char = callback_data.EventChar;
if (!callback_data.EventChar)
return false;
}
return true;
}
// Edit a string of text
// - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!".
// This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match
// Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator.
// - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect.
// - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h
// (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are
// doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188)
bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
IM_ASSERT(buf != NULL && buf_size >= 0);
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
const ImGuiStyle& style = g.Style;
const bool RENDER_SELECTION_WHEN_INACTIVE = false;
const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0;
const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0;
if (is_resizable)
IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!
if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope,
BeginGroup();
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line
const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
const ImRect total_bb(frame_bb.Min, frame_bb.Min + total_size);
ImGuiWindow* draw_window = window;
ImVec2 inner_size = frame_size;
if (is_multiline)
{
if (!ItemAdd(total_bb, id, &frame_bb))
{
ItemSize(total_bb, style.FramePadding.y);
EndGroup();
return false;
}
// We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug.
PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding);
PopStyleVar(3);
PopStyleColor();
if (!child_visible)
{
EndChild();
EndGroup();
return false;
}
draw_window = g.CurrentWindow; // Child window
draw_window->DC.NavLayerActiveMaskNext |= draw_window->DC.NavLayerCurrentMask; // This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it.
inner_size.x -= draw_window->ScrollbarSizes.x;
}
else
{
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
}
const bool hovered = ItemHoverable(frame_bb, id);
if (hovered)
g.MouseCursor = ImGuiMouseCursor_TextInput;
// We are only allowed to access the state if we are already the active widget.
ImGuiInputTextState* state = GetInputTextState(id);
const bool focus_requested = FocusableItemRegister(window, id);
const bool focus_requested_by_code = focus_requested && (g.FocusRequestCurrWindow == window && g.FocusRequestCurrCounterRegular == window->DC.FocusCounterRegular);
const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
const bool user_clicked = hovered && io.MouseClicked[0];
const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard));
const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);
const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);
bool clear_active_id = false;
bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline);
const bool init_make_active = (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start);
const bool init_state = (init_make_active || user_scroll_active);
if (init_state && g.ActiveId != id)
{
// Access state even if we don't own it yet.
state = &g.InputTextState;
state->CursorAnimReset();
// Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
// From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
const int buf_len = (int)strlen(buf);
state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
memcpy(state->InitialTextA.Data, buf, buf_len + 1);
// Start edition
const char* buf_end = NULL;
state->TextW.resize(buf_size + 1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string.
state->TextA.resize(0);
state->TextAIsValid = false; // TextA is not valid yet (we will display buf until then)
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end);
state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
// Preserve cursor position and undo/redo stack if we come back to same widget
// FIXME: For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed.
const bool recycle_state = (state->ID == id);
if (recycle_state)
{
// Recycle existing cursor/selection/undo stack but clamp position
// Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
state->CursorClamp();
}
else
{
state->ID = id;
state->ScrollX = 0.0f;
stb_textedit_initialize_state(&state->Stb, !is_multiline);
if (!is_multiline && focus_requested_by_code)
select_all = true;
}
if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
state->Stb.insert_mode = 1;
if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
select_all = true;
}
if (g.ActiveId != id && init_make_active)
{
IM_ASSERT(state && state->ID == id);
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
// Declare our inputs
IM_ASSERT(ImGuiNavInput_COUNT < 32);
g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory))
g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel);
g.ActiveIdUsingKeyInputMask |= ((ImU64)1 << ImGuiKey_Home) | ((ImU64)1 << ImGuiKey_End);
if (is_multiline)
g.ActiveIdUsingKeyInputMask |= ((ImU64)1 << ImGuiKey_PageUp) | ((ImU64)1 << ImGuiKey_PageDown); // FIXME-NAV: Page up/down actually not supported yet by widget, but claim them ahead.
if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out as we will use the \t character.
g.ActiveIdUsingKeyInputMask |= ((ImU64)1 << ImGuiKey_Tab);
}
// We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
if (g.ActiveId == id && state == NULL)
ClearActiveID();
// Release focus when we click outside
if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560
clear_active_id = true;
// Lock the decision of whether we are going to take the path displaying the cursor or selection
const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active);
bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
bool value_changed = false;
bool enter_pressed = false;
// When read-only we always use the live data passed to the function
// FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :(
if (is_readonly && state != NULL && (render_cursor || render_selection))
{
const char* buf_end = NULL;
state->TextW.resize(buf_size + 1);
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end);
state->CurLenA = (int)(buf_end - buf);
state->CursorClamp();
render_selection &= state->HasSelection();
}
// Select the buffer to render.
const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid;
const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
// Password pushes a temporary font with only a fallback glyph
if (is_password && !is_displaying_hint)
{
const ImFontGlyph* glyph = g.Font->FindGlyph('*');
ImFont* password_font = &g.InputTextPasswordFont;
password_font->FontSize = g.Font->FontSize;
password_font->Scale = g.Font->Scale;
password_font->DisplayOffset = g.Font->DisplayOffset;
password_font->Ascent = g.Font->Ascent;
password_font->Descent = g.Font->Descent;
password_font->ContainerAtlas = g.Font->ContainerAtlas;
password_font->FallbackGlyph = glyph;
password_font->FallbackAdvanceX = glyph->AdvanceX;
IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
PushFont(password_font);
}
// Process mouse inputs and character inputs
int backup_current_text_length = 0;
if (g.ActiveId == id)
{
IM_ASSERT(state != NULL);
backup_current_text_length = state->CurLenA;
state->BufCapacityA = buf_size;
state->UserFlags = flags;
state->UserCallback = callback;
state->UserCallbackData = callback_user_data;
// Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
// Down the line we should have a cleaner library-wide concept of Selected vs Active.
g.ActiveIdAllowOverlap = !io.MouseDown[0];
g.WantTextInputNextFrame = 1;
// Edit in progress
const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX;
const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
const bool is_osx = io.ConfigMacOSXBehaviors;
if (select_all || (hovered && !is_osx && io.MouseDoubleClicked[0]))
{
state->SelectAll();
state->SelectedAllMouseLock = true;
}
else if (hovered && is_osx && io.MouseDoubleClicked[0])
{
// Double-click select a word only, OS X style (by simulating keystrokes)
state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
}
else if (io.MouseClicked[0] && !state->SelectedAllMouseLock)
{
if (hovered)
{
stb_textedit_click(state, &state->Stb, mouse_x, mouse_y);
state->CursorAnimReset();
}
}
else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
{
stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y);
state->CursorAnimReset();
state->CursorFollow = true;
}
if (state->SelectedAllMouseLock && !io.MouseDown[0])
state->SelectedAllMouseLock = false;
// It is ill-defined whether the back-end needs to send a \t character when pressing the TAB keys.
// Win32 and GLFW naturally do it but not SDL.
const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper);
if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !ignore_char_inputs && !io.KeyShift && !is_readonly)
if (!io.InputQueueCharacters.contains('\t'))
{
unsigned int c = '\t'; // Insert TAB
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
// Process regular text input (before we check for Return because using some IME will effectively send a Return?)
// We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters.
if (io.InputQueueCharacters.Size > 0)
{
if (!ignore_char_inputs && !is_readonly && !user_nav_input_start)
for (int n = 0; n < io.InputQueueCharacters.Size; n++)
{
// Insert character if they pass filtering
unsigned int c = (unsigned int)io.InputQueueCharacters[n];
if (c == '\t' && io.KeyShift)
continue;
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
// Consume characters
io.InputQueueCharacters.resize(0);
}
}
// Process other shortcuts/key-presses
bool cancel_edit = false;
if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
{
IM_ASSERT(state != NULL);
IM_ASSERT(io.KeyMods == GetMergedKeyModFlags() && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods"); // We rarely do this check, but if anything let's do it here.
const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
const bool is_osx = io.ConfigMacOSXBehaviors;
const bool is_osx_shift_shortcut = is_osx && (io.KeyMods == (ImGuiKeyModFlags_Super | ImGuiKeyModFlags_Shift));
const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
const bool is_startend_key_down = is_osx && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
const bool is_ctrl_key_only = (io.KeyMods == ImGuiKeyModFlags_Ctrl);
const bool is_shift_key_only = (io.KeyMods == ImGuiKeyModFlags_Shift);
const bool is_shortcut_key = g.IO.ConfigMacOSXBehaviors ? (io.KeyMods == ImGuiKeyModFlags_Super) : (io.KeyMods == ImGuiKeyModFlags_Ctrl);
const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && !is_readonly && !is_password && (!is_multiline || state->HasSelection());
const bool is_copy = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || state->HasSelection());
const bool is_paste = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_readonly;
const bool is_undo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Z)) && !is_readonly && is_undoable);
const bool is_redo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressedMap(ImGuiKey_Z))) && !is_readonly && is_undoable;
if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Delete) && !is_readonly) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Backspace) && !is_readonly)
{
if (!state->HasSelection())
{
if (is_wordmove_key_down)
state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl)
state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
}
state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
}
else if (IsKeyPressedMap(ImGuiKey_Enter) || IsKeyPressedMap(ImGuiKey_KeyPadEnter))
{
bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
{
enter_pressed = clear_active_id = true;
}
else if (!is_readonly)
{
unsigned int c = '\n'; // Insert new line
if (InputTextFilterCharacter(&c, flags, callback, callback_user_data))
state->OnKeyPressed((int)c);
}
}
else if (IsKeyPressedMap(ImGuiKey_Escape))
{
clear_active_id = cancel_edit = true;
}
else if (is_undo || is_redo)
{
state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO);
state->ClearSelection();
}
else if (is_shortcut_key && IsKeyPressedMap(ImGuiKey_A))
{
state->SelectAll();
state->CursorFollow = true;
}
else if (is_cut || is_copy)
{
// Cut, Copy
if (io.SetClipboardTextFn)
{
const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0;
const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW;
const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1;
char* clipboard_data = (char*)IM_ALLOC(clipboard_data_len * sizeof(char));
ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie);
SetClipboardText(clipboard_data);
MemFree(clipboard_data);
}
if (is_cut)
{
if (!state->HasSelection())
state->SelectAll();
state->CursorFollow = true;
stb_textedit_cut(state, &state->Stb);
}
}
else if (is_paste)
{
if (const char* clipboard = GetClipboardText())
{
// Filter pasted buffer
const int clipboard_len = (int)strlen(clipboard);
ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len+1) * sizeof(ImWchar));
int clipboard_filtered_len = 0;
for (const char* s = clipboard; *s; )
{
unsigned int c;
s += ImTextCharFromUtf8(&c, s, NULL);
if (c == 0)
break;
if (!InputTextFilterCharacter(&c, flags, callback, callback_user_data))
continue;
clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
}
clipboard_filtered[clipboard_filtered_len] = 0;
if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
{
stb_textedit_paste(state, &state->Stb, clipboard_filtered, clipboard_filtered_len);
state->CursorFollow = true;
}
MemFree(clipboard_filtered);
}
}
// Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame.
render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
}
// Process callbacks and apply result back to user's buffer.
if (g.ActiveId == id)
{
IM_ASSERT(state != NULL);
const char* apply_new_text = NULL;
int apply_new_text_length = 0;
if (cancel_edit)
{
// Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
if (!is_readonly && strcmp(buf, state->InitialTextA.Data) != 0)
{
// Push records into the undo stack so we can CTRL+Z the revert operation itself
apply_new_text = state->InitialTextA.Data;
apply_new_text_length = state->InitialTextA.Size - 1;
ImVector<ImWchar> w_text;
if (apply_new_text_length > 0)
{
w_text.resize(ImTextCountCharsFromUtf8(apply_new_text, apply_new_text + apply_new_text_length) + 1);
ImTextStrFromUtf8(w_text.Data, w_text.Size, apply_new_text, apply_new_text + apply_new_text_length);
}
stb_textedit_replace(state, &state->Stb, w_text.Data, (apply_new_text_length > 0) ? (w_text.Size - 1) : 0);
}
}
// When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
// If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail.
// This also allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize).
bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
if (apply_edit_back_to_user_buffer)
{
// Apply new value immediately - copy modified buffer back
// Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
// FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
// FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
if (!is_readonly)
{
state->TextAIsValid = true;
state->TextA.resize(state->TextW.Size * 4 + 1);
ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL);
}
// User callback
if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
{
IM_ASSERT(callback != NULL);
// The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
ImGuiInputTextFlags event_flag = 0;
ImGuiKey event_key = ImGuiKey_COUNT;
if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
{
event_flag = ImGuiInputTextFlags_CallbackCompletion;
event_key = ImGuiKey_Tab;
}
else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
{
event_flag = ImGuiInputTextFlags_CallbackHistory;
event_key = ImGuiKey_UpArrow;
}
else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
{
event_flag = ImGuiInputTextFlags_CallbackHistory;
event_key = ImGuiKey_DownArrow;
}
else if (flags & ImGuiInputTextFlags_CallbackAlways)
event_flag = ImGuiInputTextFlags_CallbackAlways;
if (event_flag)
{
ImGuiInputTextCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData));
callback_data.EventFlag = event_flag;
callback_data.Flags = flags;
callback_data.UserData = callback_user_data;
callback_data.EventKey = event_key;
callback_data.Buf = state->TextA.Data;
callback_data.BufTextLen = state->CurLenA;
callback_data.BufSize = state->BufCapacityA;
callback_data.BufDirty = false;
// We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)
ImWchar* text = state->TextW.Data;
const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb.cursor);
const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_start);
const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_end);
// Call user code
callback(&callback_data);
// Read back what user may have modified
IM_ASSERT(callback_data.Buf == state->TextA.Data); // Invalid to modify those fields
IM_ASSERT(callback_data.BufSize == state->BufCapacityA);
IM_ASSERT(callback_data.Flags == flags);
if (callback_data.CursorPos != utf8_cursor_pos) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; }
if (callback_data.SelectionStart != utf8_selection_start) { state->Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); }
if (callback_data.SelectionEnd != utf8_selection_end) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); }
if (callback_data.BufDirty)
{
IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
if (callback_data.BufTextLen > backup_current_text_length && is_resizable)
state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length));
state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL);
state->CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
state->CursorAnimReset();
}
}
}
// Will copy result string if modified
if (!is_readonly && strcmp(state->TextA.Data, buf) != 0)
{
apply_new_text = state->TextA.Data;
apply_new_text_length = state->CurLenA;
}
}
// Copy result to user buffer
if (apply_new_text)
{
// We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size
// of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used
// without any storage on user's side.
IM_ASSERT(apply_new_text_length >= 0);
if (is_resizable)
{
ImGuiInputTextCallbackData callback_data;
callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize;
callback_data.Flags = flags;
callback_data.Buf = buf;
callback_data.BufTextLen = apply_new_text_length;
callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1);
callback_data.UserData = callback_user_data;
callback(&callback_data);
buf = callback_data.Buf;
buf_size = callback_data.BufSize;
apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1);
IM_ASSERT(apply_new_text_length <= buf_size);
}
//IMGUI_DEBUG_LOG("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length);
// If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size.
ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size));
value_changed = true;
}
// Clear temporary user storage
state->UserFlags = 0;
state->UserCallback = NULL;
state->UserCallbackData = NULL;
}
// Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
if (clear_active_id && g.ActiveId == id)
ClearActiveID();
// Render frame
if (!is_multiline)
{
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
}
const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size
ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
ImVec2 text_size(0.0f, 0.0f);
// Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
// without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
// Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash.
const int buf_display_max_length = 2 * 1024 * 1024;
const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595
const char* buf_display_end = NULL; // We have specialized paths below for setting the length
if (is_displaying_hint)
{
buf_display = hint;
buf_display_end = hint + strlen(hint);
}
// Render text. We currently only render selection when the widget is active or while scrolling.
// FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive.
if (render_cursor || render_selection)
{
IM_ASSERT(state != NULL);
if (!is_displaying_hint)
buf_display_end = buf_display + state->CurLenA;
// Render text (with cursor and selection)
// This is going to be messy. We need to:
// - Display the text (this alone can be more easily clipped)
// - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
// - Measure text height (for scrollbar)
// We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
// FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
const ImWchar* text_begin = state->TextW.Data;
ImVec2 cursor_offset, select_start_offset;
{
// Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions.
const ImWchar* searches_input_ptr[2] = { NULL, NULL };
int searches_result_line_no[2] = { -1000, -1000 };
int searches_remaining = 0;
if (render_cursor)
{
searches_input_ptr[0] = text_begin + state->Stb.cursor;
searches_result_line_no[0] = -1;
searches_remaining++;
}
if (render_selection)
{
searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end);
searches_result_line_no[1] = -1;
searches_remaining++;
}
// Iterate all lines to find our line numbers
// In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
searches_remaining += is_multiline ? 1 : 0;
int line_count = 0;
//for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\n')) != NULL; s++) // FIXME-OPT: Could use this when wchar_t are 16-bit
for (const ImWchar* s = text_begin; *s != 0; s++)
if (*s == '\n')
{
line_count++;
if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; }
if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; }
}
line_count++;
if (searches_result_line_no[0] == -1)
searches_result_line_no[0] = line_count;
if (searches_result_line_no[1] == -1)
searches_result_line_no[1] = line_count;
// Calculate 2d position by finding the beginning of the line and measuring distance
cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
cursor_offset.y = searches_result_line_no[0] * g.FontSize;
if (searches_result_line_no[1] >= 0)
{
select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
select_start_offset.y = searches_result_line_no[1] * g.FontSize;
}
// Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
if (is_multiline)
text_size = ImVec2(inner_size.x, line_count * g.FontSize);
}
// Scroll
if (render_cursor && state->CursorFollow)
{
// Horizontal scroll in chunks of quarter width
if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
{
const float scroll_increment_x = inner_size.x * 0.25f;
if (cursor_offset.x < state->ScrollX)
state->ScrollX = IM_FLOOR(ImMax(0.0f, cursor_offset.x - scroll_increment_x));
else if (cursor_offset.x - inner_size.x >= state->ScrollX)
state->ScrollX = IM_FLOOR(cursor_offset.x - inner_size.x + scroll_increment_x);
}
else
{
state->ScrollX = 0.0f;
}
// Vertical scroll
if (is_multiline)
{
float scroll_y = draw_window->Scroll.y;
if (cursor_offset.y - g.FontSize < scroll_y)
scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
else if (cursor_offset.y - inner_size.y >= scroll_y)
scroll_y = cursor_offset.y - inner_size.y;
draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag
draw_window->Scroll.y = scroll_y;
}
state->CursorFollow = false;
}
// Draw selection
const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f);
if (render_selection)
{
const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end);
const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end);
ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.
float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll;
for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
{
if (rect_pos.y > clip_rect.w + g.FontSize)
break;
if (rect_pos.y < clip_rect.y)
{
//p = (const ImWchar*)wmemchr((const wchar_t*)p, '\n', text_selected_end - p); // FIXME-OPT: Could use this when wchar_t are 16-bit
//p = p ? p + 1 : text_selected_end;
while (p < text_selected_end)
if (*p++ == '\n')
break;
}
else
{
ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
if (rect_size.x <= 0.0f) rect_size.x = IM_FLOOR(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
rect.ClipWith(clip_rect);
if (rect.Overlaps(clip_rect))
draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
}
rect_pos.x = draw_pos.x - draw_scroll.x;
rect_pos.y += g.FontSize;
}
}
// We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.
if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
{
ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
}
// Draw blinking cursor
if (render_cursor)
{
state->CursorAnim += io.DeltaTime;
bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;
ImVec2 cursor_screen_pos = draw_pos + cursor_offset - draw_scroll;
ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f);
if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
// Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
if (!is_readonly)
g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);
}
}
else
{
// Render text only (no selection, no cursor)
if (is_multiline)
text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width
else if (!is_displaying_hint && g.ActiveId == id)
buf_display_end = buf_display + state->CurLenA;
else if (!is_displaying_hint)
buf_display_end = buf_display + strlen(buf_display);
if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
{
ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
}
}
if (is_multiline)
{
Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
EndChild();
EndGroup();
}
if (is_password && !is_displaying_hint)
PopFont();
// Log as text
if (g.LogEnabled && !(is_password && !is_displaying_hint))
LogRenderedText(&draw_pos, buf_display, buf_display_end);
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if (value_changed && !(flags & ImGuiInputTextFlags_NoMarkEdited))
MarkItemEdited(id);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
return enter_pressed;
else
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
//-------------------------------------------------------------------------
// - ColorEdit3()
// - ColorEdit4()
// - ColorPicker3()
// - RenderColorRectWithAlphaCheckerboard() [Internal]
// - ColorPicker4()
// - ColorButton()
// - SetColorEditOptions()
// - ColorTooltip() [Internal]
// - ColorEditOptionsPopup() [Internal]
// - ColorPickerOptionsPopup() [Internal]
//-------------------------------------------------------------------------
bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
}
// Edit colors components (each component in 0.0f..1.0f range).
// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
// With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float square_sz = GetFrameHeight();
const float w_full = CalcItemWidth();
const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
const float w_inputs = w_full - w_button;
const char* label_display_end = FindRenderedTextEnd(label);
g.NextItemData.ClearFlags();
BeginGroup();
PushID(label);
// If we're not showing any slider there's no point in doing any HSV conversions
const ImGuiColorEditFlags flags_untouched = flags;
if (flags & ImGuiColorEditFlags_NoInputs)
flags = (flags & (~ImGuiColorEditFlags__DisplayMask)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions;
// Context menu: display and modify options (before defaults are applied)
if (!(flags & ImGuiColorEditFlags_NoOptions))
ColorEditOptionsPopup(col, flags);
// Read stored options
if (!(flags & ImGuiColorEditFlags__DisplayMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DisplayMask);
if (!(flags & ImGuiColorEditFlags__DataTypeMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask);
if (!(flags & ImGuiColorEditFlags__PickerMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask);
if (!(flags & ImGuiColorEditFlags__InputMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputMask);
flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask));
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check that only 1 is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected
const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
const int components = alpha ? 4 : 3;
// Convert to the formats we need
float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB))
ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV))
{
// Hue is lost when converting from greyscale rgb (saturation=0). Restore it.
ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
if (memcmp(g.ColorEditLastColor, col, sizeof(float) * 3) == 0)
{
if (f[1] == 0)
f[0] = g.ColorEditLastHue;
if (f[2] == 0)
f[1] = g.ColorEditLastSat;
}
}
int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
bool value_changed = false;
bool value_changed_as_float = false;
const ImVec2 pos = window->DC.CursorPos;
const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f;
window->DC.CursorPos.x = pos.x + inputs_offset_x;
if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
// RGB/HSV 0..255 Sliders
const float w_item_one = ImMax(1.0f, IM_FLOOR((w_inputs - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, IM_FLOOR(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
static const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
static const char* fmt_table_int[3][4] =
{
{ "%3d", "%3d", "%3d", "%3d" }, // Short display
{ "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA
{ "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA
};
static const char* fmt_table_float[3][4] =
{
{ "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
{ "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
{ "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
};
const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1;
for (int n = 0; n < components; n++)
{
if (n > 0)
SameLine(0, style.ItemInnerSpacing.x);
SetNextItemWidth((n + 1 < components) ? w_item_one : w_item_last);
// FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0.
if (flags & ImGuiColorEditFlags_Float)
{
value_changed |= DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
value_changed_as_float |= value_changed;
}
else
{
value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
}
else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
// RGB Hexadecimal Input
char buf[64];
if (alpha)
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255));
else
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255));
SetNextItemWidth(w_inputs);
if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
{
value_changed = true;
char* p = buf;
while (*p == '#' || ImCharIsBlankA(*p))
p++;
i[0] = i[1] = i[2] = i[3] = 0;
if (alpha)
sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
else
sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
ImGuiWindow* picker_active_window = NULL;
if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
{
const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x;
window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y);
const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
if (ColorButton("##ColorButton", col_v4, flags))
{
if (!(flags & ImGuiColorEditFlags_NoPicker))
{
// Store current color and open a picker
g.ColorPickerRef = col_v4;
OpenPopup("picker");
SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y));
}
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
if (BeginPopup("picker"))
{
picker_active_window = g.CurrentWindow;
if (label != label_display_end)
{
TextEx(label, label_display_end);
Spacing();
}
ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
EndPopup();
}
}
if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
{
const float text_offset_x = (flags & ImGuiColorEditFlags_NoInputs) ? w_button : w_full + style.ItemInnerSpacing.x;
window->DC.CursorPos = ImVec2(pos.x + text_offset_x, pos.y + style.FramePadding.y);
TextEx(label, label_display_end);
}
// Convert back
if (value_changed && picker_active_window == NULL)
{
if (!value_changed_as_float)
for (int n = 0; n < 4; n++)
f[n] = i[n] / 255.0f;
if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB))
{
g.ColorEditLastHue = f[0];
g.ColorEditLastSat = f[1];
ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
memcpy(g.ColorEditLastColor, f, sizeof(float) * 3);
}
if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV))
ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
col[0] = f[0];
col[1] = f[1];
col[2] = f[2];
if (alpha)
col[3] = f[3];
}
PopID();
EndGroup();
// Drag and Drop Target
// NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())
{
bool accepted_drag_drop = false;
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
{
memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512
value_changed = accepted_drag_drop = true;
}
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
{
memcpy((float*)col, payload->Data, sizeof(float) * components);
value_changed = accepted_drag_drop = true;
}
// Drag-drop payloads are always RGB
if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV))
ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]);
EndDragDropTarget();
}
// When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
window->DC.LastItemId = g.ActiveId;
if (value_changed)
MarkItemEdited(window->DC.LastItemId);
return value_changed;
}
bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
float col4[4] = { col[0], col[1], col[2], 1.0f };
if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
return false;
col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
return true;
}
// Helper for ColorPicker4()
static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha)
{
ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha);
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8));
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8));
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8));
ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8));
}
// Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
// (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.)
// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
// FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0)
bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImDrawList* draw_list = window->DrawList;
ImGuiStyle& style = g.Style;
ImGuiIO& io = g.IO;
const float width = CalcItemWidth();
g.NextItemData.ClearFlags();
PushID(label);
BeginGroup();
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
flags |= ImGuiColorEditFlags_NoSmallPreview;
// Context menu: display and store options.
if (!(flags & ImGuiColorEditFlags_NoOptions))
ColorPickerOptionsPopup(col, flags);
// Read stored options
if (!(flags & ImGuiColorEditFlags__PickerMask))
flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask;
if (!(flags & ImGuiColorEditFlags__InputMask))
flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__InputMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__InputMask;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check that only 1 is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected
if (!(flags & ImGuiColorEditFlags_NoOptions))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
// Setup
int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
ImVec2 picker_pos = window->DC.CursorPos;
float square_sz = GetFrameHeight();
float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
float bars_triangles_half_sz = IM_FLOOR(bars_width * 0.20f);
float backup_initial_col[4];
memcpy(backup_initial_col, col, components * sizeof(float));
float wheel_thickness = sv_picker_size * 0.08f;
float wheel_r_outer = sv_picker_size * 0.50f;
float wheel_r_inner = wheel_r_outer - wheel_thickness;
ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f);
// Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
float H = col[0], S = col[1], V = col[2];
float R = col[0], G = col[1], B = col[2];
if (flags & ImGuiColorEditFlags_InputRGB)
{
// Hue is lost when converting from greyscale rgb (saturation=0). Restore it.
ColorConvertRGBtoHSV(R, G, B, H, S, V);
if (memcmp(g.ColorEditLastColor, col, sizeof(float) * 3) == 0)
{
if (S == 0)
H = g.ColorEditLastHue;
if (V == 0)
S = g.ColorEditLastSat;
}
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
ColorConvertHSVtoRGB(H, S, V, R, G, B);
}
bool value_changed = false, value_changed_h = false, value_changed_sv = false;
PushItemFlag(ImGuiItemFlags_NoNav, true);
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Hue wheel + SV triangle logic
InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
if (IsItemActive())
{
ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
ImVec2 current_off = g.IO.MousePos - wheel_center;
float initial_dist2 = ImLengthSqr(initial_off);
if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1))
{
// Interactive with Hue wheel
H = ImAtan2(current_off.y, current_off.x) / IM_PI*0.5f;
if (H < 0.0f)
H += 1.0f;
value_changed = value_changed_h = true;
}
float cos_hue_angle = ImCos(-H * 2.0f * IM_PI);
float sin_hue_angle = ImSin(-H * 2.0f * IM_PI);
if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
{
// Interacting with SV triangle
ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
float uu, vv, ww;
ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
S = ImClamp(uu / V, 0.0001f, 1.0f);
value_changed = value_changed_sv = true;
}
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
else if (flags & ImGuiColorEditFlags_PickerHueBar)
{
// SV rectangle logic
InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
if (IsItemActive())
{
S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1));
V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = value_changed_sv = true;
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
// Hue bar logic
SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
if (IsItemActive())
{
H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = value_changed_h = true;
}
}
// Alpha bar logic
if (alpha_bar)
{
SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
if (IsItemActive())
{
col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = true;
}
}
PopItemFlag(); // ImGuiItemFlags_NoNav
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
SameLine(0, style.ItemInnerSpacing.x);
BeginGroup();
}
if (!(flags & ImGuiColorEditFlags_NoLabel))
{
const char* label_display_end = FindRenderedTextEnd(label);
if (label != label_display_end)
{
if ((flags & ImGuiColorEditFlags_NoSidePreview))
SameLine(0, style.ItemInnerSpacing.x);
TextEx(label, label_display_end);
}
}
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if ((flags & ImGuiColorEditFlags_NoLabel))
Text("Current");
ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip;
ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2));
if (ref_col != NULL)
{
Text("Original");
ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)))
{
memcpy(col, ref_col, components * sizeof(float));
value_changed = true;
}
}
PopItemFlag();
EndGroup();
}
// Convert back color to RGB
if (value_changed_h || value_changed_sv)
{
if (flags & ImGuiColorEditFlags_InputRGB)
{
ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]);
g.ColorEditLastHue = H;
g.ColorEditLastSat = S;
memcpy(g.ColorEditLastColor, col, sizeof(float) * 3);
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
col[0] = H;
col[1] = S;
col[2] = V;
}
}
// R,G,B and H,S,V slider color editor
bool value_changed_fix_hue_wrap = false;
if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
{
PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB))
{
// FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget.
// For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050)
value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap);
value_changed = true;
}
if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV);
if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags__DisplayMask) == 0)
value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex);
PopItemWidth();
}
// Try to cancel hue wrap (after ColorEdit4 call), if any
if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB))
{
float new_H, new_S, new_V;
ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
if (new_H <= 0 && H > 0)
{
if (new_V <= 0 && V != new_V)
ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
else if (new_S <= 0)
ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
}
}
if (value_changed)
{
if (flags & ImGuiColorEditFlags_InputRGB)
{
R = col[0];
G = col[1];
B = col[2];
ColorConvertRGBtoHSV(R, G, B, H, S, V);
if (memcmp(g.ColorEditLastColor, col, sizeof(float) * 3) == 0) // Fix local Hue as display below will use it immediately.
{
if (S == 0)
H = g.ColorEditLastHue;
if (V == 0)
S = g.ColorEditLastSat;
}
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
H = col[0];
S = col[1];
V = col[2];
ColorConvertHSVtoRGB(H, S, V, R, G, B);
}
}
const int style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha);
const ImU32 col_black = IM_COL32(0,0,0,style_alpha8);
const ImU32 col_white = IM_COL32(255,255,255,style_alpha8);
const ImU32 col_midgrey = IM_COL32(128,128,128,style_alpha8);
const ImU32 col_hues[6 + 1] = { IM_COL32(255,0,0,style_alpha8), IM_COL32(255,255,0,style_alpha8), IM_COL32(0,255,0,style_alpha8), IM_COL32(0,255,255,style_alpha8), IM_COL32(0,0,255,style_alpha8), IM_COL32(255,0,255,style_alpha8), IM_COL32(255,0,0,style_alpha8) };
ImVec4 hue_color_f(1, 1, 1, style.Alpha); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
ImU32 user_col32_striped_of_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)); // Important: this is still including the main rendering/style alpha!!
ImVec2 sv_cursor_pos;
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Render Hue Wheel
const float aeps = 0.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
for (int n = 0; n < 6; n++)
{
const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
const int vert_start_idx = draw_list->VtxBuffer.Size;
draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
draw_list->PathStroke(col_white, false, wheel_thickness);
const int vert_end_idx = draw_list->VtxBuffer.Size;
// Paint colors over existing vertices
ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner);
ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner);
ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n+1]);
}
// Render Cursor + preview on Hue Wheel
float cos_hue_angle = ImCos(H * 2.0f * IM_PI);
float sin_hue_angle = ImSin(H * 2.0f * IM_PI);
ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f);
float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32);
draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, col_midgrey, hue_cursor_segments);
draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments);
// Render SV triangle (rotated according to hue)
ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
ImVec2 uv_white = GetFontTexUvWhitePixel();
draw_list->PrimReserve(6, 6);
draw_list->PrimVtx(tra, uv_white, hue_color32);
draw_list->PrimVtx(trb, uv_white, hue_color32);
draw_list->PrimVtx(trc, uv_white, col_white);
draw_list->PrimVtx(tra, uv_white, 0);
draw_list->PrimVtx(trb, uv_white, col_black);
draw_list->PrimVtx(trc, uv_white, 0);
draw_list->AddTriangle(tra, trb, trc, col_midgrey, 1.5f);
sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
}
else if (flags & ImGuiColorEditFlags_PickerHueBar)
{
// Render SV Square
draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white);
draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black);
RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f);
sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
// Render Hue Bar
for (int i = 0; i < 6; ++i)
draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), col_hues[i], col_hues[i], col_hues[i + 1], col_hues[i + 1]);
float bar0_line_y = IM_ROUND(picker_pos.y + H * sv_picker_size);
RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha);
}
// Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f;
draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, 12);
draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, col_midgrey, 12);
draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, 12);
// Render alpha bar
if (alpha_bar)
{
float alpha = ImSaturate(col[3]);
ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
RenderColorRectWithAlphaCheckerboard(draw_list, bar1_bb.Min, bar1_bb.Max, 0, bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, user_col32_striped_of_alpha, user_col32_striped_of_alpha, user_col32_striped_of_alpha & ~IM_COL32_A_MASK, user_col32_striped_of_alpha & ~IM_COL32_A_MASK);
float bar1_line_y = IM_ROUND(picker_pos.y + (1.0f - alpha) * sv_picker_size);
RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha);
}
EndGroup();
if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0)
value_changed = false;
if (value_changed)
MarkItemEdited(window->DC.LastItemId);
PopID();
return value_changed;
}
// A little colored square. Return true when clicked.
// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
// Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set.
bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(desc_id);
float default_size = GetFrameHeight();
if (size.x == 0.0f)
size.x = default_size;
if (size.y == 0.0f)
size.y = default_size;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
if (flags & ImGuiColorEditFlags_NoAlpha)
flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
ImVec4 col_rgb = col;
if (flags & ImGuiColorEditFlags_InputHSV)
ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z);
ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f);
float grid_step = ImMin(size.x, size.y) / 2.99f;
float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
ImRect bb_inner = bb;
float off = 0.0f;
if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
{
off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.
bb_inner.Expand(off);
}
if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f)
{
float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f);
RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight);
window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft);
}
else
{
// Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha;
if (col_source.w < 1.0f)
RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
else
window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All);
}
RenderNavHighlight(bb, id);
if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
{
if (g.Style.FrameBorderSize > 0.0f)
RenderFrameBorder(bb.Min, bb.Max, rounding);
else
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
}
// Drag and Drop Source
// NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test.
if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource())
{
if (flags & ImGuiColorEditFlags_NoAlpha)
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once);
else
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once);
ColorButton(desc_id, col, flags);
SameLine();
TextEx("Color");
EndDragDropSource();
}
// Tooltip
if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered)
ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
return pressed;
}
// Initialize/override default color options
void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
{
ImGuiContext& g = *GImGui;
if ((flags & ImGuiColorEditFlags__DisplayMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DisplayMask;
if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask;
if ((flags & ImGuiColorEditFlags__PickerMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask;
if ((flags & ImGuiColorEditFlags__InputMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputMask;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DataTypeMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check only 1 option is selected
g.ColorEditOptions = flags;
}
// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
{
ImGuiContext& g = *GImGui;
BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
if (text_end > text)
{
TextEx(text, text_end);
Separator();
}
ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
SameLine();
if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags__InputMask))
{
if (flags & ImGuiColorEditFlags_NoAlpha)
Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
else
Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
}
else if (flags & ImGuiColorEditFlags_InputHSV)
{
if (flags & ImGuiColorEditFlags_NoAlpha)
Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]);
else
Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]);
}
EndTooltip();
}
void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
{
bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__DisplayMask);
bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask);
if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
return;
ImGuiContext& g = *GImGui;
ImGuiColorEditFlags opts = g.ColorEditOptions;
if (allow_opt_inputs)
{
if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayRGB;
if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHSV;
if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHex;
}
if (allow_opt_datatype)
{
if (allow_opt_inputs) Separator();
if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8;
if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float;
}
if (allow_opt_inputs || allow_opt_datatype)
Separator();
if (Button("Copy as..", ImVec2(-1,0)))
OpenPopup("Copy");
if (BeginPopup("Copy"))
{
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
char buf[64];
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if (Selectable(buf))
SetClipboardText(buf);
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
if (Selectable(buf))
SetClipboardText(buf);
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", cr, cg, cb);
if (Selectable(buf))
SetClipboardText(buf);
if (!(flags & ImGuiColorEditFlags_NoAlpha))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", cr, cg, cb, ca);
if (Selectable(buf))
SetClipboardText(buf);
}
EndPopup();
}
g.ColorEditOptions = opts;
EndPopup();
}
void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags)
{
bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask);
bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context"))
return;
ImGuiContext& g = *GImGui;
if (allow_opt_picker)
{
ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
PushItemWidth(picker_size.x);
for (int picker_type = 0; picker_type < 2; picker_type++)
{
// Draw small/thumbnail version of each picker type (over an invisible button for selection)
if (picker_type > 0) Separator();
PushID(picker_type);
ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha);
if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
ImVec2 backup_pos = GetCursorScreenPos();
if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask);
SetCursorScreenPos(backup_pos);
ImVec4 dummy_ref_col;
memcpy(&dummy_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4));
ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags);
PopID();
}
PopItemWidth();
}
if (allow_opt_alpha_bar)
{
if (allow_opt_picker) Separator();
CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
}
EndPopup();
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
//-------------------------------------------------------------------------
// - TreeNode()
// - TreeNodeV()
// - TreeNodeEx()
// - TreeNodeExV()
// - TreeNodeBehavior() [Internal]
// - TreePush()
// - TreePop()
// - GetTreeNodeToLabelSpacing()
// - SetNextItemOpen()
// - CollapsingHeader()
//-------------------------------------------------------------------------
bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(str_id, 0, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const char* label)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), 0, label, NULL);
}
bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
{
return TreeNodeExV(str_id, 0, fmt, args);
}
bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
{
return TreeNodeExV(ptr_id, 0, fmt, args);
}
bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags, label, NULL);
}
bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(str_id, flags, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);
}
bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);
}
bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
{
if (flags & ImGuiTreeNodeFlags_Leaf)
return true;
// We only write to the tree storage if the user clicks (or explicitly use the SetNextItemOpen function)
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiStorage* storage = window->DC.StateStorage;
bool is_open;
if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasOpen)
{
if (g.NextItemData.OpenCond & ImGuiCond_Always)
{
is_open = g.NextItemData.OpenVal;
storage->SetInt(id, is_open);
}
else
{
// We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
const int stored_value = storage->GetInt(id, -1);
if (stored_value == -1)
{
is_open = g.NextItemData.OpenVal;
storage->SetInt(id, is_open);
}
else
{
is_open = stored_value != 0;
}
}
}
else
{
is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
}
// When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
// NB- If we are above max depth we still allow manually opened nodes to be logged.
if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand)
is_open = true;
return is_open;
}
bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y));
if (!label_end)
label_end = FindRenderedTextEnd(label);
const ImVec2 label_size = CalcTextSize(label, label_end, false);
// We vertically grow up to current line height up the typical widget height.
const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
ImRect frame_bb;
frame_bb.Min.x = (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x;
frame_bb.Min.y = window->DC.CursorPos.y;
frame_bb.Max.x = window->WorkRect.Max.x;
frame_bb.Max.y = window->DC.CursorPos.y + frame_height;
if (display_frame)
{
// Framed header expand a little outside the default padding, to the edge of InnerClipRect
// (FIXME: May remove this at some point and make InnerClipRect align with WindowPadding.x instead of WindowPadding.x*0.5f)
frame_bb.Min.x -= IM_FLOOR(window->WindowPadding.x * 0.5f - 1.0f);
frame_bb.Max.x += IM_FLOOR(window->WindowPadding.x * 0.5f);
}
const float text_offset_x = g.FontSize + (display_frame ? padding.x*3 : padding.x*2); // Collapser arrow width + Spacing
const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it
const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser
ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y);
ItemSize(ImVec2(text_width, frame_height), padding.y);
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
ImRect interact_bb = frame_bb;
if (!display_frame && (flags & (ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth)) == 0)
interact_bb.Max.x = frame_bb.Min.x + text_width + style.ItemSpacing.x * 2.0f;
// Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.
// For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
// This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.
const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0;
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
window->DC.TreeJumpToParentOnPopMask |= (1 << window->DC.TreeDepth);
bool item_add = ItemAdd(interact_bb, id);
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
window->DC.LastItemDisplayRect = frame_bb;
if (!item_add)
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushOverrideID(id);
IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
return is_open;
}
ImGuiButtonFlags button_flags = ImGuiTreeNodeFlags_None;
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
button_flags |= ImGuiButtonFlags_AllowItemOverlap;
if (!is_leaf)
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
// We allow clicking on the arrow section with keyboard modifiers held, in order to easily
// allow browsing a tree while preserving selection with code implementing multi-selection patterns.
// When clicking on the rest of the tree node we always disallow keyboard modifiers.
const float arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x;
const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x;
const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2);
if (window != g.HoveredWindow || !is_mouse_x_over_arrow)
button_flags |= ImGuiButtonFlags_NoKeyModifiers;
// Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags.
// Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support.
// - Single-click on label = Toggle on MouseUp (default)
// - Single-click on arrow = Toggle on MouseUp (when _OpenOnArrow=0)
// - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1)
// - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1)
// - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0)
// This makes _OpenOnArrow have a subtle effect on _OpenOnDoubleClick: arrow click reacts on Down rather than Up.
// It is rather standard that arrow click react on Down rather than Up and we'd be tempted to make it the default
// (by removing the _OpenOnArrow test below), however this would have a perhaps surprising effect on CollapsingHeader()?
// So right now we are making this optional. May evolve later.
// We set ImGuiButtonFlags_PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work.
if (is_mouse_x_over_arrow && (flags & ImGuiTreeNodeFlags_OpenOnArrow))
button_flags |= ImGuiButtonFlags_PressedOnClick;
else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
else
button_flags |= ImGuiButtonFlags_PressedOnClickRelease;
bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0;
const bool was_selected = selected;
bool hovered, held;
bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
bool toggled = false;
if (!is_leaf)
{
if (pressed && g.DragDropHoldJustPressedId != id)
{
if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id))
toggled = true;
if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job
if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseDoubleClicked[0])
toggled = true;
}
else if (pressed && g.DragDropHoldJustPressedId == id)
{
IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);
if (!is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
toggled = true;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open)
{
toggled = true;
NavMoveRequestCancel();
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
{
toggled = true;
NavMoveRequestCancel();
}
if (toggled)
{
is_open = !is_open;
window->DC.StateStorage->SetInt(id, is_open);
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledOpen;
}
}
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
SetItemAllowOverlap();
// In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.
if (selected != was_selected) //-V547
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
// Render
const ImU32 text_col = GetColorU32(ImGuiCol_Text);
ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;
if (display_frame)
{
// Framed type
const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding);
RenderNavHighlight(frame_bb, id, nav_highlight_flags);
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col);
else if (!is_leaf)
RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
else // Leaf without bullet, left-adjusted text
text_pos.x -= text_offset_x;
if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton)
frame_bb.Max.x -= g.FontSize + style.FramePadding.x;
if (g.LogEnabled)
{
// NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
const char log_prefix[] = "\n##";
const char log_suffix[] = "##";
LogRenderedText(&text_pos, log_prefix, log_prefix+3);
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
LogRenderedText(&text_pos, log_suffix, log_suffix+2);
}
else
{
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
}
}
else
{
// Unframed typed for tree nodes
if (hovered || selected)
{
const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false);
RenderNavHighlight(frame_bb, id, nav_highlight_flags);
}
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col);
else if (!is_leaf)
RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
if (g.LogEnabled)
LogRenderedText(&text_pos, ">");
RenderText(text_pos, label, label_end, false);
}
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushOverrideID(id);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
return is_open;
}
void ImGui::TreePush(const char* str_id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
PushID(str_id ? str_id : "#TreePush");
}
void ImGui::TreePush(const void* ptr_id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
}
void ImGui::TreePushOverrideID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
Indent();
window->DC.TreeDepth++;
window->IDStack.push_back(id);
}
void ImGui::TreePop()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
Unindent();
window->DC.TreeDepth--;
ImU32 tree_depth_mask = (1 << window->DC.TreeDepth);
// Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled)
if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
if (g.NavIdIsAlive && (window->DC.TreeJumpToParentOnPopMask & tree_depth_mask))
{
SetNavID(window->IDStack.back(), g.NavLayer, 0);
NavMoveRequestCancel();
}
window->DC.TreeJumpToParentOnPopMask &= tree_depth_mask - 1;
IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much.
PopID();
}
// Horizontal distance preceding label when using TreeNode() or Bullet()
float ImGui::GetTreeNodeToLabelSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + (g.Style.FramePadding.x * 2.0f);
}
// Set next TreeNode/CollapsingHeader open state.
void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindow->SkipItems)
return;
g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasOpen;
g.NextItemData.OpenVal = is_open;
g.NextItemData.OpenCond = cond ? cond : ImGuiCond_Always;
}
// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().
bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader, label);
}
bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (p_open && !*p_open)
return false;
ImGuiID id = window->GetID(label);
flags |= ImGuiTreeNodeFlags_CollapsingHeader;
if (p_open)
flags |= ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton;
bool is_open = TreeNodeBehavior(id, flags, label);
if (p_open)
{
// Create a small overlapping close button
// FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
// FIXME: CloseButton can overlap into text, need find a way to clip the text somehow.
ImGuiContext& g = *GImGui;
ImGuiItemHoveredDataBackup last_item_backup;
float button_size = g.FontSize;
float button_x = ImMax(window->DC.LastItemRect.Min.x, window->DC.LastItemRect.Max.x - g.Style.FramePadding.x * 2.0f - button_size);
float button_y = window->DC.LastItemRect.Min.y;
if (CloseButton(window->GetID((void*)((intptr_t)id + 1)), ImVec2(button_x, button_y)))
*p_open = false;
last_item_backup.Restore();
}
return is_open;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Selectable
//-------------------------------------------------------------------------
// - Selectable()
//-------------------------------------------------------------------------
// Tip: pass a non-visible label (e.g. "##dummy") then you can use the space to draw other text or image.
// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id.
// With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowItemOverlap are also frequently used flags.
// FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported.
bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns) // FIXME-OPT: Avoid if vertically clipped.
PushColumnsBackground();
// Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle.
ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
ImVec2 pos = window->DC.CursorPos;
pos.y += window->DC.CurrLineTextBaseOffset;
ItemSize(size, 0.0f);
// Fill horizontal space
const float min_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ContentRegionRect.Min.x : pos.x;
const float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? window->ContentRegionRect.Max.x : GetContentRegionMaxAbs().x;
if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth))
size.x = ImMax(label_size.x, max_x - min_x);
// Text stays at the submission position, but bounding box may be extended on both sides
const ImVec2 text_min = pos;
const ImVec2 text_max(min_x + size.x, pos.y + size.y);
// Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
ImRect bb_enlarged(min_x, pos.y, text_max.x, text_max.y);
const float spacing_x = style.ItemSpacing.x;
const float spacing_y = style.ItemSpacing.y;
const float spacing_L = IM_FLOOR(spacing_x * 0.50f);
const float spacing_U = IM_FLOOR(spacing_y * 0.50f);
bb_enlarged.Min.x -= spacing_L;
bb_enlarged.Min.y -= spacing_U;
bb_enlarged.Max.x += (spacing_x - spacing_L);
bb_enlarged.Max.y += (spacing_y - spacing_U);
//if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb_align.Min, bb_align.Max, IM_COL32(255, 0, 0, 255)); }
//if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb_enlarged.Min, bb_enlarged.Max, IM_COL32(0, 255, 0, 255)); }
bool item_add;
if (flags & ImGuiSelectableFlags_Disabled)
{
ImGuiItemFlags backup_item_flags = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;
item_add = ItemAdd(bb_enlarged, id);
window->DC.ItemFlags = backup_item_flags;
}
else
{
item_add = ItemAdd(bb_enlarged, id);
}
if (!item_add)
{
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns)
PopColumnsBackground();
return false;
}
// We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries
ImGuiButtonFlags button_flags = 0;
if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }
if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }
if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }
if (flags & ImGuiSelectableFlags_Disabled) { button_flags |= ImGuiButtonFlags_Disabled; }
if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }
if (flags & ImGuiSelectableFlags_AllowItemOverlap) { button_flags |= ImGuiButtonFlags_AllowItemOverlap; }
if (flags & ImGuiSelectableFlags_Disabled)
selected = false;
const bool was_selected = selected;
bool hovered, held;
bool pressed = ButtonBehavior(bb_enlarged, id, &hovered, &held, button_flags);
// Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard
if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))
{
if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
{
g.NavDisableHighlight = true;
SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent);
}
}
if (pressed)
MarkItemEdited(id);
if (flags & ImGuiSelectableFlags_AllowItemOverlap)
SetItemAllowOverlap();
// In this branch, Selectable() cannot toggle the selection so this will never trigger.
if (selected != was_selected) //-V547
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
// Render
if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))
hovered = true;
if (hovered || selected)
{
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(bb_enlarged.Min, bb_enlarged.Max, col, false, 0.0f);
RenderNavHighlight(bb_enlarged, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
}
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.CurrentColumns)
PopColumnsBackground();
if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);
RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb_enlarged);
if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
// Automatically close popups
if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);
return pressed;
}
bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
{
if (Selectable(label, *p_selected, flags, size_arg))
{
*p_selected = !*p_selected;
return true;
}
return false;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: ListBox
//-------------------------------------------------------------------------
// - ListBox()
// - ListBoxHeader()
// - ListBoxFooter()
//-------------------------------------------------------------------------
// FIXME: This is an old API. We should redesign some of it, rename ListBoxHeader->BeginListBox, ListBoxFooter->EndListBox
// and promote using them over existing ListBox() functions, similarly to change with combo boxes.
//-------------------------------------------------------------------------
// FIXME: In principle this function should be called BeginListBox(). We should rename it after re-evaluating if we want to keep the same signature.
// Helper to calculate the size of a listbox and display a label on the right.
// Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an non-visible label e.g. "##empty"
bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
const ImGuiStyle& style = g.Style;
const ImGuiID id = GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
// Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy.
g.NextItemData.ClearFlags();
if (!IsRectVisible(bb.Min, bb.Max))
{
ItemSize(bb.GetSize(), style.FramePadding.y);
ItemAdd(bb, 0, &frame_bb);
return false;
}
BeginGroup();
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
BeginChildFrame(id, frame_bb.GetSize());
return true;
}
// FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature.
bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
{
// Size default to hold ~7.25 items.
// We add +25% worth of item height to allow the user to see at a glance if there are more items up/down, without looking at the scrollbar.
// We don't add this extra bit if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size.
// I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
if (height_in_items < 0)
height_in_items = ImMin(items_count, 7);
const ImGuiStyle& style = GetStyle();
float height_in_items_f = (height_in_items < items_count) ? (height_in_items + 0.25f) : (height_in_items + 0.00f);
// We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild().
ImVec2 size;
size.x = 0.0f;
size.y = ImFloor(GetTextLineHeightWithSpacing() * height_in_items_f + style.FramePadding.y * 2.0f);
return ListBoxHeader(label, size);
}
// FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature.
void ImGui::ListBoxFooter()
{
ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow;
const ImRect bb = parent_window->DC.LastItemRect;
const ImGuiStyle& style = GetStyle();
EndChildFrame();
// Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
// We call SameLine() to restore DC.CurrentLine* data
SameLine();
parent_window->DC.CursorPos = bb.Min;
ItemSize(bb, style.FramePadding.y);
EndGroup();
}
bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
{
const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
return value_changed;
}
bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
{
if (!ListBoxHeader(label, items_count, height_in_items))
return false;
// Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper.
ImGuiContext& g = *GImGui;
bool value_changed = false;
ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
{
const bool item_selected = (i == *current_item);
const char* item_text;
if (!items_getter(data, i, &item_text))
item_text = "*Unknown item*";
PushID(i);
if (Selectable(item_text, item_selected))
{
*current_item = i;
value_changed = true;
}
if (item_selected)
SetItemDefaultFocus();
PopID();
}
ListBoxFooter();
if (value_changed)
MarkItemEdited(g.CurrentWindow->DC.LastItemId);
return value_changed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: PlotLines, PlotHistogram
//-------------------------------------------------------------------------
// - PlotEx() [Internal]
// - PlotLines()
// - PlotHistogram()
//-------------------------------------------------------------------------
int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return -1;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
if (frame_size.x == 0.0f)
frame_size.x = CalcItemWidth();
if (frame_size.y == 0.0f)
frame_size.y = label_size.y + (style.FramePadding.y * 2);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0, &frame_bb))
return -1;
const bool hovered = ItemHoverable(frame_bb, id);
// Determine scale from values if not specified
if (scale_min == FLT_MAX || scale_max == FLT_MAX)
{
float v_min = FLT_MAX;
float v_max = -FLT_MAX;
for (int i = 0; i < values_count; i++)
{
const float v = values_getter(data, i);
if (v != v) // Ignore NaN values
continue;
v_min = ImMin(v_min, v);
v_max = ImMax(v_max, v);
}
if (scale_min == FLT_MAX)
scale_min = v_min;
if (scale_max == FLT_MAX)
scale_max = v_max;
}
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1;
int idx_hovered = -1;
if (values_count >= values_count_min)
{
int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
// Tooltip on hover
if (hovered && inner_bb.Contains(g.IO.MousePos))
{
const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
const int v_idx = (int)(t * item_count);
IM_ASSERT(v_idx >= 0 && v_idx < values_count);
const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
if (plot_type == ImGuiPlotType_Lines)
SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1);
else if (plot_type == ImGuiPlotType_Histogram)
SetTooltip("%d: %8.4g", v_idx, v0);
idx_hovered = v_idx;
}
const float t_step = 1.0f / (float)res_w;
const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
float v0 = values_getter(data, (0 + values_offset) % values_count);
float t0 = 0.0f;
ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
for (int n = 0; n < res_w; n++)
{
const float t1 = t0 + t_step;
const int v1_idx = (int)(t0 * item_count + 0.5f);
IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
// NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
if (plot_type == ImGuiPlotType_Lines)
{
window->DrawList->AddLine(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);
}
else if (plot_type == ImGuiPlotType_Histogram)
{
if (pos1.x >= pos0.x + 2.0f)
pos1.x -= 1.0f;
window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);
}
t0 = t1;
tp0 = tp1;
}
}
// Text overlay
if (overlay_text)
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
// Return hovered index or -1 if none are hovered.
// This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx().
return idx_hovered;
}
struct ImGuiPlotArrayGetterData
{
const float* Values;
int Stride;
ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
};
static float Plot_ArrayGetter(void* data, int idx)
{
ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
return v;
}
void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
{
ImGuiPlotArrayGetterData data(values, stride);
PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
{
ImGuiPlotArrayGetterData data(values, stride);
PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Value helpers
// Those is not very useful, legacy API.
//-------------------------------------------------------------------------
// - Value()
//-------------------------------------------------------------------------
void ImGui::Value(const char* prefix, bool b)
{
Text("%s: %s", prefix, (b ? "true" : "false"));
}
void ImGui::Value(const char* prefix, int v)
{
Text("%s: %d", prefix, v);
}
void ImGui::Value(const char* prefix, unsigned int v)
{
Text("%s: %d", prefix, v);
}
void ImGui::Value(const char* prefix, float v, const char* float_format)
{
if (float_format)
{
char fmt[64];
ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
Text(fmt, prefix, v);
}
else
{
Text("%s: %.3f", prefix, v);
}
}
//-------------------------------------------------------------------------
// [SECTION] MenuItem, BeginMenu, EndMenu, etc.
//-------------------------------------------------------------------------
// - ImGuiMenuColumns [Internal]
// - BeginMenuBar()
// - EndMenuBar()
// - BeginMainMenuBar()
// - EndMainMenuBar()
// - BeginMenu()
// - EndMenu()
// - MenuItem()
//-------------------------------------------------------------------------
// Helpers for internal use
ImGuiMenuColumns::ImGuiMenuColumns()
{
Spacing = Width = NextWidth = 0.0f;
memset(Pos, 0, sizeof(Pos));
memset(NextWidths, 0, sizeof(NextWidths));
}
void ImGuiMenuColumns::Update(int count, float spacing, bool clear)
{
IM_ASSERT(count == IM_ARRAYSIZE(Pos));
IM_UNUSED(count);
Width = NextWidth = 0.0f;
Spacing = spacing;
if (clear)
memset(NextWidths, 0, sizeof(NextWidths));
for (int i = 0; i < IM_ARRAYSIZE(Pos); i++)
{
if (i > 0 && NextWidths[i] > 0.0f)
Width += Spacing;
Pos[i] = IM_FLOOR(Width);
Width += NextWidths[i];
NextWidths[i] = 0.0f;
}
}
float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
{
NextWidth = 0.0f;
NextWidths[0] = ImMax(NextWidths[0], w0);
NextWidths[1] = ImMax(NextWidths[1], w1);
NextWidths[2] = ImMax(NextWidths[2], w2);
for (int i = 0; i < IM_ARRAYSIZE(Pos); i++)
NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
return ImMax(Width, NextWidth);
}
float ImGuiMenuColumns::CalcExtraSpace(float avail_w) const
{
return ImMax(0.0f, avail_w - Width);
}
// FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere..
// Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer.
// Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary.
// Then later the same system could be used for multiple menu-bars, scrollbars, side-bars.
bool ImGui::BeginMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (!(window->Flags & ImGuiWindowFlags_MenuBar))
return false;
IM_ASSERT(!window->DC.MenuBarAppending);
BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore
PushID("##menubar");
// We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect.
// We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy.
ImRect bar_rect = window->MenuBarRect();
ImRect clip_rect(IM_ROUND(bar_rect.Min.x + window->WindowBorderSize), IM_ROUND(bar_rect.Min.y + window->WindowBorderSize), IM_ROUND(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize))), IM_ROUND(bar_rect.Max.y));
clip_rect.ClipWith(window->OuterRectClipped);
PushClipRect(clip_rect.Min, clip_rect.Max, false);
window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y);
window->DC.LayoutType = ImGuiLayoutType_Horizontal;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
window->DC.MenuBarAppending = true;
AlignTextToFramePadding();
return true;
}
void ImGui::EndMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
// Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
{
ImGuiWindow* nav_earliest_child = g.NavWindow;
while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
nav_earliest_child = nav_earliest_child->ParentWindow;
if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None)
{
// To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
// This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost)
const ImGuiNavLayer layer = ImGuiNavLayer_Menu;
IM_ASSERT(window->DC.NavLayerActiveMaskNext & (1 << layer)); // Sanity check
FocusWindow(window);
SetNavIDWithRectRel(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
g.NavLayer = layer;
g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection.
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
NavMoveRequestCancel();
}
}
IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
IM_ASSERT(window->DC.MenuBarAppending);
PopClipRect();
PopID();
window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->MenuBarRect().Min.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos.
window->DC.GroupStack.back().EmitItem = false;
EndGroup(); // Restore position on layer 0
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.MenuBarAppending = false;
}
// For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set.
bool ImGui::BeginMainMenuBar()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f));
SetNextWindowPos(ImVec2(0.0f, 0.0f));
SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.NextWindowData.MenuBarOffsetMinVal.y + g.FontBaseSize + g.Style.FramePadding.y));
PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0));
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
bool is_open = Begin("##MainMenuBar", NULL, window_flags) && BeginMenuBar();
PopStyleVar(2);
g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);
if (!is_open)
{
End();
return false;
}
return true; //-V1020
}
void ImGui::EndMainMenuBar()
{
EndMenuBar();
// When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
// FIXME: With this strategy we won't be able to restore a NULL focus.
ImGuiContext& g = *GImGui;
if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest)
FocusTopMostWindowUnderOne(g.NavWindow, NULL);
End();
}
bool ImGui::BeginMenu(const char* label, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
bool menu_is_open = IsPopupOpen(id);
// Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu)
ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus;
if (window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu))
flags |= ImGuiWindowFlags_ChildWindow;
// If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin().
// We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame.
// If somehow this is ever becoming a problem we can switch to use e.g. a ImGuiStorager mapping key to last frame used.
if (g.MenusIdSubmittedThisFrame.contains(id))
{
if (menu_is_open)
menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
else
g.NextWindowData.ClearFlags(); // we behave like Begin() and need to consume those values
return menu_is_open;
}
// Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu
g.MenusIdSubmittedThisFrame.push_back(id);
ImVec2 label_size = CalcTextSize(label, NULL, true);
bool pressed;
bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].OpenParentId == window->IDStack.back());
ImGuiWindow* backed_nav_window = g.NavWindow;
if (menuset_is_open)
g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
// The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu,
// However the final position is going to be different! It is chosen by FindBestWindowPosForPopup().
// e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering.
ImVec2 popup_pos, pos = window->DC.CursorPos;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
// Menu inside an horizontal menu bar
// Selectable extend their highlight by half ItemSpacing in each direction.
// For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin()
popup_pos = ImVec2(pos.x - 1.0f - IM_FLOOR(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight());
window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y));
float w = label_size.x;
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
PopStyleVar();
window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
// Menu inside a menu
// (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
// Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
float min_w = window->DC.MenuColumns.DeclColumns(label_size.x, 0.0f, IM_FLOOR(g.FontSize * 1.20f)); // Feedback to next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_SpanAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(min_w, 0.0f));
ImU32 text_col = GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled);
RenderArrow(window->DrawList, pos + ImVec2(window->DC.MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), text_col, ImGuiDir_Right);
}
const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id);
if (menuset_is_open)
g.NavWindow = backed_nav_window;
bool want_open = false;
bool want_close = false;
if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
{
// Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu
// Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
bool moving_toward_other_child_menu = false;
ImGuiWindow* child_menu_window = (g.BeginPopupStack.Size < g.OpenPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window) ? g.OpenPopupStack[g.BeginPopupStack.Size].Window : NULL;
if (g.HoveredWindow == window && child_menu_window != NULL && !(window->Flags & ImGuiWindowFlags_MenuBar))
{
// FIXME-DPI: Values should be derived from a master "scale" factor.
ImRect next_window_rect = child_menu_window->Rect();
ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
ImVec2 tb = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
ImVec2 tc = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
ta.x += (window->Pos.x < child_menu_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?
tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
moving_toward_other_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
//GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG]
}
if (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_toward_other_child_menu)
want_close = true;
if (!menu_is_open && hovered && pressed) // Click to open
want_open = true;
else if (!menu_is_open && hovered && !moving_toward_other_child_menu) // Hover to open
want_open = true;
if (g.NavActivateId == id)
{
want_close = menu_is_open;
want_open = !menu_is_open;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
{
want_open = true;
NavMoveRequestCancel();
}
}
else
{
// Menu bar
if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
{
want_close = true;
want_open = menu_is_open = false;
}
else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
{
want_open = true;
}
else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
{
want_open = true;
NavMoveRequestCancel();
}
}
if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
want_close = true;
if (want_close && IsPopupOpen(id))
ClosePopupToLevel(g.BeginPopupStack.Size, true);
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));
if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)
{
// Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
OpenPopup(label);
return false;
}
menu_is_open |= want_open;
if (want_open)
OpenPopup(label);
if (menu_is_open)
{
SetNextWindowPos(popup_pos, ImGuiCond_Always);
menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
}
else
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
}
return menu_is_open;
}
void ImGui::EndMenu()
{
// Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).
// A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.
// However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)
{
ClosePopupToLevel(g.BeginPopupStack.Size, true);
NavMoveRequestCancel();
}
EndPopup();
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImVec2 label_size = CalcTextSize(label, NULL, true);
// We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73),
// but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only.
ImGuiSelectableFlags flags = ImGuiSelectableFlags_SelectOnRelease | ImGuiSelectableFlags_SetNavIdOnHover | (enabled ? 0 : ImGuiSelectableFlags_Disabled);
bool pressed;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
// Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
// Note that in this situation we render neither the shortcut neither the selected tick mark
float w = label_size.x;
window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y));
pressed = Selectable(label, false, flags, ImVec2(w, 0.0f));
PopStyleVar();
window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
// Menu item inside a vertical menu
// (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
// Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
float shortcut_w = shortcut ? CalcTextSize(shortcut, NULL).x : 0.0f;
float min_w = window->DC.MenuColumns.DeclColumns(label_size.x, shortcut_w, IM_FLOOR(g.FontSize * 1.20f)); // Feedback for next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
pressed = Selectable(label, false, flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, 0.0f));
if (shortcut_w > 0.0f)
{
PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderText(pos + ImVec2(window->DC.MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
PopStyleColor();
}
if (selected)
RenderCheckMark(window->DrawList, pos + ImVec2(window->DC.MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f);
}
IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0));
return pressed;
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
{
if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
{
if (p_selected)
*p_selected = !*p_selected;
return true;
}
return false;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
//-------------------------------------------------------------------------
// - BeginTabBar()
// - BeginTabBarEx() [Internal]
// - EndTabBar()
// - TabBarLayout() [Internal]
// - TabBarCalcTabID() [Internal]
// - TabBarCalcMaxTabWidth() [Internal]
// - TabBarFindTabById() [Internal]
// - TabBarRemoveTab() [Internal]
// - TabBarCloseTab() [Internal]
// - TabBarScrollClamp()v
// - TabBarScrollToTab() [Internal]
// - TabBarQueueChangeTabOrder() [Internal]
// - TabBarScrollingButtons() [Internal]
// - TabBarTabListPopupButton() [Internal]
//-------------------------------------------------------------------------
namespace ImGui
{
static void TabBarLayout(ImGuiTabBar* tab_bar);
static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label);
static float TabBarCalcMaxTabWidth();
static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling);
static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);
static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar);
static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar);
}
ImGuiTabBar::ImGuiTabBar()
{
ID = 0;
SelectedTabId = NextSelectedTabId = VisibleTabId = 0;
CurrFrameVisible = PrevFrameVisible = -1;
LastTabContentHeight = 0.0f;
OffsetMax = OffsetMaxIdeal = OffsetNextTab = 0.0f;
ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f;
Flags = ImGuiTabBarFlags_None;
ReorderRequestTabId = 0;
ReorderRequestDir = 0;
WantLayout = VisibleTabWasSubmitted = false;
LastTabItemIdx = -1;
}
static int IMGUI_CDECL TabItemComparerByVisibleOffset(const void* lhs, const void* rhs)
{
const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
return (int)(a->Offset - b->Offset);
}
static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref)
{
ImGuiContext& g = *GImGui;
return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index);
}
static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
if (g.TabBars.Contains(tab_bar))
return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar));
return ImGuiPtrOrIndex(tab_bar);
}
bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
ImGuiID id = window->GetID(str_id);
ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id);
ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2);
tab_bar->ID = id;
return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused);
}
bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
if ((flags & ImGuiTabBarFlags_DockNode) == 0)
PushOverrideID(tab_bar->ID);
// Add to stack
g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar));
g.CurrentTabBar = tab_bar;
if (tab_bar->CurrFrameVisible == g.FrameCount)
{
//IMGUI_DEBUG_LOG("BeginTabBarEx already called this frame\n", g.FrameCount);
IM_ASSERT(0);
return true;
}
// When toggling back from ordered to manually-reorderable, shuffle tabs to enforce the last visible order.
// Otherwise, the most recently inserted tabs would move at the end of visible list which can be a little too confusing or magic for the user.
if ((flags & ImGuiTabBarFlags_Reorderable) && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable) && tab_bar->Tabs.Size > 1 && tab_bar->PrevFrameVisible != -1)
ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByVisibleOffset);
// Flags
if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
tab_bar->Flags = flags;
tab_bar->BarRect = tab_bar_bb;
tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab()
tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible;
tab_bar->CurrFrameVisible = g.FrameCount;
tab_bar->FramePadding = g.Style.FramePadding;
// Layout
ItemSize(ImVec2(tab_bar->OffsetMaxIdeal, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y);
window->DC.CursorPos.x = tab_bar->BarRect.Min.x;
// Draw separator
const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive);
const float y = tab_bar->BarRect.Max.y - 1.0f;
{
const float separator_min_x = tab_bar->BarRect.Min.x - IM_FLOOR(window->WindowPadding.x * 0.5f);
const float separator_max_x = tab_bar->BarRect.Max.x + IM_FLOOR(window->WindowPadding.x * 0.5f);
window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f);
}
return true;
}
void ImGui::EndTabBar()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!");
return;
}
if (tab_bar->WantLayout)
TabBarLayout(tab_bar);
// Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed().
const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing)
tab_bar->LastTabContentHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, 0.0f);
else
window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->LastTabContentHeight;
if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
PopID();
g.CurrentTabBarStack.pop_back();
g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back());
}
// This is called only once a frame before by the first call to ItemTab()
// The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions.
static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
tab_bar->WantLayout = false;
// Garbage collect
int tab_dst_n = 0;
for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n];
if (tab->LastFrameVisible < tab_bar->PrevFrameVisible)
{
if (tab->ID == tab_bar->SelectedTabId)
tab_bar->SelectedTabId = 0;
continue;
}
if (tab_dst_n != tab_src_n)
tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n];
tab_dst_n++;
}
if (tab_bar->Tabs.Size != tab_dst_n)
tab_bar->Tabs.resize(tab_dst_n);
// Setup next selected tab
ImGuiID scroll_track_selected_tab_id = 0;
if (tab_bar->NextSelectedTabId)
{
tab_bar->SelectedTabId = tab_bar->NextSelectedTabId;
tab_bar->NextSelectedTabId = 0;
scroll_track_selected_tab_id = tab_bar->SelectedTabId;
}
// Process order change request (we could probably process it when requested but it's just saner to do it in a single spot).
if (tab_bar->ReorderRequestTabId != 0)
{
if (ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId))
{
//IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools
int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestDir;
if (tab2_order >= 0 && tab2_order < tab_bar->Tabs.Size)
{
ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order];
ImGuiTabItem item_tmp = *tab1;
*tab1 = *tab2;
*tab2 = item_tmp;
if (tab2->ID == tab_bar->SelectedTabId)
scroll_track_selected_tab_id = tab2->ID;
tab1 = tab2 = NULL;
}
if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings)
MarkIniSettingsDirty();
}
tab_bar->ReorderRequestTabId = 0;
}
// Tab List Popup (will alter tab_bar->BarRect and therefore the available width!)
const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0;
if (tab_list_popup_button)
if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x!
scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
// Compute ideal widths
g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size);
float width_total_contents = 0.0f;
ImGuiTabItem* most_recently_selected_tab = NULL;
bool found_selected_tab_id = false;
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible);
if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected)
most_recently_selected_tab = tab;
if (tab->ID == tab_bar->SelectedTabId)
found_selected_tab_id = true;
// Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar.
// Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet,
// and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window.
const char* tab_name = tab_bar->GetTabName(tab);
const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true;
tab->ContentWidth = TabItemCalcSize(tab_name, has_close_button).x;
width_total_contents += (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f) + tab->ContentWidth;
// Store data so we can build an array sorted by width if we need to shrink tabs down
g.ShrinkWidthBuffer[tab_n].Index = tab_n;
g.ShrinkWidthBuffer[tab_n].Width = tab->ContentWidth;
}
// Compute width
const float initial_offset_x = 0.0f; // g.Style.ItemInnerSpacing.x;
const float width_avail = ImMax(tab_bar->BarRect.GetWidth() - initial_offset_x, 0.0f);
float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f;
if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown))
{
// If we don't have enough room, resize down the largest tabs first
ShrinkWidths(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Size, width_excess);
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index].Width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width);
}
else
{
const float tab_max_width = TabBarCalcMaxTabWidth();
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
tab->Width = ImMin(tab->ContentWidth, tab_max_width);
IM_ASSERT(tab->Width > 0.0f);
}
}
// Layout all active tabs
float offset_x = initial_offset_x;
float offset_x_ideal = offset_x;
tab_bar->OffsetNextTab = offset_x; // This is used by non-reorderable tab bar where the submission order is always honored.
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
tab->Offset = offset_x;
if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID)
scroll_track_selected_tab_id = tab->ID;
offset_x += tab->Width + g.Style.ItemInnerSpacing.x;
offset_x_ideal += tab->ContentWidth + g.Style.ItemInnerSpacing.x;
}
tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f);
tab_bar->OffsetMaxIdeal = ImMax(offset_x_ideal - g.Style.ItemInnerSpacing.x, 0.0f);
// Horizontal scrolling buttons
const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll);
if (scrolling_buttons)
if (ImGuiTabItem* tab_to_select = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x!
scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
// If we have lost the selected tab, select the next most recently active one
if (found_selected_tab_id == false)
tab_bar->SelectedTabId = 0;
if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL)
scroll_track_selected_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID;
// Lock in visible tab
tab_bar->VisibleTabId = tab_bar->SelectedTabId;
tab_bar->VisibleTabWasSubmitted = false;
// Update scrolling
if (scroll_track_selected_tab_id)
if (ImGuiTabItem* scroll_track_selected_tab = TabBarFindTabByID(tab_bar, scroll_track_selected_tab_id))
TabBarScrollToTab(tab_bar, scroll_track_selected_tab);
tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim);
tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget);
if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget)
{
// Scrolling speed adjust itself so we can always reach our target in 1/3 seconds.
// Teleport if we are aiming far off the visible line
tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize);
tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f);
const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize);
tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed);
}
else
{
tab_bar->ScrollingSpeed = 0.0f;
}
// Clear name buffers
if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
tab_bar->TabsNames.Buf.resize(0);
}
// Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack.
static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label)
{
if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)
{
ImGuiID id = ImHashStr(label);
KeepAliveID(id);
return id;
}
else
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(label);
}
}
static float ImGui::TabBarCalcMaxTabWidth()
{
ImGuiContext& g = *GImGui;
return g.FontSize * 20.0f;
}
ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id)
{
if (tab_id != 0)
for (int n = 0; n < tab_bar->Tabs.Size; n++)
if (tab_bar->Tabs[n].ID == tab_id)
return &tab_bar->Tabs[n];
return NULL;
}
// The *TabId fields be already set by the docking system _before_ the actual TabItem was created, so we clear them regardless.
void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id)
{
if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
tab_bar->Tabs.erase(tab);
if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; }
if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; }
if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; }
}
// Called on manual closure attempt
void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
{
if ((tab_bar->VisibleTabId == tab->ID) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument))
{
// This will remove a frame of lag for selecting another tab on closure.
// However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure
tab->LastFrameVisible = -1;
tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0;
}
else if ((tab_bar->VisibleTabId != tab->ID) && (tab->Flags & ImGuiTabItemFlags_UnsavedDocument))
{
// Actually select before expecting closure
tab_bar->NextSelectedTabId = tab->ID;
}
}
static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling)
{
scrolling = ImMin(scrolling, tab_bar->OffsetMax - tab_bar->BarRect.GetWidth());
return ImMax(scrolling, 0.0f);
}
static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
{
ImGuiContext& g = *GImGui;
float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar)
int order = tab_bar->GetTabOrder(tab);
float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f);
float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f);
tab_bar->ScrollingTargetDistToVisibility = 0.0f;
if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= tab_bar->BarRect.GetWidth()))
{
tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f);
tab_bar->ScrollingTarget = tab_x1;
}
else if (tab_bar->ScrollingTarget < tab_x2 - tab_bar->BarRect.GetWidth())
{
tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - tab_bar->BarRect.GetWidth()) - tab_bar->ScrollingAnim, 0.0f);
tab_bar->ScrollingTarget = tab_x2 - tab_bar->BarRect.GetWidth();
}
}
void ImGui::TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir)
{
IM_ASSERT(dir == -1 || dir == +1);
IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
tab_bar->ReorderRequestTabId = tab->ID;
tab_bar->ReorderRequestDir = (ImS8)dir;
}
static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f);
const float scrolling_buttons_width = arrow_button_size.x * 2.0f;
const ImVec2 backup_cursor_pos = window->DC.CursorPos;
//window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255));
const ImRect avail_bar_rect = tab_bar->BarRect;
bool want_clip_rect = !avail_bar_rect.Contains(ImRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(scrolling_buttons_width, 0.0f)));
if (want_clip_rect)
PushClipRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max + ImVec2(g.Style.ItemInnerSpacing.x, 0.0f), true);
ImGuiTabItem* tab_to_select = NULL;
int select_dir = 0;
ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
arrow_col.w *= 0.5f;
PushStyleColor(ImGuiCol_Text, arrow_col);
PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
const float backup_repeat_delay = g.IO.KeyRepeatDelay;
const float backup_repeat_rate = g.IO.KeyRepeatRate;
g.IO.KeyRepeatDelay = 0.250f;
g.IO.KeyRepeatRate = 0.200f;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y);
if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))
select_dir = -1;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width + arrow_button_size.x, tab_bar->BarRect.Min.y);
if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))
select_dir = +1;
PopStyleColor(2);
g.IO.KeyRepeatRate = backup_repeat_rate;
g.IO.KeyRepeatDelay = backup_repeat_delay;
if (want_clip_rect)
PopClipRect();
if (select_dir != 0)
if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
{
int selected_order = tab_bar->GetTabOrder(tab_item);
int target_order = selected_order + select_dir;
tab_to_select = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; // If we are at the end of the list, still scroll to make our tab visible
}
window->DC.CursorPos = backup_cursor_pos;
tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f;
return tab_to_select;
}
static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We use g.Style.FramePadding.y to match the square ArrowButton size
const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y;
const ImVec2 backup_cursor_pos = window->DC.CursorPos;
window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y);
tab_bar->BarRect.Min.x += tab_list_popup_button_width;
ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
arrow_col.w *= 0.5f;
PushStyleColor(ImGuiCol_Text, arrow_col);
PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview);
PopStyleColor(2);
ImGuiTabItem* tab_to_select = NULL;
if (open)
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
const char* tab_name = tab_bar->GetTabName(tab);
if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID))
tab_to_select = tab;
}
EndCombo();
}
window->DC.CursorPos = backup_cursor_pos;
return tab_to_select;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
//-------------------------------------------------------------------------
// - BeginTabItem()
// - EndTabItem()
// - TabItemEx() [Internal]
// - SetTabItemClosed()
// - TabItemCalcSize() [Internal]
// - TabItemBackground() [Internal]
// - TabItemLabelAndCloseButton() [Internal]
//-------------------------------------------------------------------------
bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT_USER_ERROR(tab_bar, "BeginTabItem() Needs to be called between BeginTabBar() and EndTabBar()!");
return false;
}
bool ret = TabItemEx(tab_bar, label, p_open, flags);
if (ret && !(flags & ImGuiTabItemFlags_NoPushId))
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label)
}
return ret;
}
void ImGui::EndTabItem()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
ImGuiTabBar* tab_bar = g.CurrentTabBar;
if (tab_bar == NULL)
{
IM_ASSERT(tab_bar != NULL && "Needs to be called between BeginTabBar() and EndTabBar()!");
return;
}
IM_ASSERT(tab_bar->LastTabItemIdx >= 0);
ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
if (!(tab->Flags & ImGuiTabItemFlags_NoPushId))
window->IDStack.pop_back();
}
bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags)
{
// Layout whole tab bar if not already done
if (tab_bar->WantLayout)
TabBarLayout(tab_bar);
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
const ImGuiStyle& style = g.Style;
const ImGuiID id = TabBarCalcTabID(tab_bar, label);
// If the user called us with *p_open == false, we early out and don't render. We make a dummy call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID.
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
if (p_open && !*p_open)
{
PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true);
ItemAdd(ImRect(), id);
PopItemFlag();
return false;
}
// Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented)
if (flags & ImGuiTabItemFlags_NoCloseButton)
p_open = NULL;
else if (p_open == NULL)
flags |= ImGuiTabItemFlags_NoCloseButton;
// Calculate tab contents size
ImVec2 size = TabItemCalcSize(label, p_open != NULL);
// Acquire tab data
ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id);
bool tab_is_new = false;
if (tab == NULL)
{
tab_bar->Tabs.push_back(ImGuiTabItem());
tab = &tab_bar->Tabs.back();
tab->ID = id;
tab->Width = size.x;
tab_is_new = true;
}
tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab);
tab->ContentWidth = size.x;
const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0;
const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount);
tab->LastFrameVisible = g.FrameCount;
tab->Flags = flags;
// Append name with zero-terminator
tab->NameOffset = tab_bar->TabsNames.size();
tab_bar->TabsNames.append(label, label + strlen(label) + 1);
// If we are not reorderable, always reset offset based on submission order.
// (We already handled layout and sizing using the previous known order, but sizing is not affected by order!)
if (!tab_appearing && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable))
{
tab->Offset = tab_bar->OffsetNextTab;
tab_bar->OffsetNextTab += tab->Width + g.Style.ItemInnerSpacing.x;
}
// Update selected tab
if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0)
if (!tab_bar_appearing || tab_bar->SelectedTabId == 0)
tab_bar->NextSelectedTabId = id; // New tabs gets activated
if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // SetSelected can only be passed on explicit tab bar
tab_bar->NextSelectedTabId = id;
// Lock visibility
// (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!)
bool tab_contents_visible = (tab_bar->VisibleTabId == id);
if (tab_contents_visible)
tab_bar->VisibleTabWasSubmitted = true;
// On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches
if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing)
if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs))
tab_contents_visible = true;
if (tab_appearing && !(tab_bar_appearing && !tab_is_new))
{
PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true);
ItemAdd(ImRect(), id);
PopItemFlag();
return tab_contents_visible;
}
if (tab_bar->SelectedTabId == id)
tab->LastFrameSelected = g.FrameCount;
// Backup current layout position
const ImVec2 backup_main_cursor_pos = window->DC.CursorPos;
// Layout
size.x = tab->Width;
window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_FLOOR(tab->Offset - tab_bar->ScrollingAnim), 0.0f);
ImVec2 pos = window->DC.CursorPos;
ImRect bb(pos, pos + size);
// We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation)
bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x) || (bb.Max.x > tab_bar->BarRect.Max.x);
if (want_clip_rect)
PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x, bb.Max.y), true);
ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos;
ItemSize(bb.GetSize(), style.FramePadding.y);
window->DC.CursorMaxPos = backup_cursor_max_pos;
if (!ItemAdd(bb, id))
{
if (want_clip_rect)
PopClipRect();
window->DC.CursorPos = backup_main_cursor_pos;
return tab_contents_visible;
}
// Click to Select a tab
ImGuiButtonFlags button_flags = (ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_AllowItemOverlap);
if (g.DragDropActive)
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
if (pressed)
tab_bar->NextSelectedTabId = id;
hovered |= (g.HoveredId == id);
// Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered)
if (!held)
SetItemAllowOverlap();
// Drag and drop: re-order tabs
if (held && !tab_appearing && IsMouseDragging(0))
{
if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable))
{
// While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x
if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x)
{
if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)
TabBarQueueChangeTabOrder(tab_bar, tab, -1);
}
else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x)
{
if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)
TabBarQueueChangeTabOrder(tab_bar, tab, +1);
}
}
}
#if 0
if (hovered && g.HoveredIdNotActiveTimer > 0.50f && bb.GetWidth() < tab->ContentWidth)
{
// Enlarge tab display when hovering
bb.Max.x = bb.Min.x + IM_FLOOR(ImLerp(bb.GetWidth(), tab->ContentWidth, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f)));
display_draw_list = GetForegroundDrawList(window);
TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive));
}
#endif
// Render tab shape
ImDrawList* display_draw_list = window->DrawList;
const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabUnfocused));
TabItemBackground(display_draw_list, bb, flags, tab_col);
RenderNavHighlight(bb, id);
// Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
if (hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)))
tab_bar->NextSelectedTabId = id;
if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
// Render tab label, process close button
const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0;
bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible);
if (just_closed && p_open != NULL)
{
*p_open = false;
TabBarCloseTab(tab_bar, tab);
}
// Restore main window position so user can draw there
if (want_clip_rect)
PopClipRect();
window->DC.CursorPos = backup_main_cursor_pos;
// Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer)
// We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar (which g.HoveredId ignores)
if (g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f && IsItemHovered())
if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip))
SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label);
return tab_contents_visible;
}
// [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed.
// To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem()
void ImGui::SetTabItemClosed(const char* label)
{
ImGuiContext& g = *GImGui;
bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode);
if (is_within_manual_tab_bar)
{
ImGuiTabBar* tab_bar = g.CurrentTabBar;
IM_ASSERT(tab_bar->WantLayout); // Needs to be called AFTER BeginTabBar() and BEFORE the first call to BeginTabItem()
ImGuiID tab_id = TabBarCalcTabID(tab_bar, label);
TabBarRemoveTab(tab_bar, tab_id);
}
}
ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button)
{
ImGuiContext& g = *GImGui;
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f);
if (has_close_button)
size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle.
else
size.x += g.Style.FramePadding.x + 1.0f;
return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y);
}
void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col)
{
// While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it.
ImGuiContext& g = *GImGui;
const float width = bb.GetWidth();
IM_UNUSED(flags);
IM_ASSERT(width > 0.0f);
const float rounding = ImMax(0.0f, ImMin(g.Style.TabRounding, width * 0.5f - 1.0f));
const float y1 = bb.Min.y + 1.0f;
const float y2 = bb.Max.y - 1.0f;
draw_list->PathLineTo(ImVec2(bb.Min.x, y2));
draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9);
draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12);
draw_list->PathLineTo(ImVec2(bb.Max.x, y2));
draw_list->PathFillConvex(col);
if (g.Style.TabBorderSize > 0.0f)
{
draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2));
draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9);
draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12);
draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2));
draw_list->PathStroke(GetColorU32(ImGuiCol_Border), false, g.Style.TabBorderSize);
}
}
// Render text label (with custom clipping) + Unsaved Document marker + Close Button logic
// We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter.
bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible)
{
ImGuiContext& g = *GImGui;
ImVec2 label_size = CalcTextSize(label, NULL, true);
if (bb.GetWidth() <= 1.0f)
return false;
// In Style V2 we'll have full override of all colors per state (e.g. focused, selected)
// But right now if you want to alter text color of tabs this is what you need to do.
#if 0
const float backup_alpha = g.Style.Alpha;
if (!is_contents_visible)
g.Style.Alpha *= 0.7f;
#endif
// Render text label (with clipping + alpha gradient) + unsaved marker
const char* TAB_UNSAVED_MARKER = "*";
ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y);
if (flags & ImGuiTabItemFlags_UnsavedDocument)
{
text_pixel_clip_bb.Max.x -= CalcTextSize(TAB_UNSAVED_MARKER, NULL, false).x;
ImVec2 unsaved_marker_pos(ImMin(bb.Min.x + frame_padding.x + label_size.x + 2, text_pixel_clip_bb.Max.x), bb.Min.y + frame_padding.y + IM_FLOOR(-g.FontSize * 0.25f));
RenderTextClippedEx(draw_list, unsaved_marker_pos, bb.Max - frame_padding, TAB_UNSAVED_MARKER, NULL, NULL);
}
ImRect text_ellipsis_clip_bb = text_pixel_clip_bb;
// Close Button
// We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap()
// 'hovered' will be true when hovering the Tab but NOT when hovering the close button
// 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button
// 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false
bool close_button_pressed = false;
bool close_button_visible = false;
if (close_button_id != 0)
if (is_contents_visible || bb.GetWidth() >= g.Style.TabMinWidthForUnselectedCloseButton)
if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id)
close_button_visible = true;
if (close_button_visible)
{
ImGuiItemHoveredDataBackup last_item_backup;
const float close_button_sz = g.FontSize;
PushStyleVar(ImGuiStyleVar_FramePadding, frame_padding);
if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x * 2.0f - close_button_sz, bb.Min.y)))
close_button_pressed = true;
PopStyleVar();
last_item_backup.Restore();
// Close with middle mouse button
if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))
close_button_pressed = true;
text_pixel_clip_bb.Max.x -= close_button_sz;
}
float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f;
RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size);
#if 0
if (!is_contents_visible)
g.Style.Alpha = backup_alpha;
#endif
return close_button_pressed;
}
//-------------------------------------------------------------------------
// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.
// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system.
//-------------------------------------------------------------------------
// - GetColumnIndex()
// - GetColumnCount()
// - GetColumnOffset()
// - GetColumnWidth()
// - SetColumnOffset()
// - SetColumnWidth()
// - PushColumnClipRect() [Internal]
// - PushColumnsBackground() [Internal]
// - PopColumnsBackground() [Internal]
// - FindOrCreateColumns() [Internal]
// - GetColumnsID() [Internal]
// - BeginColumns()
// - NextColumn()
// - EndColumns()
// - Columns()
//-------------------------------------------------------------------------
int ImGui::GetColumnIndex()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;
}
int ImGui::GetColumnsCount()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;
}
float ImGui::GetColumnOffsetFromNorm(const ImGuiColumns* columns, float offset_norm)
{
return offset_norm * (columns->OffMaxX - columns->OffMinX);
}
float ImGui::GetColumnNormFromOffset(const ImGuiColumns* columns, float offset)
{
return offset / (columns->OffMaxX - columns->OffMinX);
}
static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f;
static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index)
{
// Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
// window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x;
x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
return x;
}
float ImGui::GetColumnOffset(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns == NULL)
return 0.0f;
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const float t = columns->Columns[column_index].OffsetNorm;
const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t);
return x_offset;
}
static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool before_resize = false)
{
if (column_index < 0)
column_index = columns->Current;
float offset_norm;
if (before_resize)
offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
else
offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
return ImGui::GetColumnOffsetFromNorm(columns, offset_norm);
}
float ImGui::GetColumnWidth(int column_index)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns == NULL)
return GetContentRegionAvail().x;
if (column_index < 0)
column_index = columns->Current;
return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
}
void ImGui::SetColumnOffset(int column_index, float offset)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX);
if (preserve_width)
SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
}
void ImGui::SetColumnWidth(int column_index, float width)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
}
void ImGui::PushColumnClipRect(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (column_index < 0)
column_index = columns->Current;
ImGuiColumnData* column = &columns->Columns[column_index];
PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
}
// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)
void ImGui::PushColumnsBackground()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
return;
columns->Splitter.SetCurrentChannel(window->DrawList, 0);
int cmd_size = window->DrawList->CmdBuffer.Size;
PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false);
IM_UNUSED(cmd_size);
IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd
}
void ImGui::PopColumnsBackground()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
return;
columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
PopClipRect();
}
ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)
{
// We have few columns per window so for now we don't need bother much with turning this into a faster lookup.
for (int n = 0; n < window->ColumnsStorage.Size; n++)
if (window->ColumnsStorage[n].ID == id)
return &window->ColumnsStorage[n];
window->ColumnsStorage.push_back(ImGuiColumns());
ImGuiColumns* columns = &window->ColumnsStorage.back();
columns->ID = id;
return columns;
}
ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)
{
ImGuiWindow* window = GetCurrentWindow();
// Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
// In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
PushID(0x11223347 + (str_id ? 0 : columns_count));
ImGuiID id = window->GetID(str_id ? str_id : "columns");
PopID();
return id;
}
void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported
// Acquire storage for the columns set
ImGuiID id = GetColumnsID(str_id, columns_count);
ImGuiColumns* columns = FindOrCreateColumns(window, id);
IM_ASSERT(columns->ID == id);
columns->Current = 0;
columns->Count = columns_count;
columns->Flags = flags;
window->DC.CurrentColumns = columns;
columns->HostCursorPosY = window->DC.CursorPos.y;
columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;
columns->HostClipRect = window->ClipRect;
columns->HostWorkRect = window->WorkRect;
// Set state for first column
// We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect
const float column_padding = g.Style.ItemSpacing.x;
const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize));
const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f);
const float max_2 = window->WorkRect.Max.x + half_clip_extend_x;
columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f);
columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f);
columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
// Clear data if columns count changed
if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
columns->Columns.resize(0);
// Initialize default widths
columns->IsFirstFrame = (columns->Columns.Size == 0);
if (columns->Columns.Size == 0)
{
columns->Columns.reserve(columns_count + 1);
for (int n = 0; n < columns_count + 1; n++)
{
ImGuiColumnData column;
column.OffsetNorm = n / (float)columns_count;
columns->Columns.push_back(column);
}
}
for (int n = 0; n < columns_count; n++)
{
// Compute clipping rectangle
ImGuiColumnData* column = &columns->Columns[n];
float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n));
float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
column->ClipRect.ClipWith(window->ClipRect);
}
if (columns->Count > 1)
{
columns->Splitter.Split(window->DrawList, 1 + columns->Count);
columns->Splitter.SetCurrentChannel(window->DrawList, 1);
PushColumnClipRect(0);
}
// We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user.
float offset_0 = GetColumnOffset(columns->Current);
float offset_1 = GetColumnOffset(columns->Current + 1);
float width = offset_1 - offset_0;
PushItemWidth(width * 0.65f);
window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
}
void ImGui::NextColumn()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems || window->DC.CurrentColumns == NULL)
return;
ImGuiContext& g = *GImGui;
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
{
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
IM_ASSERT(columns->Current == 0);
return;
}
PopItemWidth();
PopClipRect();
const float column_padding = g.Style.ItemSpacing.x;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
if (++columns->Current < columns->Count)
{
// Columns 1+ ignore IndentX (by canceling it out)
// FIXME-COLUMNS: Unnecessary, could be locked?
window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding;
columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
}
else
{
// New row/line
// Column 0 honor IndentX
window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
columns->Splitter.SetCurrentChannel(window->DrawList, 1);
columns->Current = 0;
columns->LineMinY = columns->LineMaxY;
}
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->DC.CursorPos.y = columns->LineMinY;
window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = 0.0f;
PushColumnClipRect(columns->Current); // FIXME-COLUMNS: Could it be an overwrite?
// FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup.
float offset_0 = GetColumnOffset(columns->Current);
float offset_1 = GetColumnOffset(columns->Current + 1);
float width = offset_1 - offset_0;
PushItemWidth(width * 0.65f);
window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
}
void ImGui::EndColumns()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
PopItemWidth();
if (columns->Count > 1)
{
PopClipRect();
columns->Splitter.Merge(window->DrawList);
}
const ImGuiColumnsFlags flags = columns->Flags;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
window->DC.CursorPos.y = columns->LineMaxY;
if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize))
window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent
// Draw columns borders and handle resize
// The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy
bool is_being_resized = false;
if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
{
// We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.
const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);
const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);
int dragging_column = -1;
for (int n = 1; n < columns->Count; n++)
{
ImGuiColumnData* column = &columns->Columns[n];
float x = window->Pos.x + GetColumnOffset(n);
const ImGuiID column_id = columns->ID + ImGuiID(n);
const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH;
const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));
KeepAliveID(column_id);
if (IsClippedEx(column_hit_rect, column_id, false))
continue;
bool hovered = false, held = false;
if (!(flags & ImGuiColumnsFlags_NoResize))
{
ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeEW;
if (held && !(column->Flags & ImGuiColumnsFlags_NoResize))
dragging_column = n;
}
// Draw column
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
const float xi = IM_FLOOR(x);
window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col);
}
// Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
if (dragging_column != -1)
{
if (!columns->IsBeingResized)
for (int n = 0; n < columns->Count + 1; n++)
columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
columns->IsBeingResized = is_being_resized = true;
float x = GetDraggedColumnOffset(columns, dragging_column);
SetColumnOffset(dragging_column, x);
}
}
columns->IsBeingResized = is_being_resized;
window->WorkRect = columns->HostWorkRect;
window->DC.CurrentColumns = NULL;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
}
// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
void ImGui::Columns(int columns_count, const char* id, bool border)
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
//flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)
return;
if (columns != NULL)
EndColumns();
if (columns_count != 1)
BeginColumns(id, columns_count, flags);
}
//-------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE
|
[
"dylanHetherington97@gmail.com"
] |
dylanHetherington97@gmail.com
|
4e4c9c3fee8e3e6a349a8f96074733a8abb54b99
|
5d917e97f825ee26f1e133ea9ea374b277a837d9
|
/frameworks/lua-bindings/bindings/auto/lua_cocos2dx_auto.hpp
|
76e48d894e97366f97c14be01213e6fcba2b5f51
|
[
"MIT"
] |
permissive
|
xiangyuan/cocos2d-lua
|
fc233a7d64c6aa5a834cc8d45f434c0ca595edfc
|
59934c329b58740486cb3dfe9125bfcdfe12d730
|
refs/heads/master
| 2020-12-26T02:39:16.478848
| 2014-03-03T08:43:39
| 2014-03-03T08:43:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,729
|
hpp
|
#ifndef __cocos2dx_h__
#define __cocos2dx_h__
#ifdef __cplusplus
extern "C" {
#endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif
int register_all_cocos2dx(lua_State* tolua_S);
#endif // __cocos2dx_h__
|
[
"jianhua.chen@cocos2d-x.org"
] |
jianhua.chen@cocos2d-x.org
|
7b9e31d8ed8333b04b8d8068bafa38127d014a25
|
8eafb73fdab3e422aa717bac9af338dcba5e3c1e
|
/bbp/src/irikura/greenscale/saitofilt.cpp
|
fef83968fbbe625f3dbff73783e7d3c0c9bdcab8
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
LevyForchh/bbp
|
6dae4ce3577a73f5cef9b9b5507753a1381ec870
|
3cc389fb956ea14ef827af0f437ce37e8291afac
|
refs/heads/master
| 2020-06-03T05:10:35.751009
| 2019-06-11T21:38:18
| 2019-06-11T21:38:18
| 191,453,945
| 0
| 0
| null | 2019-06-11T21:38:16
| 2019-06-11T21:38:15
| null |
UTF-8
|
C++
| false
| false
| 8,092
|
cpp
|
#define PI 3.141593
#define HP 1.570796
#include <math.h>
#include "saitofilt.h"
/*
+ BUTTERWORTH LOW PASS FILTER COEFFICIENT
+
+ ARGUMENTS
+ H : FILTER COEFFICIENTS
+ M : ORDER OF FILTER (M=(N+1)/2)
+ GN : GAIN FACTOR
+ N : ORDER OF BUTTERWORTH FUNCTION
+ FP : PASS BAND FREQUENCY (NON-DIMENSIONAL)
+ FS : STOP BAND FREQUENCY
+ AP : MAX. ATTENUATION IN PASS BAND
+ AS : MIN. ATTENUATION IN STOP BAND
+
+ M. SAITO (17/XII/75)
*/
int butlop(double *h,int *m,double *gn,int *n,double fp,double fs,double ap,double as)
{
//double *h,fp,fs,ap,as,*gn;
//int *m,*n;
{
double wp,ws,tp,ts,pa,sa,cc,c,dp,g,fj,c2,sj,tj,a;
int k,j;
if(fabs(fp)<fabs(fs)) wp=fabs(fp)*PI;
else wp=fabs(fs)*PI;
if(fabs(fp)>fabs(fs)) ws=fabs(fp)*PI;
else ws=fabs(fs)*PI;
if(wp==0.0 || wp==ws || ws>=HP)
{
printf("? (butlop) invalid input : fp=%14.6e fs=%14.6e ?\n",fp,fs);
return(1);
}
/**** DETERMINE N & C */
tp=tan(wp);
ts=tan(ws);
if(fabs(ap)<fabs(as)) pa=fabs(ap);
else pa=fabs(as);
if(fabs(ap)>fabs(as)) sa=fabs(ap);
else sa=fabs(as);
if(pa==0.0) pa=0.5;
if(sa==0.0) sa=5.0;
int nn;
double ddd;
ddd = fabs(log(pa/sa)/log(tp/ts))+0.5;
nn = (int)(fabs(log(pa/sa)/log(tp/ts))+0.5);
if((*n=(int)(fabs(log(pa/sa)/log(tp/ts))+0.5))<2){
*n=2;
}
cc=exp(log(pa*sa)/(double)(*n))/(tp*ts);
c=sqrt(cc);
dp=HP/(double)(*n);
*m=(*n)/2;
k=(*m)*4;
g=fj=1.0;
c2=2.0*(1.0-c)*(1.0+c);
for(j=0;j<k;j+=4){
sj=pow(cos(dp*fj),2.0);
tj=sin(dp*fj);
fj=fj+2.0;
a=1.0/(pow(c+tj,2.0)+sj);
g=g*a;
h[j ]=2.0;
h[j+1]=1.0;
h[j+2]=c2*a;
h[j+3]=(pow(c-tj,2.0)+sj)*a;
}
/**** EXIT */
*gn=g;
if(*n%2==0) return(0);
/**** FOR ODD N */
*m=(*m)+1;
*gn=g/(1.0+c);
h[k ]=1.0;
h[k+1]=0.0;
h[k+2]=(1.0-c)/(1.0+c);
h[k+3]=0.0;
return(0);
}
}
/*
+ BUTTERWORTH HIGH PASS FILTER COEFFICIENT
+
+ ARGUMENTS
+ H : FILTER COEFFICIENTS
+ M : ORDER OF FILTER (M=(N+1)/2)
+ GN : GAIN FACTOR
+ N : ORDER OF BUTTERWORTH FUNCTION
+ FP : PASS BAND FREQUENCY (NON-DIMENSIONAL)
+ FS : STOP BAND FREQUENCY
+ AP : MAX. ATTENUATION IN PASS BAND
+ AS : MIN. ATTENUATION IN STOP BAND
+
+ M. SAITO (7/I/76)
*/
int buthip(double *h,int *m,double *gn,int *n,double fp,double fs,double ap,double as)
{
double wp,ws,tp,ts,pa,sa,cc,c,dp,g,fj,c2,sj,tj,a;
int k,j;
if(fabs(fp)>fabs(fs)) wp=fabs(fp)*PI;
else wp=fabs(fs)*PI;
if(fabs(fp)<fabs(fs)) ws=fabs(fp)*PI;
else ws=fabs(fs)*PI;
if(wp==0.0 || wp==ws || wp>=HP)
{
printf("? (buthip) invalid input : fp=%14.6e fs=%14.6e ?\n",fp,fs);
return(1);
}
/**** DETERMINE N & C */
tp=tan(wp);
ts=tan(ws);
if(fabs(ap)<fabs(as)) pa=fabs(ap);
else pa=fabs(as);
if(fabs(ap)>fabs(as)) sa=fabs(ap);
else sa=fabs(as);
if(pa==0.0) pa=0.5;
if(sa==0.0) sa=5.0;
if((*n=(int)(fabs(log(sa/pa)/log(tp/ts))+0.5))<2) *n=2;
cc=exp(log(pa*sa)/(double)(*n))*(tp*ts);
c=sqrt(cc);
dp=HP/(double)(*n);
*m=(*n)/2;
k=(*m)*4;
g=fj=1.0;
c2=(-2.0)*(1.0-c)*(1.0+c);
for(j=0;j<k;j+=4){
sj=pow(cos(dp*fj),2.0);
tj=sin(dp*fj);
fj=fj+2.0;
a=1.0/(pow(c+tj,2.0)+sj);
g=g*a;
h[j ]=(-2.0);
h[j+1]=1.0;
h[j+2]=c2*a;
h[j+3]=(pow(c-tj,2.0)+sj)*a;
}
/**** EXIT */
*gn=g;
if(*n%2==0) return(0);
/**** FOR ODD N */
*m=(*m)+1;
*gn=g/(c+1.0);
h[k ]=(-1.0);
h[k+1]=0.0;
h[k+2]=(c-1.0)/(c+1.0);
h[k+3]=0.0;
return(0);
}
/*
+ BUTTERWORTH BAND PASS FILTER COEFFICIENT
+
+ ARGUMENTS
+ H : FILTER COEFFICIENTS
+ M : ORDER OF FILTER
+ GN : GAIN FACTOR
+ N : ORDER OF BUTTERWORTH FUNCTION
+ FL : LOW FREQUENCY CUT-OFF (NON-DIMENSIONAL)
+ FH : HIGH FREQUENCY CUT-OFF
+ FS : STOP BAND FREQUENCY
+ AP : MAX. ATTENUATION IN PASS BAND
+ AS : MIN. ATTENUATION IN STOP BAND
+
+ M. SAITO (7/I/76)
*/
int butpas(double *h,int *m,double *gn,int *n,double fl,double fh,double fs,double ap,double as)
{
//double *h,fl,fh,fs,ap,as,*gn;
//int *m,*n;
double wl,wh,ws,clh,op,ww,ts,os,pa,sa,cc,c,dp,g,fj,rr,tt,
re,ri,a,wpc,wmc;
int k,l,j,i;
struct {
double r;
double c;
} oj,aa,cq,r[2];
if(fabs(fl)<fabs(fh)) wl=fabs(fl)*PI;
else wl=fabs(fh)*PI;
if(fabs(fl)>fabs(fh)) wh=fabs(fl)*PI;
else wh=fabs(fh)*PI;
ws=fabs(fs)*PI;
if(wl==0.0 || wl==wh || wh>=HP || ws==0.0 || ws>=HP ||
(ws-wl)*(ws-wh)<=0.0){
printf("? (butpas) invalid input : fl=%14.6e fh=%14.6e fs=%14.6e ?\n",
fl,fh,fs);
*m=0;
*gn=1.0;
return(1);
}
/**** DETERMINE N & C */
clh=1.0/(cos(wl)*cos(wh));
op=sin(wh-wl)*clh;
ww=tan(wl)*tan(wh);
ts=tan(ws);
os=fabs(ts-ww/ts);
if(fabs(ap)<fabs(as)) pa=fabs(ap);
else pa=fabs(as);
if(fabs(ap)>fabs(as)) sa=fabs(ap);
else sa=fabs(as);
if(pa==0.0) pa=0.5;
if(sa==0.0) sa=5.0;
if((*n=(int)(fabs(log(pa/sa)/log(op/os))+0.5))<2) *n=2;
cc=exp(log(pa*sa)/(double)(*n))/(op*os);
c=sqrt(cc);
ww=ww*cc;
dp=HP/(double)(*n);
k=(*n)/2;
*m=k*2;
l=0;
g=fj=1.0;
for(j=0;j<k;j++){
oj.r=cos(dp*fj)*0.5;
oj.c=sin(dp*fj)*0.5;
fj=fj+2.0;
aa.r=oj.r*oj.r-oj.c*oj.c+ww;
aa.c=2.0*oj.r*oj.c;
rr=sqrt(aa.r*aa.r+aa.c*aa.c);
tt=atan(aa.c/aa.r);
cq.r=sqrt(rr)*cos(tt/2.0);
cq.c=sqrt(rr)*sin(tt/2.0);
r[0].r=oj.r+cq.r;
r[0].c=oj.c+cq.c;
r[1].r=oj.r-cq.r;
r[1].c=oj.c-cq.c;
g=g*cc;
for(i=0;i<2;i++){
re=r[i].r*r[i].r;
ri=r[i].c;
a=1.0/((c+ri)*(c+ri)+re);
g=g*a;
h[l ]=0.0;
h[l+1]=(-1.0);
h[l+2]=2.0*((ri-c)*(ri+c)+re)*a;
h[l+3]=((ri-c)*(ri-c)+re)*a;
l=l+4;
}
}
/**** EXIT */
*gn=g;
if(*n==(*m)) return(0);
/**** FOR ODD N */
*m=(*m)+1;
wpc= cc *cos(wh-wl)*clh;
wmc=(-cc)*cos(wh+wl)*clh;
a=1.0/(wpc+c);
*gn=g*c*a;
h[l ]=0.0;
h[l+1]=(-1.0);
h[l+2]=2.0*wmc*a;
h[l+3]=(wpc-c)*a;
return(0);
}
/*
+ RECURSIVE FILTERING : F(Z) = (1+A*Z+AA*Z**2)/(1+B*Z+BB*Z**2)
+
+ ARGUMENTS
+ X : INPUT TIME SERIES
+ Y : OUTPUT TIME SERIES (MAY BE EQUIVALENT TO X)
+ N : LENGTH OF X & Y
+ H : FILTER COEFFICIENTS ; H(1)=A, H(2)=AA, H(3)=B, H(4)=BB
+ NML : >0 ; FOR NORMAL DIRECTION FILTERING
+ <0 ; FOR REVERSE DIRECTION FILTERING
+ uv : past data and results saved
+
+ M. SAITO (6/XII/75)
*/
int recfil(double *x,double *y,int n,double *h,int nml)
{
//int n,nml;
//double *x,*y,*h;
int i,j,jd;
double a,aa,b,bb,u1,u2,u3,v1,v2,v3;
if(n<=0){
printf("? (recfil) invalid input : n=%d ?\n",n);
return(1);
}
if(nml>=0){
j=0;
jd=1;
}else{
j=n-1;
jd=(-1);
}
a =h[0];
aa=h[1];
b =h[2];
bb=h[3];
u1 = u2 = v1 = v2 = 0.0;
/**** FILTERING */
for(i=0;i<n;i++){
u3=u2;
u2=u1;
u1=x[j];
v3=v2;
v2=v1;
v1=u1+a*u2+aa*u3-b*v2-bb*v3;
y[j]=v1;
j+=jd;
}
return(0);
}
/*
+ RECURSIVE FILTERING IN SERIES
+
+ ARGUMENTS
+ X : INPUT TIME SERIES
+ Y : OUTPUT TIME SERIES (MAY BE EQUIVALENT TO X)
+ N : LENGTH OF X & Y
+ H : COEFFICIENTS OF FILTER
+ M : ORDER OF FILTER
+ NML : >0 ; FOR NORMAL DIRECTION FILTERING
+ <0 ; REVERSE DIRECTION FILTERING
+ uv : past data and results saved
+
+ SUBROUTINE REQUIRED : RECFIL
+
+ M. SAITO (6/XII/75)
*/
int tandem(double *x,double *y,int n,double *h,int m,int nml)
{
//double *x,*y,*h;
//int n,m,nml;
int i;
if(n<=0 || m<=0){
printf("? (tandem) invalid input : n=%d m=%d ?\n",n,m);
return(1);
}
/**** 1-ST CALL */
recfil(x,y,n,h,nml);
/**** 2-ND AND AFTER */
if(m>1){
for(i=1;i<m;i++){
recfil(y,y,n,&h[i*4],nml);
}
}
return(0);
}
|
[
"fsilva@usc.edu"
] |
fsilva@usc.edu
|
5729a8aa2d71f43fc1891c32b16998a700694d7e
|
bd18ae73e6a97f15929d2eeebfed34cb003e4742
|
/Source/ImsvGraphVis/IGVLog.cpp
|
999e0479b3940711704b60ce486ef139d0ddefb5
|
[
"BSD-3-Clause"
] |
permissive
|
kwonoh/ImsvGraphVis
|
d7faada6b63c40b20ce3962a46804d5f3e2673b8
|
a97397818d7d8c6be4d8ea67882ac61093f52fc0
|
refs/heads/master
| 2022-05-26T23:34:27.332066
| 2022-03-24T02:46:39
| 2022-03-24T02:46:39
| 102,439,015
| 23
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 50
|
cpp
|
#include "IGVLog.h"
DEFINE_LOG_CATEGORY(LogIGV);
|
[
"kwonoh@me.com"
] |
kwonoh@me.com
|
648326531ab4b2366b9b6227b713c5bb0a7b7ceb
|
718ef298b4f5983ba5623753d3d63dc56c95ca66
|
/iOS/Classes/Native/UnityClassRegistration.cpp
|
f9d3d0b5f7edb12737d5305229b5bf1fc65b94da
|
[] |
no_license
|
aditya4812/ZIROInvasion
|
fab2116a4b46312146ba751fab8bdb171d1f936b
|
f10b7f8625c94d6640342d16c273c0345fd0761a
|
refs/heads/master
| 2020-12-20T23:23:52.659556
| 2020-05-06T02:21:04
| 2020-05-06T02:21:04
| 236,237,117
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 130
|
cpp
|
version https://git-lfs.github.com/spec/v1
oid sha256:953bf89a0206ba57d260e18ef86af892a1a6955c1fbe0ede4d0b59a475672e0e
size 16621
|
[
"a7mehta@ucsd.edu"
] |
a7mehta@ucsd.edu
|
ea8b73956a85463edb3d4fcf1eb398ea8b7cc3da
|
4354173cc824119dc4922ebc8157befe188b05e0
|
/Cache.h
|
bb52a610bcd9ba38fdc3415f0a3ca9d4e6376bfd
|
[
"MIT"
] |
permissive
|
Tarferi/youtubedownloader
|
9d5c182179e26ee43a8a0339e714eeb39f013a33
|
70c46a33787b93265254f932cf1c73963716ec28
|
refs/heads/master
| 2020-09-10T05:17:46.804973
| 2019-11-14T15:09:10
| 2019-11-14T15:09:10
| 221,657,954
| 18
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 425
|
h
|
#pragma once
#include "common.h"
class Cache {
public:
static const unsigned int CACHE_CHECKSUM_LEN = 48;
bool isValid = false;
Cache(char* path, size_t maxSize);
virtual ~Cache();
ReadBuffer* get(char* checksum);
bool put(char* checksum, char* data, unsigned int dataLength);
private:
void ensureSize();
FILE* fileHandle = nullptr;
char* path = nullptr;
size_t maxCache;
};
|
[
"Tom@DESKTOP-OKDR18E"
] |
Tom@DESKTOP-OKDR18E
|
0da996a5d98940184e06351c5fff0c9965aa8367
|
a8e8c56272c284b69f4e0204fa01da8fa7b33703
|
/GarageControlSlave/GarageControlSlave.ino
|
ccf93c3641766b180b48ab8a18678f9e05dc0e6c
|
[] |
no_license
|
stejsoftware/GarageControlFirmware
|
ef0c07e41ba3ed1f5c1da3e5b89305d8479f03da
|
9469a6bfa1e8fcfd5491312209f8852c70098b73
|
refs/heads/master
| 2020-02-26T14:05:12.794254
| 2016-11-20T15:52:02
| 2016-11-20T15:52:02
| 19,815,982
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,575
|
ino
|
#include <DHT.h>
#include <CmdMessenger.h>
#include <GarageControl.h>
#include <Timer.h>
#include <LED.h>
#include <Button.h>
#include <Relay.h>
// door status
Button door_open(11, false);
Button door_closed(10, false);
Timer door_timer;
DS door_status = DS_Unknown;
// relay variables
Relay relay(9);
// temp variables
DHT sensor(2, DHT22);
Timer temp_timer;
float temperature = 0.0;
float humidity = 0.0;
// button vars
Button button(12, false);
LED button_led(5);
CmdMessenger cmd(Serial);
LED green(13);
Timer led_timer;
void push_button()
{
relay.flash();
}
void OnPushButton()
{
cmd.sendCmd(GC_Acknowledge, "OnPushButton");
push_button();
}
void OnCloseDoor()
{
if( door_status == DS_Open )
{
push_button();
cmd.sendCmd(GC_Acknowledge, "OnCloseDoor");
}
else
{
cmd.sendCmd(GC_Error, "OnCloseDoor: Door is not open.");
}
}
void OnOpenDoor()
{
if( door_status == DS_Closed )
{
push_button();
cmd.sendCmd(GC_Acknowledge, "OnOpenDoor");
}
else
{
cmd.sendCmd(GC_Error, "OnOpenDoor: Door is not closed.");
}
}
void OnGetTemperature()
{
cmd.sendCmdStart(GC_Temperature);
cmd.sendCmdArg(sensor.convertCtoF(temperature));
cmd.sendCmdArg(humidity);
cmd.sendCmdEnd();
green.flash();
}
void read_sensor()
{
float temp = sensor.readTemperature();
float humd = sensor.readHumidity();
// if we didn't get numbers then there is an error
if( !isnan(temp) && !isnan(humd) )
{
// if either the temp or humid changes
if( (temp != temperature) || (humd != humidity) )
{
// store the new values
temperature = temp;
humidity = humd;
// report the values
OnGetTemperature();
}
}
else
{
cmd.sendCmd(GC_Error, "Couldn't read the Sensor.");
}
}
void get_door_status()
{
DS was = door_status;
if( door_open.closed() )
{
door_status = DS_Open;
button_led.on();
}
else
if( door_closed.closed() )
{
door_status = DS_Closed;
button_led.off();
}
else
{
/* if( door_status == DS_Open )
{
door_status = DS_Closing;
}
else
if( door_status == DS_Closed )
{
door_status = DS_Opening;
}
*/
}
if( door_status != was )
{
door_timer.start(100);
}
}
void OnGetDoorStatus()
{
cmd.sendCmd(GC_DoorStatus, door_status);
green.flash();
}
// Setup function
void setup()
{
// Listen on serial connection for messages from the master
Serial.begin(9600);
// start sensor
sensor.begin();
// Adds newline to every command
cmd.printLfCr();
// cmd.attach(GC_PushButton, &OnPushButton);
cmd.attach(GC_CloseDoor, &OnCloseDoor);
cmd.attach(GC_OpenDoor, &OnOpenDoor);
cmd.attach(GC_GetTemperature, &OnGetTemperature);
cmd.attach(GC_GetDoorStatus, &OnGetDoorStatus);
// cmd.attach(GC_SetDoorInterval, &OnSetDoorInterval);
temp_timer.interval(10000); // 10 sec
led_timer.interval(30);
cmd.sendCmd(GC_Acknowledge, "Garage Control Slave Started!");
}
// Loop function
void loop()
{
// process serial commands
cmd.feedinSerialData();
if( temp_timer.isTime() )
{
// read the sensor and report if changes
read_sensor();
}
// check the button
if( button.closed() )
{
button_led.flash();
OnPushButton();
}
// update the status of the door
get_door_status();
if( door_timer.isTime() )
{
// report the door status
OnGetDoorStatus();
}
if( led_timer.isTime() )
{
button_led.display();
green.display();
relay.run();
}
}
|
[
"jon@stejsoftware.com"
] |
jon@stejsoftware.com
|
4a5f0352f38f1245c786415369af32dd6c4b608b
|
c140db9d127803a03199db78ff5507b503b316fb
|
/cpp/includes/cloud/asio_handler/asio_handler.cpp
|
184bd9853dc2e44712a003447d9702ccaca437e5
|
[
"Apache-2.0"
] |
permissive
|
shangma/rapp-api
|
dedaf7ed140549568f1e83306b039ae81482a4ae
|
e842401e1a83754a51874b996646355e627a9b18
|
refs/heads/master
| 2021-01-23T08:11:23.688892
| 2016-07-01T12:29:01
| 2016-07-01T12:29:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,962
|
cpp
|
#include "asio_handler.hpp"
namespace rapp {
namespace cloud {
void asio_handler::error_handler(const boost::system::error_code & error)
{
std::cerr << "error: " << error.message() << std::endl;
}
void asio_handler::invalid_request(const std::string message)
{
std::cerr << "invalid http request: " << message << std::endl;
}
void asio_handler::content_length(std::string response, std::size_t & length)
{
static const boost::regex reg("Content-Length:\\s[-0-9]+",
boost::regex::icase);
boost::match_results<std::string::const_iterator> results;
// search for matching regex
if (boost::regex_search(response, results, reg)) {
if (results.size() > 0) {
std::string key = results[0];
key.erase(std::remove(key.begin(),
key.end(), '\n'),
key.end());
// find the `: `
std::string hay = ": ";
std::size_t i = key.find(hay);
if (i != std::string::npos) {
length = boost::lexical_cast<std::size_t>(
key.substr(i+hay.size(), std::string::npos));
}
else {
std::cerr << "malformed `Content-Lengtht` delimiter" << std::endl;
}
}
}
}
bool asio_handler::has_content_length(std::string response)
{
static const boost::regex reg("Content-Length:\\s[-0-9]+", boost::regex::icase);
boost::match_results<std::string::const_iterator> results;
// search for matching regex
if (boost::regex_search(response, results, reg)) {
return (results.size() > 0 ? true : false);
}
else {
return false;
}
}
std::string asio_handler::strip_header(std::string response)
{
// find the "\r\n\r\n" double return after the header
std::size_t i = response.find("\r\n\r\n");
if (i != std::string::npos) {
return response.substr(i+4, std::string::npos);
}
else {
throw std::runtime_error("no double return after header");
}
}
std::string asio_handler::random_boundary() const
{
std::string chars("abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"1234567890");
boost::random::random_device rng;
std::string uid;
// Randomly chose 16 characters
boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1);
for (int i = 0; i < 16; ++i){
uid.push_back(chars[index_dist(rng)]);
}
return uid;
}
std::string asio_handler::escape_string(const std::string & str)
{
std::ostringstream ss;
for (auto iter = str.cbegin(); iter != str.cend(); iter++) {
switch (*iter) {
case '\\': ss << "\\\\"; break;
case '"': ss << "\\\""; break;
case '/': ss << "\\/"; break;
case '\b': ss << "\\b"; break;
case '\f': ss << "\\f"; break;
case '\n': ss << "\\n"; break;
case '\r': ss << "\\r"; break;
case '\t': ss << "\\t"; break;
default: ss << *iter; break;
}
}
return ss.str();
}
std::string asio_handler::decode64(const std::string &val)
{
using namespace boost::archive::iterators;
using It = transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>;
return boost::algorithm::trim_right_copy_if(std::string(It(std::begin(val)),
It(std::end(val))),
[](char c) {return c == '\0';});
}
std::string asio_handler::encode64(const std::string &val)
{
using namespace boost::archive::iterators;
using It = base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>;
auto tmp = std::string(It(std::begin(val)), It(std::end(val)));
return tmp.append((3 - val.size() % 3) % 3, '=');
}
}
}
|
[
"klpanagi@gmail.com"
] |
klpanagi@gmail.com
|
43e25408894b875c8a8b0c2d59d44858fa9f971b
|
51f4106e2a42bf3c9794b85ccb1f103870c4643a
|
/common/src/physics2/BoundingBox3D.h
|
55d20ba707baffd30bb70fd0c21c21885180bac6
|
[] |
no_license
|
expokorea/korea
|
7eaf84e62ef0dbe63cddd6a6c590e85d78633c24
|
d88d3206e66845ee72eda91b72963f43e591045d
|
refs/heads/master
| 2021-01-01T19:15:34.462778
| 2012-04-14T15:16:08
| 2012-04-14T15:16:08
| 3,376,639
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,998
|
h
|
#pragma once
#include "ofMesh.h"
#include "ofGraphics.h"
//----------------------------------------
static void ofBox(ofVec3f size){
static ofMesh vertexData;
ofPushMatrix();
if(ofGetCoordHandedness() == OF_LEFT_HANDED){
ofScale(1, 1, -1);
}
float w = size.x * .5;
float h = size.y * .5;
float d = size.z * .5;
vertexData.clear();
if(ofGetStyle().bFill){
ofVec3f vertices[] = {
ofVec3f(+w,-h,+d), ofVec3f(+w,-h,-d), ofVec3f(+w,+h,-d), ofVec3f(+w,+h,+d),
ofVec3f(+w,+h,+d), ofVec3f(+w,+h,-d), ofVec3f(-w,+h,-d), ofVec3f(-w,+h,+d),
ofVec3f(+w,+h,+d), ofVec3f(-w,+h,+d), ofVec3f(-w,-h,+d), ofVec3f(+w,-h,+d),
ofVec3f(-w,-h,+d), ofVec3f(-w,+h,+d), ofVec3f(-w,+h,-d), ofVec3f(-w,-h,-d),
ofVec3f(-w,-h,+d), ofVec3f(-w,-h,-d), ofVec3f(+w,-h,-d), ofVec3f(+w,-h,+d),
ofVec3f(-w,-h,-d), ofVec3f(-w,+h,-d), ofVec3f(+w,+h,-d), ofVec3f(+w,-h,-d)
};
vertexData.addVertices(vertices,24);
static ofVec3f normals[] = {
ofVec3f(+1,0,0), ofVec3f(+1,0,0), ofVec3f(+1,0,0), ofVec3f(+1,0,0),
ofVec3f(0,+1,0), ofVec3f(0,+1,0), ofVec3f(0,+1,0), ofVec3f(0,+1,0),
ofVec3f(0,0,+1), ofVec3f(0,0,+1), ofVec3f(0,0,+1), ofVec3f(0,0,+1),
ofVec3f(-1,0,0), ofVec3f(-1,0,0), ofVec3f(-1,0,0), ofVec3f(-1,0,0),
ofVec3f(0,-1,0), ofVec3f(0,-1,0), ofVec3f(0,-1,0), ofVec3f(0,-1,0),
ofVec3f(0,0,-1), ofVec3f(0,0,-1), ofVec3f(0,0,-1), ofVec3f(0,0,-1)
};
vertexData.addNormals(normals,24);
static ofVec2f tex[] = {
ofVec2f(1,0), ofVec2f(0,0), ofVec2f(0,1), ofVec2f(1,1),
ofVec2f(1,1), ofVec2f(1,0), ofVec2f(0,0), ofVec2f(0,1),
ofVec2f(0,1), ofVec2f(1,1), ofVec2f(1,0), ofVec2f(0,0),
ofVec2f(0,0), ofVec2f(0,1), ofVec2f(1,1), ofVec2f(1,0),
ofVec2f(0,0), ofVec2f(0,1), ofVec2f(1,1), ofVec2f(1,0),
ofVec2f(0,0), ofVec2f(0,1), ofVec2f(1,1), ofVec2f(1,0)
};
vertexData.addTexCoords(tex,24);
static ofIndexType indices[] = {
0,1,2, // right top left
0,2,3, // right bottom right
4,5,6, // bottom top right
4,6,7, // bottom bottom left
8,9,10, // back bottom right
8,10,11, // back top left
12,13,14, // left bottom right
12,14,15, // left top left
16,17,18, // ... etc
16,18,19,
20,21,22,
20,22,23
};
vertexData.addIndices(indices,36);
vertexData.setMode(OF_PRIMITIVE_TRIANGLES);
ofGetCurrentRenderer()->draw(vertexData,vertexData.usingColors(),vertexData.usingTextures(),vertexData.usingNormals());
} else {
ofVec3f vertices[] = {
ofVec3f(+w,+h,+d),
ofVec3f(+w,+h,-d),
ofVec3f(+w,-h,+d),
ofVec3f(+w,-h,-d),
ofVec3f(-w,+h,+d),
ofVec3f(-w,+h,-d),
ofVec3f(-w,-h,+d),
ofVec3f(-w,-h,-d)
};
vertexData.addVertices(vertices,8);
static float n = sqrtf(3);
static ofVec3f normals[] = {
ofVec3f(+n,+n,+n),
ofVec3f(+n,+n,-n),
ofVec3f(+n,-n,+n),
ofVec3f(+n,-n,-n),
ofVec3f(-n,+n,+n),
ofVec3f(-n,+n,-n),
ofVec3f(-n,-n,+n),
ofVec3f(-n,-n,-n)
};
vertexData.addNormals(normals,8);
static ofIndexType indices[] = {
0,1, 1,3, 3,2, 2,0,
4,5, 5,7, 7,6, 6,4,
0,4, 5,1, 7,3, 6,2
};
vertexData.addIndices(indices,24);
vertexData.setMode(OF_PRIMITIVE_LINES);
ofGetCurrentRenderer()->draw(vertexData, vertexData.usingColors(),vertexData.usingTextures(),vertexData.usingNormals());
}
ofPopMatrix();
}
//----------------------------------------
static void ofBox(const ofPoint& position, float w, float h, float d){
static ofMesh vertexData;
ofPushMatrix();
ofTranslate(position);
ofBox(ofVec3f(w,h,d));
ofPopMatrix();
}
class BoundingBox3D{
public:
BoundingBox3D()
:x(0)
,y(0)
,z(0)
,width(0)
,height(0)
,depth(0){}
BoundingBox3D(float x, float y, float z, float w, float h, float d)
:x(x)
,y(y)
,z(z)
,width(w)
,height(h)
,depth(d){}
bool inside(const ofPoint & p) const{
return p.x > x && p.x < x + width &&
p.y > y && p.y < y + height &&
p.z > z && p.z < z + depth;
}
float x,y,z;
float width, height, depth;
void draw(){
ofBox(ofVec3f(x+width*.5,y+height*.5,z+depth*.5),width,height,depth);
}
};
|
[
"arturo@openframeworks.cc"
] |
arturo@openframeworks.cc
|
1665b06774a0a4fd88be778c3743372785fc1542
|
f88777eea48fa72d26518325d99e2fa022895c70
|
/aoj/grl-4-b_topological-sort.cpp
|
cda196ee30be3d6e190878b3466ed13471756a38
|
[] |
no_license
|
komukomo/competitive-programming
|
c0797e138c592121223676030f81e765b893f378
|
5c7e9462b0e5035c3a8a27007c4bcdfd55bf390c
|
refs/heads/master
| 2021-01-18T15:37:07.313730
| 2017-03-30T05:22:37
| 2017-03-30T05:22:37
| 86,662,843
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 827
|
cpp
|
#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
static const int MAX = 10000;
vector<int> G[MAX];
int indegs[MAX];
bool visited[MAX];
void visit(int x) {
cout << x << endl;
visited[x] = true;
}
void bfs(int start) {
queue<int> q;
q.push(start);
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto t : G[u]) {
indegs[t]--;
if (indegs[t] == 0 && !visited[t])
q.push(t);
}
visit(u);
}
}
int main() {
int nv, ne;
cin >> nv >> ne;
for (int i = 0; i < nv; i++) {
indegs[i] = 0;
visited[i] = false;
}
for (int i = 0; i < ne; i++) {
int s, t;
cin >> s >> t;
G[s].push_back(t);
indegs[t]++;
}
for (int i = 0; i < nv; i++) {
if (indegs[i] == 0 && !visited[i])
bfs(i);
}
}
|
[
"komukomo@users.noreply.github.com"
] |
komukomo@users.noreply.github.com
|
f1484cd016c1c1d5222ecfa7bd700f4ce39f47ae
|
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
|
/Engine/Code/Mathematics/Intersection/Intersection2D/StaticFindIntersectorSegment2Arc2.cpp
|
3e3028aa786c396ce154a22b51f3edb5a2f25e29
|
[
"BSD-3-Clause"
] |
permissive
|
WuyangPeng/Engine
|
d5d81fd4ec18795679ce99552ab9809f3b205409
|
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
|
refs/heads/master
| 2023-08-17T17:01:41.765963
| 2023-08-16T07:27:05
| 2023-08-16T07:27:05
| 246,266,843
| 10
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 942
|
cpp
|
/// Copyright (c) 2010-2023
/// Threading Core Render Engine
///
/// 作者:彭武阳,彭晔恩,彭晔泽
/// 联系作者:94458936@qq.com
///
/// 标准:std:c++20
/// 引擎版本:0.9.0.11 (2023/06/08 19:23)
#include "Mathematics/MathematicsExport.h"
#ifdef MATHEMATICS_EXPORT_TEMPLATE
#ifndef MATHEMATICS_INCLUDED_STATIC_FIND_INTERSECTOR_SEGMENT2_ARC2_ACHIEVE
#define MATHEMATICS_INCLUDED_STATIC_FIND_INTERSECTOR_SEGMENT2_ARC2_ACHIEVE
#endif // MATHEMATICS_INCLUDED_STATIC_FIND_INTERSECTOR_SEGMENT2_ARC2_ACHIEVE
#endif // MATHEMATICS_EXPORT_TEMPLATE
#include "StaticFindIntersectorSegment2Arc2Detail.h"
#ifdef MATHEMATICS_EXPORT_TEMPLATE
namespace Mathematics
{
template MATHEMATICS_TEMPLATE_DEFAULT_DECLARE class StaticFindIntersectorSegment2Arc2<float>;
template MATHEMATICS_TEMPLATE_DEFAULT_DECLARE class StaticFindIntersectorSegment2Arc2<double>;
}
#endif // MATHEMATICS_EXPORT_TEMPLATE
|
[
"94458936@qq.com"
] |
94458936@qq.com
|
9a05a0e0f6dae4b45145c6d9b0d7f84dbddbb2e7
|
df8cbdbf75e4bf08ddda9fdcc3b2999e98dfc539
|
/SU2016/C++/Play/LeetCodeQuestions/LeetCodeQuestions/MajorityElementII229.hpp
|
5c0ffb254164fab419c39e3a70beac625cd49cbf
|
[] |
no_license
|
SiyangJ/Courses
|
a1a0f3d24002d6f755db2d14a9eb4968e132e524
|
b95588c80d25f34f43002af1bd9a3234f7f8bc9b
|
refs/heads/master
| 2020-03-22T17:18:13.351510
| 2019-01-22T15:11:33
| 2019-01-22T15:11:33
| 140,386,976
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 945
|
hpp
|
//
// MajorityElementII229.hpp
// LeetCodeQuestions
//
// Created by apple on 10/26/17.
// Copyright © 2017 UNC. All rights reserved.
//
#ifndef MajorityElementII229_hpp
#define MajorityElementII229_hpp
#include <stdio.h>
#include <vector>
using namespace std;
class MajorityElementII229 {
public:
// Linear time and constant space
vector<int> majorityElement(vector<int> &a) {
int y = 0, z = 1, cy = 0, cz = 0;
for (auto x: a) {
if (x == y) cy++;
else if (x == z) cz++;
else if (! cy) y = x, cy = 1;
else if (! cz) z = x, cz = 1;
else cy--, cz--;
}
cy = cz = 0;
for (auto x: a)
if (x == y) cy++;
else if (x == z) cz++;
vector<int> r;
if (cy > a.size()/3) r.push_back(y);
if (cz > a.size()/3) r.push_back(z);
return r;
}
};
#endif /* MajorityElementII229_hpp */
|
[
"siyangj@live.unc.edu"
] |
siyangj@live.unc.edu
|
c0e8919457ec80760743a5beb7221e7c98dc5c66
|
fe106df825705a090f321967a38f9901bf31a4a9
|
/cpp/wejscie-wyjscie.cpp
|
2c4a6ed8c5a073b13e3dbc520d97f7f22d445fac
|
[] |
no_license
|
Piter98/gittest
|
1388dcea43821b2e345d53175854e7f689c4a4fd
|
61a561e73d5033226948a9ab763cee3179942013
|
refs/heads/master
| 2021-01-20T15:18:52.677693
| 2017-04-12T11:39:55
| 2017-04-12T11:39:55
| 82,804,716
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 545
|
cpp
|
/*
* wejscie-wyjscie.cpp
*
* Copyright 2017 user <user@lap79>
*
*/
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <math.h>
using namespace std;
int main(int argc, char **argv)
{
int lint = 0;
cout << "Podaj liczbę całkowitą: ";
cin >> lint;
cout.setf(ios_base::hex, ios_base::basefield);
cout.setf(ios_base::showbase);
cout << "Hex: " << lint <<endl;
cout.setf(ios_base::oct, ios_base::basefield);
cout.setf(ios_base::showbase);
cout << "Oct: " << lint <<endl;
return 0;
}
|
[
"piotr.pal98@gmail.com"
] |
piotr.pal98@gmail.com
|
a84d354a42e585c6fa4dbc582da1963e4447fc2e
|
c18e3cba4f445613b2ed7503061cdfe088d46da5
|
/docs/parallel/concrt/codesnippet/CPP/asynchronous-agents-library_1.cpp
|
e0b433c368b08532024cc43d4a608f225f0076cb
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
MicrosoftDocs/cpp-docs
|
dad03e548e13ca6a6e978df3ba84c4858c77d4bd
|
87bacc85d5a1e9118a69122d84c43d70f6893f72
|
refs/heads/main
| 2023-09-01T00:19:22.423787
| 2023-08-28T17:27:40
| 2023-08-28T17:27:40
| 73,740,405
| 1,354
| 1,213
|
CC-BY-4.0
| 2023-09-08T21:27:46
| 2016-11-14T19:38:32
|
PowerShell
|
UTF-8
|
C++
| false
| false
| 2,490
|
cpp
|
// basic-agents.cpp
// compile with: /EHsc
#include <agents.h>
#include <string>
#include <iostream>
#include <sstream>
using namespace concurrency;
using namespace std;
// This agent writes a string to its target and reads an integer
// from its source.
class agent1 : public agent
{
public:
explicit agent1(ISource<int>& source, ITarget<wstring>& target)
: _source(source)
, _target(target)
{
}
protected:
void run()
{
// Send the request.
wstringstream ss;
ss << L"agent1: sending request..." << endl;
wcout << ss.str();
send(_target, wstring(L"request"));
// Read the response.
int response = receive(_source);
ss = wstringstream();
ss << L"agent1: received '" << response << L"'." << endl;
wcout << ss.str();
// Move the agent to the finished state.
done();
}
private:
ISource<int>& _source;
ITarget<wstring>& _target;
};
// This agent reads a string to its source and then writes an integer
// to its target.
class agent2 : public agent
{
public:
explicit agent2(ISource<wstring>& source, ITarget<int>& target)
: _source(source)
, _target(target)
{
}
protected:
void run()
{
// Read the request.
wstring request = receive(_source);
wstringstream ss;
ss << L"agent2: received '" << request << L"'." << endl;
wcout << ss.str();
// Send the response.
ss = wstringstream();
ss << L"agent2: sending response..." << endl;
wcout << ss.str();
send(_target, 42);
// Move the agent to the finished state.
done();
}
private:
ISource<wstring>& _source;
ITarget<int>& _target;
};
int wmain()
{
// Step 1: Create two message buffers to serve as communication channels
// between the agents.
// The first agent writes messages to this buffer; the second
// agents reads messages from this buffer.
unbounded_buffer<wstring> buffer1;
// The first agent reads messages from this buffer; the second
// agents writes messages to this buffer.
overwrite_buffer<int> buffer2;
// Step 2: Create the agents.
agent1 first_agent(buffer2, buffer1);
agent2 second_agent(buffer1, buffer2);
// Step 3: Start the agents. The runtime calls the run method on
// each agent.
first_agent.start();
second_agent.start();
// Step 4: Wait for both agents to finish.
agent::wait(&first_agent);
agent::wait(&second_agent);
}
|
[
"v-zhecai@microsoft.com"
] |
v-zhecai@microsoft.com
|
bf0fe243336130c1f6633cc4a6aeb5057d993766
|
7f84adc638f0b43442ebcbfa562597fc24cad186
|
/Graph/Connected_Components.cpp
|
068be9262ea1e11eff5dd0c2365cc63ab5fc717f
|
[] |
no_license
|
okoge-kaz/cpp-library
|
c122338e02e63346d83b4e689f8791b85ef9da64
|
afdae5ee94b101e1f4b7793f8046652b2e1090e6
|
refs/heads/main
| 2023-08-24T09:52:15.789845
| 2021-09-18T09:02:00
| 2021-09-18T09:02:00
| 405,311,262
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,901
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const long long INF = 1LL << 60;
const int inf = (1 << 30);
const ll mod = 998244353;
const ll MOD = 1000000007;
const ld PI = acos(-1.0L);
int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1};
int dy8[] = {1, 1, 0, -1, -1, -1, 0, 1}, dx8[] = {0, -1, -1, -1, 0, 1, 1, 1};
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
using lll = __int128_t;
// Connected-Components 連結成分(分解)
// verified https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_11_D
class ConnectedComponents {
private:
vector<vector<int>>G;
vector<int>cc;// connected components
vector<bool>used;
void dfs(int v, int cnt){
if(used[v]) return;
used[v] = true;
cc[v] = cnt;
for(int nv:G[v]) dfs(nv,cnt);
}
public:
ConnectedComponents(const vector<vector<int>> &g){
int n = (int)g.size(); G = g;
cc.resize(n,-1); used.resize(n,false);
int id = 0;
for(int i=0;i<n;i++){
if(used[i]) continue;
dfs(i,id);
id++;
}
}
bool is_same(int u,int v){
return cc[u] == cc[v];
}
vector<int> vec(){ return cc; }// 連結成分の番号が振られたvectorを返す
};
int main(){
int n,m; cin >> n >> m;
vector<vector<int>>G(n);
for(int i=0;i<m;i++){
int s,t; cin >> s >> t;
G[s].push_back(t); G[t].push_back(s);
}
int q; cin >> q;
ConnectedComponents cc(G);
while(q-->0){
int u,v;
cin >> u >> v;
if(cc.is_same(u,v)) cout << "yes" << endl;
else cout << "no" << endl;
}
}
|
[
"kaz.tokyo.tech20@gmail.com"
] |
kaz.tokyo.tech20@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.