hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d6745d17c58f01e1db5ecffae723aa7d863d1165 | 662 | hpp | C++ | components/operators/include/ftl/operators/colours.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | 4 | 2020-12-28T15:29:15.000Z | 2021-06-27T12:37:15.000Z | components/operators/include/ftl/operators/colours.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | null | null | null | components/operators/include/ftl/operators/colours.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | 2 | 2021-01-13T05:28:39.000Z | 2021-05-04T03:37:11.000Z | #ifndef _FTL_OPERATORS_COLOURS_HPP_
#define _FTL_OPERATORS_COLOURS_HPP_
#include <ftl/operators/operator.hpp>
namespace ftl {
namespace operators {
class ColourChannels : public ftl::operators::Operator {
public:
explicit ColourChannels(ftl::operators::Graph *g, ftl::Configurable *cfg);
~ColourChannels();
inline Operator::Type type() const override { return Operator::Type::OneToOne; }
bool apply(ftl::rgbd::Frame &in, ftl::rgbd::Frame &out, cudaStream_t stream) override;
static void configuration(ftl::Configurable*) {}
private:
cv::cuda::GpuMat temp_;
cv::cuda::GpuMat rbuf_;
};
}
}
#endif // _FTL_OPERATORS_COLOURS_HPP_
| 22.827586 | 90 | 0.732628 | knicos |
d675c0f05cc5632fade00bea7c317d693f6243a2 | 1,156 | cpp | C++ | src/managers/environmentmanager.cpp | alexhuntley/GameplayFootball | 67a3c123e31384b757b1d223c53acf9f7fcb8b41 | [
"Apache-2.0"
] | 56 | 2020-07-22T22:11:06.000Z | 2022-03-09T08:11:43.000Z | src/managers/environmentmanager.cpp | alexhuntley/GameplayFootball | 67a3c123e31384b757b1d223c53acf9f7fcb8b41 | [
"Apache-2.0"
] | 9 | 2021-04-22T07:06:25.000Z | 2022-01-22T12:54:52.000Z | src/managers/environmentmanager.cpp | alexhuntley/GameplayFootball | 67a3c123e31384b757b1d223c53acf9f7fcb8b41 | [
"Apache-2.0"
] | 18 | 2020-10-15T08:11:07.000Z | 2022-03-23T14:49:46.000Z | // written by bastiaan konings schuiling 2008 - 2014
// this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important.
// i do not offer support, so don't ask. to be used for inspiration :)
#include "environmentmanager.hpp"
#include <SDL2/SDL.h>
#include <boost/thread.hpp>
namespace blunted {
template<> EnvironmentManager* Singleton<EnvironmentManager>::singleton = 0;
EnvironmentManager::EnvironmentManager() {
quit.SetData(false);
startTime = boost::posix_time::microsec_clock::local_time();
};
EnvironmentManager::~EnvironmentManager() {
};
unsigned long EnvironmentManager::GetTime_ms() {
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration msdiff = now - startTime;
return msdiff.total_milliseconds();
}
void EnvironmentManager::Pause_ms(int duration) {
boost::this_thread::sleep(boost::posix_time::milliseconds(duration));
}
void EnvironmentManager::SignalQuit() {
quit.SetData(true);
}
bool EnvironmentManager::GetQuit() {
return quit.GetData();
}
}
| 28.195122 | 132 | 0.728374 | alexhuntley |
d681b4c481a663360a6bde5e70e62c9f370957c6 | 71 | hh | C++ | extern/typed-geometry/src/typed-geometry/feature/quadric.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/typed-geometry/src/typed-geometry/feature/quadric.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/typed-geometry/src/typed-geometry/feature/quadric.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
#include <typed-geometry/functions/quadrics/quadrics.hh>
| 17.75 | 56 | 0.802817 | rovedit |
d68330f8332d8357535563a6c07cc88ccdcb925d | 1,094 | cpp | C++ | src/util.cpp | eozd/naive-bayes-text-classification | 3891b8d64a59d3f91b02ee23cb91d853adc7e7b4 | [
"Apache-2.0"
] | 2 | 2019-12-08T12:30:22.000Z | 2021-03-04T18:04:42.000Z | src/util.cpp | eozd/positional-boolean-search | 03b3a3bf4b29c02240bc620d304d9bdf0d041e5b | [
"Apache-2.0"
] | null | null | null | src/util.cpp | eozd/positional-boolean-search | 03b3a3bf4b29c02240bc620d304d9bdf0d041e5b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Esref Ozdemir
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "util.hpp"
#include <cstring>
std::vector<std::string> ir::split(std::string& str,
const std::string& delimeters) {
std::vector<std::string> result;
// find the first token
char* token = strtok(&str[0], delimeters.c_str());
while (token != nullptr) {
// end of the first token is replaced with \0 already.
result.emplace_back(token);
token = strtok(nullptr, delimeters.c_str());
}
return result;
}
| 32.176471 | 75 | 0.667276 | eozd |
d6865d54633d83c67f32ba92125a8af7c29bfb48 | 1,658 | hpp | C++ | lib/libcpp/Alat/Alat/vectorallvariables.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | lib/libcpp/Alat/Alat/vectorallvariables.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | 1 | 2019-01-31T10:59:11.000Z | 2019-01-31T10:59:11.000Z | lib/libcpp/Alat/Alat/vectorallvariables.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | #ifndef __Alat_VectorAllVariables_h
#define __Alat_VectorAllVariables_h
#include "Alat/vector.hpp"
#include "Alat/vectoronevariableinterface.hpp"
/*--------------------------------------------------------------------------*/
namespace alat
{
class StringSet;
class StringVector;
class VectorAllVariables : public alat::Vector<std::shared_ptr<alat::VectorOneVariableInterface> >
{
public:
~VectorAllVariables();
VectorAllVariables();
VectorAllVariables(int nvars);
VectorAllVariables( const VectorAllVariables& vectorallvariables);
VectorAllVariables& operator=( const VectorAllVariables& vectorallvariables);
std::string getClassName() const;
VectorAllVariables* clone() const;
const alat::VectorOneVariableInterface* get(int i) const;
alat::VectorOneVariableInterface* get(int i);
void fillzeros();
double norm() const;
double dot(const alat::VectorAllVariables* v) const;
void equal(const alat::VectorAllVariables* v);
void equal(double d);
void add(const double& d, const alat::VectorAllVariables* v);
// void scalePerVariables(const alat::Vector<alat::armavec>& scales);
// void scalePerVariablesInverse(const alat::Vector<alat::armavec>& scales);
void loadhdf5(const std::string& filename, const alat::StringVector& names);
void savehdf5(const std::string& filename, const alat::StringVector& names) const;
void save(std::ostream& os, arma::file_type datatype = arma::arma_binary) const;
};
std::ostream& operator<<(std::ostream& s, const VectorAllVariables& v);
}
/*--------------------------------------------------------------------------*/
#endif
| 36.844444 | 100 | 0.670084 | beckerrh |
d68692797d902cfeddae8fd0168be39a934a1a97 | 1,146 | hpp | C++ | Frameworks/include/Helmet/Workbench/I_Controller.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | 2 | 2018-02-07T01:19:37.000Z | 2018-02-09T14:27:48.000Z | Frameworks/include/Helmet/Workbench/I_Controller.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | null | null | null | Frameworks/include/Helmet/Workbench/I_Controller.hpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | null | null | null | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Helmet Software Framework
//
// Copyright (C) 2018 Hat Boy Software, Inc.
//
// @author Matthew Alan Gray - <mgray@hatboysoftware.com>
// @author Tony Richards - <trichards@indiezen.com>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#pragma once
#include <Helmet/Workbench/Configuration.hpp>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Helmet {
namespace Workbench {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
class HELMET_WORKBENCH_DLL_LINK I_Controller
{
/// @name Types
/// @{
public:
/// @}
/// @name I_Controller interface
/// @{
public:
/// @}
/// @name 'Structors
/// @{
protected:
I_Controller();
virtual ~I_Controller();
/// @}
}; // interface I_Controller
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Workbench
} // namespace Helmet
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| 26.651163 | 80 | 0.358639 | hatboysoftware |
d6886cc1f91b158f4a09fc12593b5889ecc6d387 | 4,414 | cpp | C++ | test/dcu/level1/doti_s_dcu_test.cpp | xupinjie/AlphaSparse | 06bf06a57f9112c2f940741841485243d8073c7c | [
"MIT"
] | 18 | 2022-02-22T15:10:18.000Z | 2022-03-29T07:54:57.000Z | test/dcu/level1/doti_s_dcu_test.cpp | xupinjie/AlphaSparse | 06bf06a57f9112c2f940741841485243d8073c7c | [
"MIT"
] | null | null | null | test/dcu/level1/doti_s_dcu_test.cpp | xupinjie/AlphaSparse | 06bf06a57f9112c2f940741841485243d8073c7c | [
"MIT"
] | 2 | 2022-02-23T09:25:57.000Z | 2022-02-25T08:01:03.000Z | /**
* @brief ict dcu mv csr test
* @author HPCRC, ICT
*/
#include <hip/hip_runtime_api.h>
#include <rocsparse.h>
#include <stdio.h>
#include <stdlib.h>
#include <iomanip>
#include <iostream>
#include <vector>
#include "rocsparse.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <alpha_spblas_dcu.h>
const char *file;
bool check;
int iter;
// sparse vector
ALPHA_INT nnz;
ALPHA_INT *alpha_x_idx;
rocsparse_int *roc_x_idx;
float *x_val, *y;
float roc_res = 1., alpha_res = 2.;
ALPHA_INT idx_n = 10000;
static void roc_doti()
{
// rocSPARSE handle
rocsparse_handle handle;
rocsparse_create_handle(&handle);
hipDeviceProp_t devProp;
int device_id = 0;
hipGetDevice(&device_id);
hipGetDeviceProperties(&devProp, device_id);
std::cout << "Device: " << devProp.name << std::endl;
// Offload data to device
rocsparse_int *dx_idx = NULL;
float *dx_val = NULL;
float *dy = NULL;
hipMalloc((void **)&dx_idx, sizeof(rocsparse_int) * idx_n);
hipMalloc((void **)&dx_val, sizeof(float) * idx_n);
hipMalloc((void **)&dy, sizeof(float) * idx_n * 20);
hipMemcpy(dx_idx, roc_x_idx, sizeof(rocsparse_int) * idx_n, hipMemcpyHostToDevice);
hipMemcpy(dx_val, x_val, sizeof(float) * idx_n, hipMemcpyHostToDevice);
hipMemcpy(dy, y, sizeof(float) * idx_n * 20, hipMemcpyHostToDevice);
// Call rocsparse csrmv
roc_call_exit(rocsparse_sdoti(handle, idx_n, dx_val, dx_idx, dy, &roc_res, rocsparse_index_base_zero),
"rocsparse_sdoti");
// Device synchronization
hipDeviceSynchronize();
// Clear up on device
hipFree(dx_val);
hipFree(dx_idx);
hipFree(dy);
rocsparse_destroy_handle(handle);
}
static void alpha_doti()
{
// rocSPARSE handle
alphasparse_dcu_handle_t handle;
init_handle(&handle);
alphasparse_dcu_get_handle(&handle);
hipDeviceProp_t devProp;
int device_id = 0;
hipGetDevice(&device_id);
hipGetDeviceProperties(&devProp, device_id);
std::cout << "Device: " << devProp.name << std::endl;
// Offload data to device
ALPHA_INT *dx_idx = NULL;
float *dx_val = NULL;
float *dy = NULL;
hipMalloc((void **)&dx_idx, sizeof(ALPHA_INT) * idx_n);
hipMalloc((void **)&dx_val, sizeof(float) * idx_n);
hipMalloc((void **)&dy, sizeof(float) * idx_n * 20);
hipMemcpy(dx_idx, roc_x_idx, sizeof(ALPHA_INT) * idx_n, hipMemcpyHostToDevice);
hipMemcpy(dx_val, x_val, sizeof(float) * idx_n, hipMemcpyHostToDevice);
hipMemcpy(dy, y, sizeof(float) * idx_n * 20, hipMemcpyHostToDevice);
// Call rocsparse csrmv
alphasparse_dcu_s_doti(handle, idx_n, dx_val, dx_idx, dy, &alpha_res, ALPHA_SPARSE_INDEX_BASE_ZERO);
// Device synchronization
hipDeviceSynchronize();
// Clear up on device
hipFree(dx_val);
hipFree(dx_idx);
hipFree(dy);
alphasparse_dcu_destory_handle(handle);
}
int main(int argc, const char *argv[])
{
// args
args_help(argc, argv);
file = args_get_data_file(argc, argv);
check = args_get_if_check(argc, argv);
iter = args_get_iter(argc, argv);
alpha_x_idx =
(ALPHA_INT *)alpha_memalign(sizeof(ALPHA_INT) * idx_n, DEFAULT_ALIGNMENT);
roc_x_idx = (rocsparse_int *)alpha_memalign(sizeof(rocsparse_int) * idx_n,
DEFAULT_ALIGNMENT);
x_val = (float *)alpha_memalign(sizeof(float) * idx_n, DEFAULT_ALIGNMENT);
y = (float *)alpha_memalign(sizeof(float) * idx_n * 20, DEFAULT_ALIGNMENT);
alpha_fill_random_s(y, 1, idx_n * 20);
alpha_fill_random_s(x_val, 1, idx_n);
for (ALPHA_INT i = 0; i < idx_n; i++) {
alpha_x_idx[i] = i * 20;
roc_x_idx[i] = i * 20;
}
alpha_doti();
// if (check) {
// roc_doti();
// bool status = fabs(alpha_res - roc_res) > 1e-2;
// if (!status) {
// fprintf(stderr, "doti_s correct, %f\n", fabs(alpha_res - roc_res));
// fprintf(stderr, "roc : %f, ict : %f\n", roc_res, alpha_res);
// } else {
// fprintf(stderr, "doti_s error\n");
// fprintf(stderr, "roc : %f, ict : %f\n", roc_res, alpha_res);
// }
// }
printf("\n");
alpha_free(x_val);
alpha_free(roc_x_idx);
alpha_free(alpha_x_idx);
return 0;
}
#ifdef __cplusplus
}
#endif /*__cplusplus */
| 26.914634 | 106 | 0.636611 | xupinjie |
d688795b75dc64a87474c253347cbc49913b68cd | 258 | cpp | C++ | src/game/server/entities/spawns/gunbotspawn.cpp | theovier/TW-TimeRun | 87afef60d018ba748fbe2339ec1ce74c16d41679 | [
"Zlib"
] | 2 | 2018-08-24T08:54:22.000Z | 2019-01-07T09:05:22.000Z | src/game/server/entities/spawns/gunbotspawn.cpp | theovier/TW-TimeRun | 87afef60d018ba748fbe2339ec1ce74c16d41679 | [
"Zlib"
] | 1 | 2018-08-18T10:13:37.000Z | 2018-08-19T09:42:40.000Z | src/game/server/entities/spawns/gunbotspawn.cpp | theovier/TW-TimeRun | 87afef60d018ba748fbe2339ec1ce74c16d41679 | [
"Zlib"
] | 1 | 2021-12-26T03:52:09.000Z | 2021-12-26T03:52:09.000Z | #include "gunbotspawn.h"
CGunBotSpawn::CGunBotSpawn(CGameWorld *pGameWorld, vec2 Pos, CGameControllerTimeRun *pController) : CBotSpawn(pGameWorld, Pos, pController) {
m_BotType = BOTTYPE_GUN;
m_RespawnTimer = GameServer()->Tuning()->m_GunBotRespawnTime;
} | 43 | 141 | 0.794574 | theovier |
d68aad3695242540de0ebb362edf43045a21f280 | 1,959 | cpp | C++ | Mrf_DS18B20.cpp | RodNewHampshire/MRF101-150W-HF-Broadband-Amplifier | 769ac0ea2b5d09ef193aa78ef23563b83cec6d2d | [
"MIT"
] | 3 | 2021-08-15T17:40:53.000Z | 2022-01-20T14:45:33.000Z | Mrf_DS18B20.cpp | RodNewHampshire/MRF101-150W-HF-Broadband-Amplifier | 769ac0ea2b5d09ef193aa78ef23563b83cec6d2d | [
"MIT"
] | null | null | null | Mrf_DS18B20.cpp | RodNewHampshire/MRF101-150W-HF-Broadband-Amplifier | 769ac0ea2b5d09ef193aa78ef23563b83cec6d2d | [
"MIT"
] | null | null | null | /******************************************************************************
*
* MRF101 Amplifier by AD5GH
*
* ARDUINO MEGA DISPLAY & CONTROL BOARD SOFTWARE
* DS18B20+ ONE WIRE TEMPERATURE SENSOR FUNCTION ROUTINES
*
* Distributed under the terms of the MIT License:
* http://www.opensource.org/licenses/mit-license
*
* See http://www.ad5gh.com for further details
*
* VERSION 1.4.0
* June 4, 2021
*
******************************************************************************/
#include <OneWire.h>
#include <Mrf_DS18B20.h>
Mrf_DS18B20::Mrf_DS18B20(void)
{
}
float Mrf_DS18B20::getTemp(int DS18S20_Pin) // returns the temperature from one DS18B20 in DEG C
{
OneWire ds(DS18S20_Pin); // set digital pin
byte data[12];
byte addr[8];
if ( !ds.search(addr))
{
ds.reset_search();
if( !ds.search(addr)) // try a second time if first try fails
{
ds.reset_search();
return -10;
}
}
if ( OneWire::crc8( addr, 7) != addr[7]) {
Serial.println("Invalid CRC");
return -20;
}
if ( addr[0] != 0x10 && addr[0] != 0x28) {
Serial.print("Device not recognized");
return -30;
}
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end
byte present = ds.reset();
ds.select(addr);
ds.write(0xBE); // read Scratchpad
for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
ds.reset_search();
byte MSB = data[1];
byte LSB = data[0];
float tempRead = ((MSB << 8) | LSB); // using two's compliment
float TemperatureSum = tempRead / 16;
return (TemperatureSum); // return temperature in degrees C
}
| 25.441558 | 118 | 0.48392 | RodNewHampshire |
d68d73c809ad2fafa4e1f6c4f0f4ca87255754dd | 11,173 | cpp | C++ | RFlib/src/RandomizedTree.cpp | scanavan/GestureRecognition | f0761978b8f1a85544151adb1f1e30f3a9070984 | [
"MIT"
] | 2 | 2016-11-06T15:11:23.000Z | 2017-03-09T01:00:01.000Z | RFlib/src/RandomizedTree.cpp | SRI2016/GestureRecognition | f0761978b8f1a85544151adb1f1e30f3a9070984 | [
"MIT"
] | null | null | null | RFlib/src/RandomizedTree.cpp | SRI2016/GestureRecognition | f0761978b8f1a85544151adb1f1e30f3a9070984 | [
"MIT"
] | 3 | 2016-10-26T00:41:15.000Z | 2019-05-13T13:30:16.000Z | /**
* @file $URL: svn+ssh://svn_athena/home/svnrepositories/BuildingModeling/branches/Olivier/ML/src/RandomizedTree.cpp $
* @author $Author: teboul $
* @date $Date: 2009-10-16 19:24:19 +0200 (ven., 16 oct. 2009) $
* @brief
*/
#include <string>
#include <fstream>
#include "../inc/Histogram.h"
#include "../inc/RandomizedTest.h"
#include "../inc/LeafNode.h"
#include "../inc/RandomizedTree.h"
RandomizedTree::RandomizedTree(int depth, int nbLabels, unsigned int vector_size, double minV, double maxV)
:m_depth(depth),m_nb_classes(nbLabels),m_vector_size(vector_size),m_min_value(minV),m_max_value(maxV)
{
m_test = new RandomizedTest(m_vector_size,m_min_value,m_max_value);
m_true_child = 0;
m_false_child = 0;
}
RandomizedTree::RandomizedTree(int depth, int nbLabels, const RandomizedTest& test)
:m_depth(depth),m_nb_classes(nbLabels),m_vector_size(test.getSize()),
m_min_value(test.getMinValue()),m_max_value(test.getMaxValue())
{
m_test = new RandomizedTest(test);
m_true_child = 0;
m_false_child = 0;
}
RandomizedTree::RandomizedTree(const RandomizedTree& other)
:m_depth(other.m_depth),m_nb_classes(other.m_nb_classes),
m_vector_size(other.m_vector_size),m_min_value(other.m_min_value),m_max_value(other.m_max_value),
m_id(other.m_id)
{
// copy the test
m_test = new RandomizedTest(*other.m_test);
// copy the subtrees
m_true_child = 0;
if(other.m_true_child)
{
if(! other.m_true_child->isLeaf()) m_true_child = new RandomizedTree(*other.m_true_child);
else m_true_child = new LeafNode(*dynamic_cast<LeafNode*>(other.m_true_child));
}
m_false_child=0;
if(other.m_false_child)
{
if(! other.m_false_child->isLeaf()) m_false_child = new RandomizedTree(*other.m_false_child);
else m_false_child = new LeafNode(*dynamic_cast<LeafNode*>(other.m_false_child));
}
}
void
RandomizedTree::copy(RandomizedTree* other)
{
m_depth = other->m_depth;
m_nb_classes = other->m_nb_classes;
m_vector_size = other->m_vector_size;
m_min_value = other->m_min_value;
m_max_value = other->m_max_value;
*m_test = *other->m_test;
m_id = other->m_id;
// first delete the subtrees if they exists
if(m_true_child)
{
delete m_true_child;
m_true_child = 0;
}
if(m_false_child)
{
delete m_false_child;
m_false_child = 0;
}
// rebuild the children according to the other tree
if(other->m_true_child)
{
if(! other->m_true_child->isLeaf())
{
m_true_child = new RandomizedTree(m_depth-1,m_nb_classes,m_vector_size,m_min_value,m_max_value);
}
else
{
m_true_child = new LeafNode(m_nb_classes);
}
m_true_child->copy(other->m_true_child);
}
if(other->m_false_child)
{
if(! other->m_false_child->isLeaf())
{
m_false_child = new RandomizedTree(m_depth-1,m_nb_classes,m_vector_size,m_min_value,m_max_value);
}
else
{
m_false_child = new LeafNode(m_nb_classes);
}
m_false_child->copy(other->m_false_child);
}
}
RandomizedTree::~RandomizedTree()
{
delete m_test;
if(m_true_child)
{
delete m_true_child;
m_true_child = 0;
}
if(m_false_child)
{
delete m_false_child;
m_false_child = 0;
}
}
bool
RandomizedTree::isLeaf() const
{
return false;
}
void
RandomizedTree::train(const IFeatureVector& vector, int label)
{
train(vector,label,m_depth);
}
const LeafNode*
RandomizedTree::patchToLeaf(const IFeatureVector& vector) const
{
if(isLeaf()) return dynamic_cast<const LeafNode*>(this);
bool test = m_test->process(vector);
// vector goes to left child (True)
if(test)
{
if(!m_true_child)
{
//! return an outlier leaf
return NULL;
}
else
{
return m_true_child->patchToLeaf(vector);
}
}
// vector goes to right child (False)
else
{
if(!m_false_child)
{
//! return an outlier leaf
return NULL;
}
return m_false_child->patchToLeaf(vector);
}
return NULL;
}
void
RandomizedTree::train(const IFeatureVector& vector, int label, int d)
{
// apply the randomized test
bool test = m_test->process(vector);
// Patch goes to left child (True)
RandomizedTree* childtree;
if(test)
{
if(!m_true_child)
{
if(d>1) m_true_child = new RandomizedTree(d-1,m_nb_classes,m_vector_size,m_min_value,m_max_value);
else m_true_child = new LeafNode(m_nb_classes);
}
childtree = m_true_child;
}
// patch goes to right child (False)
else
{
if(!m_false_child)
{
if(d>1) m_false_child = new RandomizedTree(d-1,m_nb_classes,m_vector_size,m_min_value,m_max_value);
else m_false_child = new LeafNode(m_nb_classes);
}
childtree = m_false_child;
}
// recursive call
childtree->train(vector,label,d-1);
}
std::ostream&
operator<<(std::ostream& out, const RandomizedTree& v)
{
// turn the tree into a set of nodes and edges
std::vector<RandomizedTree*> nodes;
std::vector<t_Edge> edges;
v.compact(nodes,edges);
// dump the global caracteristics of the tree
out<<"Tree : depth "<<v.m_depth<<", "<<v.m_nb_classes<<" labels, patch size "
<<v.m_vector_size<<" "<<v.m_min_value<<" "<<v.m_max_value<<std::endl;
// dump the nodes : id, nature and features
out<<v.getNumberNodes()<<" Nodes :"<<std::endl;
for(unsigned int i = 0; i<nodes.size();i++)
{
RandomizedTree& node = *nodes[i];
if(!node.isLeaf())
{
out << node.m_id<<" S "<<*node.m_test<<std::endl;
}
else
{
out << node.m_id<<" L ";
for(int k=0; k<v.m_nb_classes; k++) out<<dynamic_cast<LeafNode&>(node)[k]<<" ";
out<<std::endl;
}
}
// dump the edges : topology and left/right
out<<"Edges :"<<std::endl;
for(unsigned int i=0; i<edges.size(); i++)
{
out<<edges[i].first.first<<" "<<edges[i].first.second<<" "<<edges[i].second<<std::endl;
}
return out;
}
std::istream&
operator>>(std::istream& in, RandomizedTree& tree)
{
std::map<int,RandomizedTree*> nodes;
std::string st;
for(int i=0; i<3; i++)
{
in>>st;
}
// get the global caracteristics of the tree
int size, depth, nbclasses;
double minV, maxV;
in>>depth>>st>>nbclasses>>st>>st>>st>>size>>minV>>maxV;
// get the number of nodes in the tree
int nbNodes;
in>>nbNodes>>st>>st;
// create the nodes
int id;
double b;
std::string s;
RandomizedTest test;
RandomizedTree* root=0;
for(int i=0; i<nbNodes; i++)
{
RandomizedTree* node;
in>>id>>s;
if(!s.compare("S"))
{
in>>test;
node = new RandomizedTree(depth,nbclasses,test);
}
else
{
node = new LeafNode(nbclasses);
for(int c = 0; c<nbclasses; c++)
{
in>>b;
(*dynamic_cast<LeafNode*>(node))[c] = b;
}
}
node->m_id = id;
nodes.insert(std::pair<int,RandomizedTree*>(id,node));
if(!root) root = node; // the root has the smallest id, it's in fact the first node to be dumped, so the first to be met here
}
// create the edges
in>>st>>st; // read "Edge :"
for(int i=0; i<nbNodes-1; i++)
{
int id1, id2, nature;
in>>id1>>id2>>nature;
RandomizedTree* node = nodes[id1];
if(nature == 1)
{
node->m_true_child = nodes[id2];
}
else
{
node->m_false_child = nodes[id2];
}
}
tree.copy(root);
delete root;
nodes.clear();
return in;
}
void
RandomizedTree::annotate(int& current_id)
{
m_id = current_id;
current_id++;
if(m_true_child) m_true_child->annotate(current_id);
if(m_false_child) m_false_child->annotate(current_id);
}
int
RandomizedTree::getNumberNodes() const
{
int a = 0;
int b = 0;
if(m_true_child) a = m_true_child->getNumberNodes();
if(m_false_child) b = m_false_child->getNumberNodes();
return 1+a+b;
}
void
RandomizedTree::compact(std::vector<RandomizedTree*>& nodes, std::vector<t_Edge>& edges) const
{
nodes.push_back(const_cast<RandomizedTree*>(this));// bad cast
if(m_true_child)
{
edges.push_back(std::pair<std::pair<int,int>,int>(std::pair<int,int>(m_id,m_true_child->m_id),1));
m_true_child->compact(nodes,edges);
}
if(m_false_child)
{
edges.push_back(std::pair<std::pair<int,int>,int>(std::pair<int,int>(m_id,m_false_child->m_id),0));
m_false_child->compact(nodes,edges);
}
}
void
RandomizedTree::expand(std::map<int,RandomizedTree*>& nodes, std::vector<t_Edge>& edges)
{
// get the id of the children, by traversing the edge list
int count=0;
for(unsigned int k=0; k<edges.size(); k++)
{
t_Edge& edge = edges[k];
if(edge.first.first == m_id)
{
if(edge.second == 1)
{
count++;
m_true_child = nodes[edge.first.second];
//remove edge from edges
edges.erase(edges.begin()+k);
k--;
}
else
{
count++;
m_false_child = nodes[edge.first.second];
//remove edge from edges
edges.erase(edges.begin()+k);
k--;
}
if(count==2)
{
// remove node from node
break; //should be faster like that
}
}
}
if(m_true_child)
{
m_true_child->expand(nodes,edges);
}
if(m_false_child)
{
m_false_child->expand(nodes,edges);
}
}
void
RandomizedTree::toDot(const char* filename)
{
// annotate the tree
int current_id = 0;
annotate(current_id);
std::vector<RandomizedTree*> nodes;
std::vector<t_Edge> edges;
compact(nodes,edges);
std::ofstream outFile(filename);
outFile<<"digraph RandomizedTree{"<<std::endl;
for(unsigned int i=0; i<nodes.size(); i++)
{
outFile<<"\tNode"<<nodes[i]->m_id<<"[label = "<<nodes[i]->m_id<<"]"<<std::endl;
}
for(unsigned int i=0; i<edges.size(); i++)
{
outFile<<"\tNode"<<edges[i].first.first<<" -> Node"<<edges[i].first.second<<"[color = ";
if(edges[i].second) outFile<<"\"#0000ff\"]"<<std::endl;
else outFile<<"\"#ff0000\"]"<<std::endl;
}
outFile<<"}"<<std::endl;
outFile.close();
}
int
RandomizedTree::getID() const
{
return m_id;
}
int
RandomizedTree::getDepth() const
{
return m_depth;
}
int
RandomizedTree::getNbClasses() const
{
return m_nb_classes;
}
unsigned int
RandomizedTree::getVectorSize() const
{
return m_vector_size;
}
double
RandomizedTree::getMinValue() const
{
return m_min_value;
}
double
RandomizedTree::getMaxValue() const
{
return m_max_value;
}
| 23.976395 | 133 | 0.600376 | scanavan |
d6900aac91829a6c1554c0df35ee5f74decc49df | 1,663 | cpp | C++ | test/test_file_io.cpp | antoinewdg/cv-utils | 3dab4f24d37ae7a41d07b7a7c18f9b80c66e3f7e | [
"MIT"
] | null | null | null | test/test_file_io.cpp | antoinewdg/cv-utils | 3dab4f24d37ae7a41d07b7a7c18f9b80c66e3f7e | [
"MIT"
] | null | null | null | test/test_file_io.cpp | antoinewdg/cv-utils | 3dab4f24d37ae7a41d07b7a7c18f9b80c66e3f7e | [
"MIT"
] | null | null | null | #include "test_common.h"
TEST_CASE("load_color") {
SECTION("Vec3b") {
Mat_<Vec3b> image = load_color(assets_dir() + "/colors.png");
REQUIRE(image(0, 0) == Vec3b(0, 0, 0));
REQUIRE(image(1, 0) == Vec3b(255, 0, 0));
REQUIRE(image(0, 1) == Vec3b(0, 0, 255));
REQUIRE(image(1, 1) == Vec3b(0, 255, 0));
REQUIRE(image(2, 1) == Vec3b(255, 255, 255));
}
SECTION("Vec3f") {
Mat_<Vec3f> image = load_color<Vec3f>(assets_dir() + "/colors.png");
REQUIRE(image(0, 0) == Vec3f(0, 0, 0));
REQUIRE(image(1, 0) == Vec3f(1, 0, 0));
REQUIRE(image(0, 1) == Vec3f(0, 0, 1));
REQUIRE(image(1, 1) == Vec3f(0, 1, 0));
REQUIRE(image(2, 1) == Vec3f(1, 1, 1));
}
}
TEST_CASE("load_grayscale") {
SECTION("uchar") {
Mat_<uchar> image = load_grayscale(assets_dir() + "/colors.png");
REQUIRE(image(0, 0) == 0);
REQUIRE(image(1, 0) == 29);
REQUIRE(image(0, 1) == 76);
REQUIRE(image(1, 1) == 149);
REQUIRE(image(2, 1) == 255);
}
SECTION("float") {
Mat_<float> image = load_grayscale<float>(assets_dir() + "/colors.png");
REQUIRE(image(0, 0) == 0.f);
REQUIRE(image(1, 0) == Approx(0.114f).epsilon(0.01));
REQUIRE(image(0, 1) == Approx(0.299f).epsilon(0.01));
REQUIRE(image(1, 1) == Approx(0.587f).epsilon(0.01));
REQUIRE(image(2, 1) == 1.f);
}
}
TEST_CASE("load_binary") {
Mat_<bool> mask = load_binary(assets_dir() + "/colors.png");
REQUIRE(!mask(0, 0));
REQUIRE(mask(1, 0));
REQUIRE(mask(0, 1));
REQUIRE(mask(1, 1));
REQUIRE(mask(2, 1));
} | 31.377358 | 80 | 0.526759 | antoinewdg |
d6911da8163b4de49fb706010ffb8cc9b120b159 | 5,960 | cpp | C++ | imapp_platform_glfw.cpp | remyroez/imgui_app | 2e715a3b4a5f2f351b27cc9af02d405d2b483e02 | [
"MIT"
] | 5 | 2021-04-07T17:33:35.000Z | 2022-03-20T21:18:42.000Z | imapp_platform_glfw.cpp | remyroez/imgui_app | 2e715a3b4a5f2f351b27cc9af02d405d2b483e02 | [
"MIT"
] | null | null | null | imapp_platform_glfw.cpp | remyroez/imgui_app | 2e715a3b4a5f2f351b27cc9af02d405d2b483e02 | [
"MIT"
] | null | null | null | // imapp: standalone application starter kit
// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
#include "imapp.h"
#include "imapp_internal.h"
#include "imgui.h"
#include "imgui_impl_glfw.h"
#if defined(IMAPP_RENDERER_OPENGL)
#include "imapp_opengl_loader.h"
#endif
// Include glfw3.h after our OpenGL definitions
#if defined(IMAPP_RENDERER_OPENGL2)
#ifdef __APPLE__
#define GL_SILENCE_DEPRECATION
#endif
#elif defined(IMAPP_RENDERER_VULKAN)
#define GLFW_INCLUDE_NONE
#define GLFW_INCLUDE_VULKAN
#endif
#include <GLFW/glfw3.h>
// [Win32] Our example includes a copy of glfw3.lib pre-compiled with VS2010 to maximize ease of testing and compatibility with old VS compilers.
// To link with VS2010-era libraries, VS2015+ requires linking with legacy_stdio_definitions.lib, which we do using this pragma.
// Your own project should not be affected, as you are likely to link with a newer binary of GLFW that is adequate for your version of Visual Studio.
#if defined(_MSC_VER) && (_MSC_VER >= 1900) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#pragma comment(lib, "legacy_stdio_definitions")
#endif
namespace
{
GLFWwindow* window = NULL;
void glfw_error_callback(int error, const char* description)
{
fprintf(stderr, "Glfw Error %d: %s\n", error, description);
}
} // namespace
namespace ImApp
{
bool SetupPlatform(const char* name, const ImVec2& size)
{
bool succeeded = false;
// Setup window
glfwSetErrorCallback(glfw_error_callback);
if (!glfwInit())
{
// Error
}
else
{
#if defined(IMAPP_RENDERER_OPENGL3)
// Decide GL+GLSL versions
#if __APPLE__
// GL 3.2 Core + GLSL 150
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Required on Mac
#else
// GL 3.0 + GLSL 130
//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // 3.0+ only
#endif
// GL Context version
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, IMAPP_GL_CONTEXT_MAJOR_VERSION);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, IMAPP_GL_CONTEXT_MINOR_VERSION);
#elif defined(IMAPP_RENDERER_VULKAN)
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
#endif
// Create window with graphics context
window = glfwCreateWindow(
size.x > 0 ? (int)size.x : 1280,
size.y > 0 ? (int)size.y : 720,
name,
NULL,
NULL
);
if (window == NULL)
{
// Error
}
else
{
#if defined(IMAPP_RENDERER_OPENGL)
glfwMakeContextCurrent(window);
glfwSwapInterval(1); // Enable vsync
#ifdef IMAPP_RENDERER_OPENGL3
succeeded = InitOpenGLLoader();
#else
succeeded = true;
#endif
#elif defined(IMAPP_RENDERER_VULKAN)
succeeded = glfwVulkanSupported();
#endif
}
}
return succeeded;
}
void ShutdownPlatform()
{
glfwDestroyWindow(window);
window = NULL;
glfwTerminate();
}
bool InitPlatform()
{
// Setup Platform bindings
#if defined(IMAPP_RENDERER_OPENGL)
return ImGui_ImplGlfw_InitForOpenGL(window, true);
#elif defined(IMAPP_RENDERER_VULKAN)
return ImGui_ImplGlfw_InitForVulkan(window, true);
#else
return false;
#endif
}
void CleanupPlatform()
{
ImGui_ImplGlfw_Shutdown();
}
void BeginFramePlatform()
{
ImGui_ImplGlfw_NewFrame();
}
void EndFramePlatform()
{
#ifdef IMAPP_RENDERER_OPENGL
glfwSwapBuffers(window);
#endif
}
void UpdateViewportPlatform()
{
#ifdef IMGUI_HAS_VIEWPORT
// Update and Render additional Platform Windows
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
#ifdef IMAPP_RENDERER_OPENGL
// (Platform functions may change the current OpenGL context, so we save/restore it to make it easier to paste this code elsewhere.
// For this specific demo app we could also call glfwMakeContextCurrent(window) directly)
GLFWwindow* backup_current_context = glfwGetCurrentContext();
#endif
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
#ifdef IMAPP_RENDERER_OPENGL
glfwMakeContextCurrent(backup_current_context);
#endif
}
#endif
}
bool ProcessEventPlatform()
{
// Poll and handle events (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
glfwPollEvents();
if (glfwWindowShouldClose(window))
{
RequestQuit();
}
return true;
}
void GetFramebufferSize(int &width, int &height)
{
glfwGetFramebufferSize(window, &width, &height);
}
void SetFramebufferSizeCallback(void* callback)
{
glfwSetFramebufferSizeCallback(window, (GLFWframebuffersizefun)callback);
}
void *GetProcAddress(const char* proc_name)
{
return (void *)glfwGetProcAddress(proc_name);
}
const char** GetInstanceExtensions(unsigned int* extensions_count)
{
return glfwGetRequiredInstanceExtensions(extensions_count);
}
void ReleaseInstanceExtensions(const char** extensions)
{
// not required.
}
int CreateWindowSurface(void* instance, const void* allocator, void* surface)
{
#ifdef IMAPP_RENDERER_VULKAN
return glfwCreateWindowSurface((VkInstance)instance, window, (const VkAllocationCallbacks*)allocator, (VkSurfaceKHR*)surface);;
#else
return 0;
#endif
}
}
| 26.968326 | 149 | 0.713423 | remyroez |
d692135582f44fee33dd8fb3ea7e545fd3e5cd9f | 3,466 | cpp | C++ | src/main.cpp | segmentation-chaos/dynamical-systems | 046f239b1be7753dfbe8f3f556030151a528fc0c | [
"BSD-3-Clause"
] | 3 | 2019-09-25T22:20:32.000Z | 2019-09-26T14:43:40.000Z | src/main.cpp | segmentation-chaos/dynamical-systems | 046f239b1be7753dfbe8f3f556030151a528fc0c | [
"BSD-3-Clause"
] | null | null | null | src/main.cpp | segmentation-chaos/dynamical-systems | 046f239b1be7753dfbe8f3f556030151a528fc0c | [
"BSD-3-Clause"
] | 1 | 2021-07-21T23:25:45.000Z | 2021-07-21T23:25:45.000Z | /* */
/* CLICK SPACE */
/* */
/* An educational application for dy- */
/* namical systems and C++ programmi- */
/* ng. Two applications available: */
/* */
/* 2D maps: */
/* Allows the interaction with a can- */
/* vas from which orbits of 2D maps */
/* can be iterated. */
/* Controls: */
/* Left click (hold): iterate orbit */
/* Right click: open zoom frame */
/* (When zooming) Left click: zoom in */
/* C: total zoom out */
/* X: delete previous orbit */
/* Ctrl + X: delete all orbits */
/* Ctrl + S: Save current orbits */
/* (file in results/map_name/) */
/* Ctrl + Left Click (hold and drag): */
/* Pan Screen */
/* Scrool UP: Zoom in */
/* Scrool DOWN: Zoom out */
/* R: Start line of init. cond. pts */
/* (In line) Scrool up: increase pts */
/* (In line) Scrool down: decrease pts*/
/* (In line) Space bar: run all */
/* (In line) S: exit line */
/* N: Toggle night | light mode color */
/* */
/* */
/* 1D maps: */
/* Allows the interaction with a can- */
/* vas from which cob web orbits are */
/* draw, allowing also the control of */
/* one of the system's parameter */
/* Controls: */
/* Left mouse click: run cob web */
/* W: increase parameter */
/* S: decrease parameter */
/* ESC: back to main menu */
/* */
/* */
/* This program is implemented with */
/* the olcPixelGameEngine, as develo- */
/* ped by Javidx9 (David Bahr). Its */
/* original license and readme file */
/* are shown in LICENSE/, and the en- */
/* gine file in olcPixelGameEngine.h. */
/* Moreover, the code for the main */
/* menu was directly copied from it, */
/* along with small tips and tricks */
/* that Javidx9 brilliantly passes on */
/* to all commom folks willing to le- */
/* arn C++ from his channel (Thank */
/* you Javidx9), although any errors */
/* or bugs are in full responsability */
/* of the developers. */
/* */
/* Designed and manufactured in */
/* Brazil by: */
/* M. Lazarotto */
/* V. Oliveira */
/* M. Palmero */
/* (21/11/2020) */
/* */
/* */
/* To run the program, within a term- */
/* inal compile it by typing: */
/* */
/* make clean && make */
/* */
/* And run it by typing: */
/* */
/* vblank_mode=0 ./click_space */
/* */
#include "clickspace.h"
int main()
{
// App window settings
olcClickSpace application;
int32_t ScreenWidth = 1400;
int32_t ScreenHeight = 1000;
// Main game loop
if (application.Construct(ScreenWidth, ScreenHeight, 1, 1))
{
application.Start();
}
return 0;
} | 36.484211 | 63 | 0.430756 | segmentation-chaos |
d69294da0ec393ccf1749eeb019afcc098d45244 | 32,472 | cpp | C++ | client/Classes/View/Layers/NetworkQueueLayer/NetworkQueueLayer.cpp | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 60 | 2015-01-03T07:31:14.000Z | 2021-12-17T02:39:17.000Z | client/Classes/View/Layers/NetworkQueueLayer/NetworkQueueLayer.cpp | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 1 | 2018-08-17T09:59:30.000Z | 2018-08-17T09:59:30.000Z | client/Classes/View/Layers/NetworkQueueLayer/NetworkQueueLayer.cpp | plankes-projects/BaseWar | 693f7d02fa324b917b28be58d33bb77a18d77f26 | [
"Apache-2.0"
] | 27 | 2015-01-22T06:55:10.000Z | 2021-12-17T02:39:23.000Z | #include "NetworkQueueLayer.h"
#include "../../../Model/Model.h"
#include "../../../SceneControl.h"
#include "../../../Network/ServerCommunication.h"
#include "../../../Network/NetworkSingleton.h"
#include "../../../Tools/Tools.h"
#include "../../../Tools/BW_Time.h"
#include "../../../Model/GameMode.h"
#include "../../../Constants.h"
#include "../../../Tools/ViewTools.h"
#include "../../../AchievementSystem/AchievementSystem.h"
// on "init" you need to initialize your instance
bool NetworkQueueLayer::init() {
Model::getInstance()->setGameMode(NETWORK);
float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator();
if (!CCLayerColor::initWithColor(ccc4(100, 255, 255, 255)))
return false;
_gameStarted = false;
//adding the background
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
cocos2d::CCSprite* backgroundArt = CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("menuBackground.png"));
float bgScale = winSize.height / backgroundArt->getContentSize().height;
backgroundArt->setScale(bgScale);
float diff = winSize.width - backgroundArt->getContentSize().width * bgScale;
float x = backgroundArt->getContentSize().width / 2 * bgScale + diff / 2;
float y = backgroundArt->getContentSize().height / 2 * bgScale;
backgroundArt->setPosition(ccp(x, y));
addChild(backgroundArt);
float button_length = 66 * scaleMult;
float button_heigth = 66 * scaleMult;
float padding = 10 * scaleMult;
_leaveQueue = CCMenuItemSprite::create(CCSprite::createWithSpriteFrameName("return0.png"), CCSprite::createWithSpriteFrameName("return1.png"),
(CCObject*) this, menu_selector(NetworkQueueLayer::leaveQueueTouched));
_leaveQueue->setScaleX(button_length / _leaveQueue->getContentSize().width);
_leaveQueue->setScaleY(button_heigth / _leaveQueue->getContentSize().height);
CCMenu* menu = CCMenu::create();
menu->addChild(_leaveQueue, 1);
menu->alignItemsHorizontallyWithPadding(padding);
addChild(menu);
_sendingRequest = false;
_foundGame = false;
_countDown = CCLabelTTF::create("", FONT_NAME, 150 * scaleMult);
_countDown->setPosition(ccp(winSize.width / 2, winSize.height / 2));
_countDown->setColor(ccc3(74, 24, 147));
addChild(_countDown);
//init server message
float label_font_size = 25 * scaleMult;
const char* label_font = FONT_NAME;
ccColor3B color = ccc3(0, 0, 0);
_serverMessage = CCLabelTTF::create("Connecting to basewar.net ...", label_font, label_font_size);
_serverMessage->setColor(color);
_serverMessage->setPosition(ccp(winSize.width / 2, winSize.height / 2 - (button_heigth / 2 + padding + _serverMessage->getContentSize().height / 2)));
this->addChild(_serverMessage);
_serverInformation = CCLabelTTF::create("", label_font, label_font_size);
_serverInformation->setColor(color);
this->addChild(_serverInformation);
_loadedServerInformation = false;
_loadedPlayerNumInformation = false;
_loadedTeamsizeConfig = false;
_maxSecToStart = -1; //will be set by server request
_playerSet = false;
_teamsizeConfig = 1;
_queueTimeInSec = BW_Time::getSeconds();
_numOfPlayersOnline = -1;
ServerCommunication().sendGameProgress();
this->schedule(schedule_selector(NetworkQueueLayer::update), 1);
float offsetDown = ViewTools::addVersionAndCreditInfo(this, scaleMult);
ViewTools::addIdleUnitTo(this, offsetDown);
return true;
}
void NetworkQueueLayer::update(float dt) {
if (_foundGame)
gameCounterPart();
else
queuePart();
}
void NetworkQueueLayer::gameCounterPart() {
if (!_playerSet) {
_playerSet = true;
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator();
std::string vsStringPartOne = "";
std::string vsStringPartZwo = "";
std::string vsString = "";
bool second = false;
bool playerAtSecond = false;
std::vector < std::string > names = NetworkSingleton::getInstance()->_names;
int playerIdWrittenLast = -1;
bool gotMyName = false;
int numGamestats = NetworkSingleton::getInstance()->_gameStats.size();
for (int i = 0; i < numGamestats; i++) {
GameStat current = NetworkSingleton::getInstance()->_gameStats[i];
int id = current.getPlayerId();
if (id == (playerIdWrittenLast + 1)) {
vsString = names[i] + "\n";
} else {
gotMyName = true;
playerAtSecond = second;
i--; //we need to use this id again
vsString = _playerName + "\n";
}
if (second)
vsStringPartZwo += vsString;
else
vsStringPartOne += vsString;
playerIdWrittenLast++;
if (playerIdWrittenLast + 1 == (numGamestats + 1) / 2)
second = true;
}
if (!gotMyName) { //my name was at the end, add it
vsStringPartZwo += _playerName + "\n";
playerAtSecond = second;
}
if (playerAtSecond) {
vsString = vsStringPartZwo + "--- vs ---\n" + vsStringPartOne;
} else {
vsString = vsStringPartOne + "--- vs ---\n" + vsStringPartZwo;
}
cocos2d::CCLabelTTF* vsInfo = CCLabelTTF::create(vsString.c_str(), FONT_NAME, 25 * scaleMult);
vsInfo->setColor(ccc3(0, 0, 0));
vsInfo->setPosition(ccp(vsInfo->getContentSize().width / 2 + 10 * scaleMult, winSize.height / 2));
this->addChild(vsInfo);
}
int start = NetworkSingleton::getInstance()->_gameStart;
int now = BW_Time::getSeconds();
if (start < now) {
//fixes a bug on slower devices which results in a double call of this
if (_gameStarted)
return;
_gameStarted = true;
NetworkSingleton::getInstance()->_myName = _playerName;
SceneControl::replaceScene(SceneControl::gameScene(1, NETWORK), true);
return;
}
int left = start - now;
if (left == 0)
_countDown->setString("Fight!");
else
_countDown->setString(Tools::toString(left).c_str());
CCFiniteTimeAction *scale1 = CCScaleTo::create(0.15f, 1.3f);
CCFiniteTimeAction *scale2 = CCScaleTo::create(0.1f, 0.7f);
CCFiniteTimeAction *scale3 = CCScaleTo::create(0.05f, 1.0f);
_countDown->runAction(CCSequence::create(scale1, scale2, scale3, NULL));
}
void NetworkQueueLayer::onQueueCompleted(CCHttpClient *sender, CCHttpResponse *response) {
if (!response)
return completeQueueRequest(-1, "");
if (!response->isSucceed()) {
CCLog("server get queue response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
return completeQueueRequest(-1, "");
}
std::string resp = Tools::toString(response->getResponseData());
CCLOG("queue resp: %s", resp.c_str());
//CCLOG("string begin ---------");
//CCLOG(resp.c_str());
//CCLOG("string end ---------");
float recieve_time = BW_Time::getMilliSeconds();
//looking at it line by line
std::istringstream f(resp);
std::string line;
std::getline(f, line);
std::string firstServerLine = line;
if (firstServerLine == "")
return completeQueueRequest(-3, firstServerLine);
/** Server returns:
joined queue: 0
in queue: 1
Game init:
-18
0:1+klaus
1:1+klaus
2:1+123-132-41-12-412-423-1-412-1+klaus
3:1+klaus
4:1+klaus
5
*/
NetworkSingleton *ns = NetworkSingleton::getInstance();
ns->reset();
int addLines = -1;
while (std::getline(f, line)) {
//empty line is last
if (line == "")
break;;
addLines++;
//CCLOG("line: %s", line.c_str());
std::size_t found = line.find(":");
if (found == std::string::npos) {
//this is my id
if (ns->_myGameStat.getPlayerId() == -1) {
int id = atoi(line.c_str());
if (id != addLines) //invalid
{
//CCLOG("inv 1: %i != %i", id, addLines);
return completeQueueRequest(-2, firstServerLine);
}
ns->_myGameStat.setRace(_raceId);
ns->_myGameStat.setPlayerId(id);
ns->_myGameStat.setRandomRaceString(_randomRaceString);
continue;
} else {
//invalid
CCLOG("inv 2: ");
return completeQueueRequest(-3, firstServerLine);
}
} else if (found != 1) {
//invalid
CCLOG(line.c_str(), 1);
return completeQueueRequest(-4, firstServerLine);
}
found = line.find("+");
if (found != 3) {
CCLOG("inv 4");
return completeQueueRequest(-5, firstServerLine);
}
GameStat gs = GameStat();
int id = line[0] - '0';
if (id != addLines) { //invalid
CCLOG("inv 5: %i != %i", id, addLines);
return completeQueueRequest(-6, firstServerLine);
}
gs.setPlayerId(id);
int raceId = line[2] - '0';
gs.setRace(raceId);
std::string name = line.substr(found + 1);
if (raceId == 0) {
//there must be a randomRaceString
//2:1+123-132-41-12-412-423-1-412-1+klaus
found = name.find("+");
if (found == std::string::npos) {
CCLOG("inv 6");
return completeQueueRequest(-6, firstServerLine);
}
std::string randomRaceString = name.substr(0, found);
gs.setRandomRaceString(randomRaceString);
CCLOG("Name: %s", name.c_str());
name = name.substr(found + 1);
CCLOG("RandomRaceString: %s", randomRaceString.c_str());
}
ns->_names.push_back(name);
ns->_gameStats.push_back(gs);
}
//check number of players
if (ns->_names.size() == 0)
return completeQueueRequest(0, firstServerLine);
if ((ns->_names.size() + 1) % 2 != 0) //+1 because of my id
{
CCLOG("inv 7");
return completeQueueRequest(-7, firstServerLine);
}
//calc starttime
int delay = (recieve_time - _send_time) / 2000;
//first line is the time to start number
ns->_gameStart = BW_Time::getSeconds() + atoi(firstServerLine.c_str()) - delay;
/*
CCLOG("read some data: -----------");
CCLOG("start: %i", ns->_gameStart);
CCLOG("myid: %i", ns->_myGameStat.getPlayerId());
for(int i = 0; i < ns->_names.size(); i++)
{
CCLOG("Name: %s, id: %i, race: %i", ns->_names[i].c_str(), ns->_gameStats[i].getPlayerId(), ns->_gameStats[i].getRace());
}
CCLOG("-----------");
*/
return completeQueueRequest(2, firstServerLine);
}
void NetworkQueueLayer::initAINetworkPlayers() {
int allPlayerSize = _teamsizeConfig * 2;
if (allPlayerSize < 2 || allPlayerSize > 6)
allPlayerSize = 6;
NetworkSingleton *ns = NetworkSingleton::getInstance();
ns->reset();
ns->_myGameStat.setRace(_raceId);
ns->_myGameStat.setPlayerId(Tools::random(0, allPlayerSize - 1));
ns->_myGameStat.setRandomRaceString(_randomRaceString);
//get number of possible races
int maxPossibleRaceId = 0;
for (Race* r = Race::createRaceWithId(maxPossibleRaceId); r != 0; maxPossibleRaceId++, r = Race::createRaceWithId(maxPossibleRaceId)) {
delete r;
}
maxPossibleRaceId--; //remove not existing id
//generate random player names
std::vector < std::string > playerNames = getFakePlayerNames();
for (int id = 0; id < allPlayerSize; id++) {
if (ns->_myGameStat.getPlayerId() == id)
continue;
GameStat gs = GameStat();
gs.setPlayerId(id);
gs.setRace(Tools::random(0, maxPossibleRaceId));
gs.setRandomRaceString(gs.getRace() == 0 ? Race::createRandomizedRaceString() : "");
int fakePlayerNameIndex = Tools::random(0, playerNames.size() - 1);
ns->_names.push_back(playerNames[fakePlayerNameIndex]);
playerNames.erase(playerNames.begin() + fakePlayerNameIndex);
ns->_gameStats.push_back(gs);
}
ns->_gameStart = BW_Time::getSeconds() + Tools::random(8, 10);
}
void NetworkQueueLayer::completeQueueRequest(int code, std::string firstServerLine) {
if (code == -1) {
_serverMessage->setString("Could not connect to the server (-1)");
CCLOG("Could not connect to the server! (-1)");
} else if (code < -1) {
std::string msg = "Server communication error (" + Tools::toString(code) + ")";
_serverMessage->setString(msg.c_str());
CCLOG(msg.c_str(), 1);
} else if (code == 2) {
CCLOG("Filled the NetworkSingleton! Game created.");
_leaveQueue->removeFromParentAndCleanup(true);
_serverMessage->removeFromParentAndCleanup(true);
_serverMessage = NULL;
NetworkSingleton::getInstance()->fakeNetworkGame = false;
_foundGame = true;
} else if (code == 0) {
std::string waiting = Tools::toString(_teamsizeConfig) + " vs " + Tools::toString(_teamsizeConfig);
std::string numOfPlayer = "\nPlayers online: " + (_numOfPlayersOnline == -1 ? "-" : Tools::toString(_numOfPlayersOnline));
//Do something with firstServerLine. currently its 1/2
int secLeft = _queueTimeInSec - BW_Time::getSeconds() + _maxSecToStart;
std::string estimatedTime = "\nEstimated seconds until start: " + (secLeft < 0 ? "0" : Tools::toString(secLeft));
_serverMessage->setString((waiting + numOfPlayer + estimatedTime).c_str());
if (secLeft <= 0) {
initAINetworkPlayers();
_leaveQueue->removeFromParentAndCleanup(true);
_serverMessage->removeFromParentAndCleanup(true);
_serverMessage = NULL;
NetworkSingleton::getInstance()->fakeNetworkGame = true;
_foundGame = true;
}
}
if (_serverMessage != NULL) {
float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator();
float padding = 10 * scaleMult;
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
float button_heigth = 66 * scaleMult;
_serverMessage->setPosition(ccp(winSize.width / 2, winSize.height / 2 - (button_heigth / 2 + padding + _serverMessage->getContentSize().height / 2)));
}
_sendingRequest = false;
}
void NetworkQueueLayer::onTeamsizeConfigCompleted(CCHttpClient *sender, CCHttpResponse *response) {
if (!response) {
CCLog("server team size info response failed - response missing");
_loadedTeamsizeConfig = false;
return;
}
if (!response->isSucceed()) {
CCLog("server team size info response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
_loadedTeamsizeConfig = false;
return;
}
std::string resp = Tools::toString(response->getResponseData());
_teamsizeConfig = atoi(resp.c_str());
//we are sure to have server connection here
for (int i = 0; i < NUMBER_OF_OFFLINE_GAMES_SEND_AT_ONE_TIME; i++)
ServerCommunication().sendOldestOfflineLog();
}
void NetworkQueueLayer::onPlayerNumInfoCompleted(CCHttpClient *sender, CCHttpResponse *response) {
if (!response) {
CCLog("server player num info response failed - response missing");
_loadedPlayerNumInformation = false;
return;
}
if (!response->isSucceed()) {
CCLog("server player num info response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
_loadedPlayerNumInformation = false;
return;
}
std::string resp = Tools::toString(response->getResponseData());
std::vector < std::string > playerNumEstimatedTime = Tools::splitStringBy(resp, '-');
if (playerNumEstimatedTime.size() != 2) {
CCLOG("[ERROR] Playernum should has the format 'PlayerNum-EstimatedSec'");
_loadedPlayerNumInformation = false;
return;
}
_numOfPlayersOnline = atoi(playerNumEstimatedTime[0].c_str());
_maxSecToStart = atoi(playerNumEstimatedTime[1].c_str());
}
void NetworkQueueLayer::onGetServerInfoCompleted(CCHttpClient *sender, CCHttpResponse *response) {
if (!response) {
CCLog("server get info response failed - response missing");
_loadedServerInformation = false;
return;
}
if (!response->isSucceed()) {
CCLog("server get info response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
_loadedServerInformation = false;
return;
}
std::string resp = Tools::toString(response->getResponseData());
std::string basewarflag = "<basewarQueueInfo>";
if (resp.compare(0, basewarflag.size(), basewarflag) != 0)
return; //fail script
resp.erase(0, resp.find('\n') + 1); //remove first line with server info flag
float scaleMult = Model::getInstance()->getGUIElementScaleMultiplicator();
float padding = 10 * scaleMult;
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
float button_heigth = 66 * scaleMult;
_serverInformation->setString(resp.c_str());
_serverInformation->setPosition(
ccp(winSize.width / 2, winSize.height / 2 + (button_heigth / 2 + padding + _serverInformation->getContentSize().height / 2)));
}
void NetworkQueueLayer::queuePart() {
if (_sendingRequest)
return;
ServerCommunication sc = ServerCommunication();
if (!_loadedServerInformation) {
_loadedServerInformation = true;
sc.getServerinformation(this, httpresponse_selector(NetworkQueueLayer::onGetServerInfoCompleted));
}
if (!_loadedPlayerNumInformation) {
_loadedPlayerNumInformation = true;
sc.getPlayerNum(this, httpresponse_selector(NetworkQueueLayer::onPlayerNumInfoCompleted));
}
if (!_loadedTeamsizeConfig) {
_loadedTeamsizeConfig = true;
sc.getTeamsizeConfig(this, httpresponse_selector(NetworkQueueLayer::onTeamsizeConfigCompleted));
}
//we reset the queued time, do we will not have an invalid seconds in queue time
if (_maxSecToStart == -1)
_queueTimeInSec = BW_Time::getSeconds();
//first request is send 5 seconds after we joined (and first server contact)
if (BW_Time::getSeconds() - _queueTimeInSec < 5) {
if (_maxSecToStart != -1) {
completeQueueRequest(0, Tools::toString(BW_Time::getSeconds() - _queueTimeInSec));
}
return;
}
_sendingRequest = true;
_send_time = BW_Time::getMilliSeconds();
sc.queueMe(_raceId, _playerName, _randomRaceString, this, httpresponse_selector(NetworkQueueLayer::onQueueCompleted));
}
void NetworkQueueLayer::leaveQueueTouched(CCObject* pSender) {
SceneControl::replaceScene(SceneControl::startMenuScene(), false);
}
void NetworkQueueLayer::setPlayerName(std::string playerName) {
_playerName = playerName;
}
void NetworkQueueLayer::setRaceId(int raceId) {
_raceId = raceId;
_randomRaceString = "";
if (_raceId == 0) {
_randomRaceString = Race::createRandomizedRaceString();
}
}
std::vector<std::string> NetworkQueueLayer::getFakePlayerNames() {
std::vector < std::string > fakePlayerName;
//add some self defined names
fakePlayerName.push_back("Rok");
fakePlayerName.push_back("Rock");
fakePlayerName.push_back("Shoroa");
fakePlayerName.push_back("Töpfchen");
//add names from a generator
fakePlayerName.push_back("Doozmolt");
fakePlayerName.push_back("Gunkumb");
fakePlayerName.push_back("Froof");
fakePlayerName.push_back("Froob");
fakePlayerName.push_back("Glunphball");
fakePlayerName.push_back("Clunuzz");
fakePlayerName.push_back("Gogwook");
fakePlayerName.push_back("Womph");
fakePlayerName.push_back("Punt");
fakePlayerName.push_back("Kuckbun");
fakePlayerName.push_back("Gobult");
fakePlayerName.push_back("Donkpidiot");
fakePlayerName.push_back("Porkfrub");
fakePlayerName.push_back("Jumfelch");
fakePlayerName.push_back("Poltmorm");
fakePlayerName.push_back("Glunt");
fakePlayerName.push_back("Bookdip");
fakePlayerName.push_back("Klomphnump");
fakePlayerName.push_back("Frelchung");
fakePlayerName.push_back("Cloron");
fakePlayerName.push_back("Wongfumph");
fakePlayerName.push_back("Jidiotgunph");
fakePlayerName.push_back("Gobglunk");
fakePlayerName.push_back("Donkun");
fakePlayerName.push_back("Doofmonk");
fakePlayerName.push_back("Blokjog");
fakePlayerName.push_back("Blumphgoof");
fakePlayerName.push_back("Thobclown");
fakePlayerName.push_back("Brolt");
fakePlayerName.push_back("Porkjunb");
fakePlayerName.push_back("Funph");
fakePlayerName.push_back("Pobbeef");
fakePlayerName.push_back("Gunnit");
fakePlayerName.push_back("Kubfrorm");
fakePlayerName.push_back("Hunphthimble");
fakePlayerName.push_back("Grubbrok");
fakePlayerName.push_back("Bumbdidiot");
fakePlayerName.push_back("Gunankle");
fakePlayerName.push_back("Nuck");
fakePlayerName.push_back("Dobong");
fakePlayerName.push_back("Bump");
fakePlayerName.push_back("Borkmuck");
fakePlayerName.push_back("Kult");
fakePlayerName.push_back("Doowad");
fakePlayerName.push_back("Ghoog");
fakePlayerName.push_back("Nonkdip");
fakePlayerName.push_back("Gob");
fakePlayerName.push_back("Puzz");
fakePlayerName.push_back("Fuck");
fakePlayerName.push_back("Dulfclot");
fakePlayerName.push_back("Grunkum");
fakePlayerName.push_back("Bunkghub");
fakePlayerName.push_back("Ghunkook");
fakePlayerName.push_back("Pormbeef");
fakePlayerName.push_back("Ghomph");
fakePlayerName.push_back("Clumbob");
fakePlayerName.push_back("Dultbridiot");
fakePlayerName.push_back("Jolph");
fakePlayerName.push_back("Fomph");
fakePlayerName.push_back("Pob");
fakePlayerName.push_back("Gunbloaf");
fakePlayerName.push_back("Grorg");
fakePlayerName.push_back("Klok");
fakePlayerName.push_back("Porgoo");
fakePlayerName.push_back("Thelchgog");
fakePlayerName.push_back("Mulfflolt");
fakePlayerName.push_back("Porgknock");
fakePlayerName.push_back("Moob");
fakePlayerName.push_back("Hoobomph");
fakePlayerName.push_back("Huck");
fakePlayerName.push_back("Mummunb");
fakePlayerName.push_back("Puzz");
fakePlayerName.push_back("Klumbdooz");
fakePlayerName.push_back("Fonk");
fakePlayerName.push_back("Mok");
fakePlayerName.push_back("Dolphpolph");
fakePlayerName.push_back("Flolt");
fakePlayerName.push_back("Pook");
fakePlayerName.push_back("Florkporon");
fakePlayerName.push_back("Clok");
fakePlayerName.push_back("Gunph");
fakePlayerName.push_back("Flonk");
fakePlayerName.push_back("Didiot");
fakePlayerName.push_back("Clookgoof");
fakePlayerName.push_back("Moron");
fakePlayerName.push_back("Thugtwit");
fakePlayerName.push_back("Fumb");
fakePlayerName.push_back("Dolph");
fakePlayerName.push_back("Thumb");
fakePlayerName.push_back("Moohead");
fakePlayerName.push_back("Blok");
fakePlayerName.push_back("Koogfumble");
fakePlayerName.push_back("Flob");
fakePlayerName.push_back("Kub");
fakePlayerName.push_back("Dok");
fakePlayerName.push_back("Klunph");
fakePlayerName.push_back("Midiot");
fakePlayerName.push_back("Brubankle");
fakePlayerName.push_back("Bonk");
fakePlayerName.push_back("Mumpface");
fakePlayerName.push_back("Pulf");
fakePlayerName.push_back("Tholphknuckle");
fakePlayerName.push_back("Dunphdip");
fakePlayerName.push_back("Fuck");
fakePlayerName.push_back("Ghunbum");
fakePlayerName.push_back("Nuntgong");
fakePlayerName.push_back("Fumb");
fakePlayerName.push_back("Mongborm");
fakePlayerName.push_back("Floronbrumb");
fakePlayerName.push_back("Clorgdumb");
fakePlayerName.push_back("Ponkknock");
fakePlayerName.push_back("Clunoof");
fakePlayerName.push_back("Buboo");
fakePlayerName.push_back("Jidiotgluzz");
fakePlayerName.push_back("Fumphbult");
fakePlayerName.push_back("Borgug");
fakePlayerName.push_back("Muzz");
fakePlayerName.push_back("Bung");
fakePlayerName.push_back("Book");
fakePlayerName.push_back("Rynot");
fakePlayerName.push_back("Modup");
fakePlayerName.push_back("Xofili");
fakePlayerName.push_back("Hinserererwor");
fakePlayerName.push_back("Achsertorech");
fakePlayerName.push_back("Naldyn");
fakePlayerName.push_back("Emelm");
fakePlayerName.push_back("Hiwar");
fakePlayerName.push_back("Kimvia");
fakePlayerName.push_back("Mostai");
fakePlayerName.push_back("Imlorrad");
fakePlayerName.push_back("Steyz");
fakePlayerName.push_back("Hipolaugh");
fakePlayerName.push_back("Warbom");
fakePlayerName.push_back("Trandtin");
fakePlayerName.push_back("Eldkel");
fakePlayerName.push_back("Ormiss");
fakePlayerName.push_back("Colen");
fakePlayerName.push_back("Veryis");
fakePlayerName.push_back("Ardnque");
fakePlayerName.push_back("Kinnsul");
fakePlayerName.push_back("Lyedralye");
fakePlayerName.push_back("Quedusk");
fakePlayerName.push_back("Schoath");
fakePlayerName.push_back("Cesoh");
fakePlayerName.push_back("Iaro");
fakePlayerName.push_back("Lerkin");
fakePlayerName.push_back("Ineadves");
fakePlayerName.push_back("Chryorran");
fakePlayerName.push_back("Anysu");
fakePlayerName.push_back("Endean");
fakePlayerName.push_back("Timan");
fakePlayerName.push_back("Whialeen");
fakePlayerName.push_back("Untind");
fakePlayerName.push_back("Poiqche");
fakePlayerName.push_back("Iaez");
fakePlayerName.push_back("Ranl");
fakePlayerName.push_back("Eldalemor");
fakePlayerName.push_back("Tiald");
fakePlayerName.push_back("Telyecer");
fakePlayerName.push_back("Rodeld");
fakePlayerName.push_back("Yvory");
fakePlayerName.push_back("Blitor");
fakePlayerName.push_back("Zebese");
fakePlayerName.push_back("Naertough");
fakePlayerName.push_back("Emche");
fakePlayerName.push_back("Ittor");
fakePlayerName.push_back("Radrako");
fakePlayerName.push_back("Lerrothper");
fakePlayerName.push_back("Cheor");
fakePlayerName.push_back("Drianan");
fakePlayerName.push_back("Atidel");
fakePlayerName.push_back("Ustia");
fakePlayerName.push_back("Untther");
fakePlayerName.push_back("Sulwor");
fakePlayerName.push_back("Ranris");
fakePlayerName.push_back("Fotad");
fakePlayerName.push_back("Ranbel");
fakePlayerName.push_back("Essgar");
fakePlayerName.push_back("Lyeip");
fakePlayerName.push_back("Rodol");
fakePlayerName.push_back("Danest");
fakePlayerName.push_back("Yuemest");
fakePlayerName.push_back("Adado");
fakePlayerName.push_back("Enrothdar");
fakePlayerName.push_back("Darzton");
fakePlayerName.push_back("Rayet");
fakePlayerName.push_back("Agehwar");
fakePlayerName.push_back("Vorald");
fakePlayerName.push_back("Engissard");
fakePlayerName.push_back("Burtonine");
fakePlayerName.push_back("Nalbur");
fakePlayerName.push_back("Quetorton");
fakePlayerName.push_back("Chab");
fakePlayerName.push_back("Engem");
fakePlayerName.push_back("Dradarmor");
fakePlayerName.push_back("Dentasa");
fakePlayerName.push_back("Aughirray");
fakePlayerName.push_back("Bataf");
fakePlayerName.push_back("Ilbani");
fakePlayerName.push_back("Urnn");
fakePlayerName.push_back("Titser");
fakePlayerName.push_back("Theusmos");
fakePlayerName.push_back("Aldack");
fakePlayerName.push_back("Estunti");
fakePlayerName.push_back("Untangsam");
fakePlayerName.push_back("Serach");
fakePlayerName.push_back("Lergkin");
fakePlayerName.push_back("Zorary");
fakePlayerName.push_back("Rasec");
fakePlayerName.push_back("Burset");
fakePlayerName.push_back("Querothrak");
fakePlayerName.push_back("Swyves");
fakePlayerName.push_back("Kindel");
fakePlayerName.push_back("Enat");
fakePlayerName.push_back("Urnade");
fakePlayerName.push_back("Athine");
fakePlayerName.push_back("Serozy");
fakePlayerName.push_back("Ineone");
fakePlayerName.push_back("Rayelmmorechdyn");
fakePlayerName.push_back("Iatane");
fakePlayerName.push_back("Worona");
fakePlayerName.push_back("Lathunt");
fakePlayerName.push_back("Untalt");
fakePlayerName.push_back("Ankel");
fakePlayerName.push_back("Ghagom");
fakePlayerName.push_back("Waraldiss");
fakePlayerName.push_back("Marosian");
fakePlayerName.push_back("Lisirrasya");
fakePlayerName.push_back("Sondilsanya");
fakePlayerName.push_back("Lisadar");
fakePlayerName.push_back("Marirrala");
fakePlayerName.push_back("Sondim");
fakePlayerName.push_back("Chrundosia");
fakePlayerName.push_back("Lassosia");
fakePlayerName.push_back("Iskossa");
fakePlayerName.push_back("Lassosiaya");
fakePlayerName.push_back("Chanephi");
fakePlayerName.push_back("Chanirraya");
fakePlayerName.push_back("Frichilsanya");
fakePlayerName.push_back("Chamilsan");
fakePlayerName.push_back("Iskista");
fakePlayerName.push_back("Assast");
fakePlayerName.push_back("Chamilsa");
fakePlayerName.push_back("Assilsa");
fakePlayerName.push_back("Chadossasta");
fakePlayerName.push_back("Frichosia");
fakePlayerName.push_back("Iskastnya");
fakePlayerName.push_back("Chadim");
fakePlayerName.push_back("Lirtassa");
fakePlayerName.push_back("Iladar");
fakePlayerName.push_back("Doistiman");
fakePlayerName.push_back("Sondazoan");
fakePlayerName.push_back("Lisofe");
fakePlayerName.push_back("Sondirra");
fakePlayerName.push_back("Chadosia");
fakePlayerName.push_back("Sundassa");
fakePlayerName.push_back("Lisossanya");
fakePlayerName.push_back("Lassosiasda");
fakePlayerName.push_back("Frichassa");
fakePlayerName.push_back("Marossa");
fakePlayerName.push_back("Sundastya");
fakePlayerName.push_back("Mindossa");
fakePlayerName.push_back("Chanistanya");
fakePlayerName.push_back("Jiskjask");
fakePlayerName.push_back("Sundim");
fakePlayerName.push_back("Assjasksya");
fakePlayerName.push_back("Lisushi");
fakePlayerName.push_back("Lirtjask");
fakePlayerName.push_back("Chanisi");
fakePlayerName.push_back("Jiskadarsda");
fakePlayerName.push_back("Undim");
fakePlayerName.push_back("Jiskosia");
fakePlayerName.push_back("Lirtilsasta");
fakePlayerName.push_back("Loidinna");
fakePlayerName.push_back("Sondossa");
fakePlayerName.push_back("Assassa");
fakePlayerName.push_back("Assosia");
fakePlayerName.push_back("Chamirrasda");
fakePlayerName.push_back("Sundista");
fakePlayerName.push_back("Lisilsan");
fakePlayerName.push_back("Lisassasda");
fakePlayerName.push_back("Chadassa");
fakePlayerName.push_back("Serun");
fakePlayerName.push_back("Ormptor");
fakePlayerName.push_back("Blon");
fakePlayerName.push_back("Vorban");
fakePlayerName.push_back("Ashed");
fakePlayerName.push_back("Toit");
fakePlayerName.push_back("Enthbur");
fakePlayerName.push_back("Inasul");
fakePlayerName.push_back("Zhiwor");
fakePlayerName.push_back("Ardis");
fakePlayerName.push_back("Teer");
fakePlayerName.push_back("Nyath");
fakePlayerName.push_back("Lyetorine");
fakePlayerName.push_back("Etther");
fakePlayerName.push_back("Umvor");
fakePlayerName.push_back("Morth");
fakePlayerName.push_back("Polmser");
fakePlayerName.push_back("Morlkim");
fakePlayerName.push_back("Verurnlor");
fakePlayerName.push_back("Therrod");
fakePlayerName.push_back("Isstora");
fakePlayerName.push_back("Honr");
fakePlayerName.push_back("Aoso");
fakePlayerName.push_back("Worz");
fakePlayerName.push_back("Aechu");
fakePlayerName.push_back("Tozefa");
fakePlayerName.push_back("Rilawim");
fakePlayerName.push_back("Charilhin");
fakePlayerName.push_back("Aldcem");
fakePlayerName.push_back("Ormale");
fakePlayerName.push_back("Beust");
fakePlayerName.push_back("Gilypa");
fakePlayerName.push_back("Hindcha");
fakePlayerName.push_back("Brasam");
fakePlayerName.push_back("Belnys");
fakePlayerName.push_back("Degar");
fakePlayerName.push_back("Elmir");
fakePlayerName.push_back("Hycerale");
fakePlayerName.push_back("Poly");
fakePlayerName.push_back("Yeir");
fakePlayerName.push_back("Yuigshy");
fakePlayerName.push_back("Cherodi");
fakePlayerName.push_back("Ghancer");
fakePlayerName.push_back("Smaphusk");
fakePlayerName.push_back("Athoem");
fakePlayerName.push_back("Rynul");
fakePlayerName.push_back("Enyer");
fakePlayerName.push_back("Ormos");
fakePlayerName.push_back("Tociru");
fakePlayerName.push_back("Smyeld");
fakePlayerName.push_back("Rynas");
fakePlayerName.push_back("Getisa");
fakePlayerName.push_back("Aise");
fakePlayerName.push_back("Inghon");
fakePlayerName.push_back("Chack");
fakePlayerName.push_back("Quemorest");
fakePlayerName.push_back("Echit");
fakePlayerName.push_back("Oschebel");
fakePlayerName.push_back("Tiad");
fakePlayerName.push_back("Estver");
fakePlayerName.push_back("Skel-moryg");
fakePlayerName.push_back("Itqua");
fakePlayerName.push_back("Heegden");
fakePlayerName.push_back("Untos");
fakePlayerName.push_back("Ryage");
fakePlayerName.push_back("Nobyz");
fakePlayerName.push_back("Rakan");
fakePlayerName.push_back("Usken");
fakePlayerName.push_back("Garorm");
fakePlayerName.push_back("Slony");
fakePlayerName.push_back("Atiao");
fakePlayerName.push_back("Inala");
fakePlayerName.push_back("Bekah");
fakePlayerName.push_back("Deathmor");
fakePlayerName.push_back("Angvgha");
fakePlayerName.push_back("Nystas");
fakePlayerName.push_back("Voros");
fakePlayerName.push_back("Hatrayold");
fakePlayerName.push_back("Rilald");
fakePlayerName.push_back("Driesar");
fakePlayerName.push_back("Tanhini");
fakePlayerName.push_back("Ackturu");
fakePlayerName.push_back("Athrisi");
fakePlayerName.push_back("Yosu");
fakePlayerName.push_back("Auskochae");
fakePlayerName.push_back("Koardris");
fakePlayerName.push_back("Eelma");
fakePlayerName.push_back("Endkel");
fakePlayerName.push_back("Angdan");
fakePlayerName.push_back("Tenag");
fakePlayerName.push_back("Issdtia");
fakePlayerName.push_back("Awtintia");
fakePlayerName.push_back("Athuntther");
fakePlayerName.push_back("Swurrlt");
fakePlayerName.push_back("Stokin");
fakePlayerName.push_back("Alen");
fakePlayerName.push_back("Ghaend");
fakePlayerName.push_back("Imagea");
fakePlayerName.push_back("Ighte");
fakePlayerName.push_back("Kelgtai");
fakePlayerName.push_back("Vorril");
fakePlayerName.push_back("Ranag");
fakePlayerName.push_back("Hinart");
fakePlayerName.push_back("Morer");
fakePlayerName.push_back("Snaightser");
fakePlayerName.push_back("Adchabel");
fakePlayerName.push_back("Erbanis");
fakePlayerName.push_back("Untris");
fakePlayerName.push_back("Rothem");
fakePlayerName.push_back("Aswage");
return fakePlayerName;
}
| 34.655283 | 155 | 0.743133 | plankes-projects |
d69336dcb3392e35b0fbca4410068700b664138c | 2,497 | cpp | C++ | cpp/graphs/shortestpaths/dijkstra_custom_heap.cpp | ayushbhatt2000/codelibrary | e1209b5e6195717d20127e12e908839c595c2f4c | [
"Unlicense"
] | 1,727 | 2015-01-01T18:32:37.000Z | 2022-03-28T05:56:03.000Z | cpp/graphs/shortestpaths/dijkstra_custom_heap.cpp | ayushbhatt2000/codelibrary | e1209b5e6195717d20127e12e908839c595c2f4c | [
"Unlicense"
] | 110 | 2015-05-03T10:23:18.000Z | 2021-07-31T22:44:39.000Z | cpp/graphs/shortestpaths/dijkstra_custom_heap.cpp | ayushbhatt2000/codelibrary | e1209b5e6195717d20127e12e908839c595c2f4c | [
"Unlicense"
] | 570 | 2015-01-01T10:17:11.000Z | 2022-03-31T22:23:46.000Z | #include <bits/stdc++.h>
using namespace std;
const int maxnodes = 200'000;
const int maxedges = 1000'000;
// graph
int edges;
int last[maxnodes], head[maxedges], previous[maxedges], len[maxedges];
int prio[maxnodes], pred[maxnodes];
void reset_graph() {
fill(last, last + maxnodes, -1);
edges = 0;
}
void add_edge(int u, int v, int length) {
head[edges] = v;
len[edges] = length;
previous[edges] = last[u];
last[u] = edges++;
}
// heap
int h[maxnodes];
int pos2Id[maxnodes];
int id2Pos[maxnodes];
int hsize;
void hswap(int i, int j) {
swap(h[i], h[j]);
swap(pos2Id[i], pos2Id[j]);
swap(id2Pos[pos2Id[i]], id2Pos[pos2Id[j]]);
}
void move_up(int pos) {
while (pos > 0) {
int parent = (pos - 1) >> 1;
if (h[pos] >= h[parent]) {
break;
}
hswap(pos, parent);
pos = parent;
}
}
void add(int id, int prio) {
h[hsize] = prio;
pos2Id[hsize] = id;
id2Pos[id] = hsize;
move_up(hsize++);
}
void increase_priority(int id, int prio) {
int pos = id2Pos[id];
h[pos] = prio;
move_up(pos);
}
void move_down(int pos) {
while (pos < (hsize >> 1)) {
int child = 2 * pos + 1;
if (child + 1 < hsize && h[child + 1] < h[child]) {
++child;
}
if (h[pos] <= h[child]) {
break;
}
hswap(pos, child);
pos = child;
}
}
int remove_min() {
int res = pos2Id[0];
int lastNode = h[--hsize];
if (hsize > 0) {
h[0] = lastNode;
int id = pos2Id[hsize];
id2Pos[id] = 0;
pos2Id[0] = id;
move_down(0);
}
return res;
}
void dijkstra(int s) {
fill(pred, pred + maxnodes, -1);
fill(prio, prio + maxnodes, numeric_limits<int>::max());
prio[s] = 0;
hsize = 0;
add(s, prio[s]);
while (hsize) {
int u = remove_min();
for (int e = last[u]; e >= 0; e = previous[e]) {
int v = head[e];
int nprio = prio[u] + len[e];
if (prio[v] > nprio) {
if (prio[v] == numeric_limits<int>::max())
add(v, nprio);
else
increase_priority(v, nprio);
prio[v] = nprio;
pred[v] = u;
}
}
}
}
int main() {
reset_graph();
add_edge(0, 1, 10);
add_edge(1, 2, -5);
add_edge(0, 2, 8);
dijkstra(0);
for (int i = 0; i < 3; i++)
cout << prio[i] << endl;
}
| 20.300813 | 70 | 0.486984 | ayushbhatt2000 |
d696e6279fd0a3a19099601c5578deb8b8c697cb | 8,111 | cpp | C++ | src/FFMPEG.cpp | dubhater/D2VWitch | b379384bb6aa7ee475ff7421b0ce5fee9e85d8b6 | [
"ISC"
] | 35 | 2016-01-15T08:00:10.000Z | 2021-12-22T19:49:49.000Z | src/FFMPEG.cpp | dubhater/D2VWitch | b379384bb6aa7ee475ff7421b0ce5fee9e85d8b6 | [
"ISC"
] | 11 | 2016-03-07T00:04:26.000Z | 2022-02-09T18:32:54.000Z | src/FFMPEG.cpp | dubhater/D2VWitch | b379384bb6aa7ee475ff7421b0ce5fee9e85d8b6 | [
"ISC"
] | 5 | 2016-01-18T12:50:13.000Z | 2021-05-01T09:12:02.000Z | /*
Copyright (c) 2016, John Smith
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
*/
#include "FFMPEG.h"
FFMPEG::FFMPEG()
: io_buffer(nullptr)
, fctx(nullptr)
, avcodec(nullptr)
, avctx(nullptr)
, parser(nullptr)
{ }
FFMPEG::~FFMPEG() {
cleanup();
}
const std::string &FFMPEG::getError() const {
return error;
}
bool FFMPEG::initFormat(FakeFile &fake_file) {
fctx = avformat_alloc_context();
if (!fctx) {
error = "Couldn't allocate AVFormatContext.";
return false;
}
size_t io_buffer_size = 32 * 1024;
io_buffer = (uint8_t *)av_malloc(io_buffer_size);
if (!io_buffer) {
error = "Couldn't allocate " + std::to_string(io_buffer_size) + " bytes for the AVIOContext.";
return false;
}
fctx->pb = avio_alloc_context(io_buffer, io_buffer_size, 0, &fake_file, FakeFile::readPacket, nullptr, FakeFile::seek);
if (!fctx->pb) {
error = "Couldn't allocate AVIOContext.";
return false;
}
// These two are both needed in order to properly detect the
// details of the audio streams from a certain DVD.
// Values obtained by trial and error. Increase them if needed.
// They add a bit of delay, but what can you do?
fctx->probesize = 10 * 1000 * 1000; // bytes
fctx->max_analyze_duration = 20 * 1000 * 1000; // microseconds
int ret = avformat_open_input(&fctx, fake_file[0].name.c_str(), nullptr, nullptr);
if (ret < 0) {
error = "avformat_open_input() failed: ";
char av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 };
if (!av_strerror(ret, av_error, AV_ERROR_MAX_STRING_SIZE))
error += av_error;
else
error += strerror(ret);
return false;
}
ret = avformat_find_stream_info(fctx, nullptr);
if (ret < 0) {
error = "avformat_find_stream_info() failed: ";
char av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 };
if (!av_strerror(ret, av_error, AV_ERROR_MAX_STRING_SIZE))
error += av_error;
else
error += strerror(ret);
return false;
}
return true;
}
bool FFMPEG::initVideoCodec(int stream_index) {
if (!fctx) {
error = "Must call initFormat before initVideoCodec.";
return false;
}
deinitVideoCodec();
AVCodecID video_codec_id = fctx->streams[stream_index]->codec->codec_id;
avcodec = avcodec_find_decoder(video_codec_id);
if (!avcodec) {
error = "Couldn't find decoder for ";
error += avcodec_get_name(video_codec_id);
return false;
}
avctx = avcodec_alloc_context3(avcodec);
if (!avctx) {
error = "Couldn't allocate AVCodecContext for the video decoder.";
return false;
}
if (avcodec_copy_context(avctx, fctx->streams[stream_index]->codec) < 0) {
error = "Couldn't copy video codec parameters.";
return false;
}
if (avcodec_open2(avctx, avcodec, nullptr) < 0) {
error = "Couldn't open AVCodecContext for the video decoder.";
return false;
}
parser = av_parser_init(video_codec_id);
if (!parser) {
error = "Couldn't initialise parser for ";
error += avcodec_get_name(video_codec_id);
return false;
}
parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
return true;
}
bool FFMPEG::initAudioCodec(int stream_index) {
if (codecIDRequiresWave64(fctx->streams[stream_index]->codec->codec_id)) {
AVCodecContext *ctx = avcodec_alloc_context3(nullptr);
if (!ctx) {
error = "Couldn't allocate AVCodecContext for an audio decoder.";
return false;
}
if (avcodec_copy_context(ctx, fctx->streams[stream_index]->codec) < 0) {
error = "Couldn't copy AVCodecContext for an audio decoder.";
return false;
}
AVCodec *audio_decoder = avcodec_find_decoder(fctx->streams[stream_index]->codec->codec_id);
if (!audio_decoder) {
error = "Couldn't find decoder for ";
error += avcodec_get_name(fctx->streams[stream_index]->codec->codec_id);
return false;
}
if (avcodec_open2(ctx, audio_decoder, nullptr) < 0) {
error = "Couldn't open AVCodecContext for an audio decoder.";
return false;
}
audio_ctx.insert({ fctx->streams[stream_index]->index, ctx });
}
return true;
}
bool FFMPEG::initAudioCodecs() {
for (unsigned i = 0; i < fctx->nb_streams; i++) {
if (!initAudioCodec(i))
return false;
}
return true;
}
void FFMPEG::deinitVideoCodec() {
if (parser) {
av_parser_close(parser);
parser = nullptr;
}
if (avctx) {
avcodec_close(avctx);
avcodec_free_context(&avctx);
}
}
void FFMPEG::cleanup() {
deinitVideoCodec();
if (fctx) {
avio_context_free(&fctx->pb);
avformat_close_input(&fctx);
}
for (auto it = audio_ctx.begin(); it != audio_ctx.end(); it++) {
avcodec_close(it->second);
avcodec_free_context(&it->second);
}
}
AVStream *FFMPEG::selectVideoStreamById(int id) {
for (unsigned i = 0; i < fctx->nb_streams; i++) {
if (fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
if (fctx->streams[i]->id == id) {
fctx->streams[i]->discard = AVDISCARD_DEFAULT;
return fctx->streams[i];
}
}
}
return nullptr;
}
AVStream *FFMPEG::selectFirstVideoStream() {
for (unsigned i = 0; i < fctx->nb_streams; i++) {
if (fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
fctx->streams[i]->discard = AVDISCARD_DEFAULT;
return fctx->streams[i];
}
}
return nullptr;
}
bool FFMPEG::selectAudioStreamsById(const std::vector<int> &audio_ids, std::vector<int> &missing_audio_ids) {
missing_audio_ids = audio_ids;
for (int j = missing_audio_ids.size() - 1; j >= 0; j--) {
for (unsigned i = 0; i < fctx->nb_streams; i++) {
if (fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
if (fctx->streams[i]->id == missing_audio_ids[j]) {
fctx->streams[i]->discard = AVDISCARD_DEFAULT;
missing_audio_ids.erase((missing_audio_ids.begin() + j));
break;
}
}
}
}
return !missing_audio_ids.size();
}
bool FFMPEG::selectAllAudioStreams() {
bool okay = false;
for (unsigned i = 0; i < fctx->nb_streams; i++) {
if (fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
fctx->streams[i]->discard = AVDISCARD_DEFAULT;
okay = true;
}
}
return okay;
}
void FFMPEG::deselectAllStreams() {
for (unsigned i = 0; i < fctx->nb_streams; i++)
fctx->streams[i]->discard = AVDISCARD_ALL;
}
bool FFMPEG::seek(int64_t position) {
int ret = avformat_seek_file(fctx, -1, INT64_MIN, position, INT64_MAX, AVSEEK_FLAG_BYTE);
if (ret < 0) {
error = "avformat_seek_file() failed to seek to position " + std::to_string(position) + ": ";
char av_error[AV_ERROR_MAX_STRING_SIZE] = { 0 };
if (!av_strerror(ret, av_error, AV_ERROR_MAX_STRING_SIZE))
error += av_error;
else
error += strerror(ret);
return false;
}
return true;
}
| 27.218121 | 123 | 0.613858 | dubhater |
d6988bac367ba60933ba1c7715d28c5e0b71c082 | 20,315 | cc | C++ | dcmtract/libsrc/trctrackset.cc | palmerc/dcmtk | 716832be091d138f3e119c47a4e1e243f5b261d3 | [
"Apache-2.0"
] | 4 | 2017-03-03T13:52:51.000Z | 2022-01-04T12:10:15.000Z | dcmtract/libsrc/trctrackset.cc | palmerc/dcmtk | 716832be091d138f3e119c47a4e1e243f5b261d3 | [
"Apache-2.0"
] | null | null | null | dcmtract/libsrc/trctrackset.cc | palmerc/dcmtk | 716832be091d138f3e119c47a4e1e243f5b261d3 | [
"Apache-2.0"
] | 5 | 2017-03-06T01:32:13.000Z | 2020-05-12T23:53:29.000Z | /*
*
* Copyright (C) 2016, Open Connections GmbH
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation are maintained by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmtract
*
* Author: Michael Onken
*
* Purpose: Class representing a Track Set from a Tractography Results IOD
*
*/
#include "dcmtk/config/osconfig.h"
#include "dcmtk/ofstd/ofutil.h"
#include "dcmtk/dcmdata/dcuid.h"
#include "dcmtk/dcmiod/iodutil.h"
#include "dcmtk/dcmtract/trctrackset.h"
#include "dcmtk/dcmtract/trctrack.h"
#include "dcmtk/dcmtract/trcmeasurement.h"
#include "dcmtk/dcmtract/trcstatistic.h"
#include "dcmtk/dcmtract/trctypes.h"
// default constructor (protected, instance creation via create() function)
TrcTrackSet::TrcTrackSet()
: IODComponent(),
m_Tracks(),
m_Anatomy("3", "1"),
m_Measurements(),
m_TrackStatistics(),
m_TrackSetStatistics(),
m_DiffusionAcquisitionCode(),
m_DiffusionModelCode(),
m_TrackingAlgorithmIdentification()
{
TrcTrackSet::resetRules();
}
void TrcTrackSet::resetRules()
{
// Set rules for the attributes within this component
getRules()->addRule(new IODRule(DCM_TrackSetNumber, "1","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_TrackSetLabel, "1","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_TrackSetDescription, "1","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_TrackSetAnatomicalTypeCodeSequence, "1","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_TrackSequence, "1-n","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_RecommendedDisplayCIELabValue, "3","1C", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_RecommendedLineThickness, "1","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_MeasurementsSequence, "1-n","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_TrackStatisticsSequence, "1-n","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_TrackSetStatisticsSequence, "1-n","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_DiffusionAcquisitionCodeSequence, "1","3", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_DiffusionModelCodeSequence, "1","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
getRules()->addRule(new IODRule(DCM_TrackingAlgorithmIdentificationSequence, "1-n","1", getName(), DcmIODTypes::IE_INSTANCE), OFTrue);
}
OFCondition TrcTrackSet::create(const OFString& trackSetLabel,
const OFString& trackSetDescription,
const CodeWithModifiers& trackSetAnatomy,
const CodeSequenceMacro& trackSetDiffusionModelCode,
const CodeSequenceMacro& trackSetAlgorithmIdentification,
TrcTrackSet*& trackSet)
{
// Track Set Number is set within TrcTractographyResults::addTrackSet()
trackSet = new TrcTrackSet();
if (!trackSet)
return EC_MemoryExhausted;
OFCondition result = trackSet->setTrackSetLabel(trackSetLabel);
if (result.good()) result = trackSet->setTrackSetDescription(trackSetDescription);
if (result.good())
{
result = OFconst_cast(CodeWithModifiers*, &trackSetAnatomy)->check();
if (result.good())
{
trackSet->m_Anatomy = trackSetAnatomy;
}
}
if (result.good())
{
result = OFconst_cast(CodeSequenceMacro*, &trackSetDiffusionModelCode)->check();
if (result.good())
{
trackSet->m_DiffusionModelCode = trackSetDiffusionModelCode;
}
}
if (result.good())
{
result = OFconst_cast(CodeSequenceMacro*, &trackSetAlgorithmIdentification)->check();
if (result.good())
{
// add deep copy (via IODComponent) of input param
trackSet->m_TrackingAlgorithmIdentification.push_back(new CodeSequenceMacro(trackSetAlgorithmIdentification));
}
}
return result;
}
OFCondition TrcTrackSet::read(DcmItem& source,
const OFBool clearOldData)
{
if (clearOldData)
this->clearData();
// Read as much as possible. In order to return success at minimum the tracks
// must be readable.
IODComponent::read(source, OFFalse /* we cleared data before */);
DcmIODUtil::readSingleItem(source, DCM_TrackSetAnatomicalTypeCodeSequence, m_Anatomy, getRules()->getByTag(DCM_TrackSetAnatomicalTypeCodeSequence));
DcmIODUtil::readSingleItem(source, DCM_DiffusionAcquisitionCodeSequence, m_DiffusionAcquisitionCode, getRules()->getByTag(DCM_DiffusionAcquisitionCodeSequence));
DcmIODUtil::readSingleItem(source, DCM_DiffusionModelCodeSequence, m_DiffusionModelCode, getRules()->getByTag(DCM_DiffusionModelCodeSequence));
DcmIODUtil::readSubSequence(source, DCM_TrackingAlgorithmIdentificationSequence, m_TrackingAlgorithmIdentification, getRules()->getByTag(DCM_TrackingAlgorithmIdentificationSequence));
readTrackStatistics(source);
readTrackSetStatistics(source);
OFCondition result = readTracks(source);
DCMTRACT_DEBUG("Found " << m_Tracks.size() << " Tracks in Track Set");
if (result.good())
{
readMeasurements(source);
}
else
{
DCMTRACT_ERROR("Could not read tracks from Track Set");
}
return result;
}
OFCondition TrcTrackSet::write(DcmItem& destination)
{
OFCondition result;
DcmIODUtil::writeSingleItem(result, DCM_TrackSetAnatomicalTypeCodeSequence, m_Anatomy, getData(), getRules()->getByTag(DCM_TrackSetAnatomicalTypeCodeSequence));
DcmIODUtil::writeSingleItem(result, DCM_DiffusionAcquisitionCodeSequence, m_DiffusionAcquisitionCode, getData(), getRules()->getByTag(DCM_DiffusionAcquisitionCodeSequence));
DcmIODUtil::writeSingleItem(result, DCM_DiffusionModelCodeSequence, m_DiffusionModelCode, getData(), getRules()->getByTag(DCM_DiffusionModelCodeSequence));
DcmIODUtil::writeSubSequence(result, DCM_TrackingAlgorithmIdentificationSequence, m_TrackingAlgorithmIdentification, getData(), getRules()->getByTag(DCM_TrackingAlgorithmIdentificationSequence));
writeTrackStatistics(result, getData());
writeTrackSetStatistics(result, getData());
writeMeasurements(result, getData());
writeTracks(result, getData());
if (result.good()) result = IODComponent::write(destination);
return result;
}
const OFVector<TrcTrack *>& TrcTrackSet::getTracks()
{
return m_Tracks;
}
void TrcTrackSet::clearData()
{
m_Anatomy.clearData();
DcmIODUtil::freeContainer(m_Tracks);
DcmIODUtil::freeContainer(m_Measurements);
DcmIODUtil::freeContainer(m_TrackStatistics);
DcmIODUtil::freeContainer(m_TrackSetStatistics);
DcmIODUtil::freeContainer(m_TrackingAlgorithmIdentification);
m_DiffusionAcquisitionCode.clearData();
m_DiffusionModelCode.clearData();
IODComponent::clearData();
}
TrcTrackSet::~TrcTrackSet()
{
clearData();
}
OFString TrcTrackSet::getName() const
{
return "TrackSetSequenceItem";
}
void TrcTrackSet::inventMissing()
{
IODComponent::inventMissing();
// Note: We could also add code to automatic default coloring
}
OFCondition TrcTrackSet::getTrackSetNumber(Uint16& value,
const unsigned long pos) const
{
return m_Item->findAndGetUint16(DCM_TrackSetNumber, value, pos);
}
OFCondition TrcTrackSet::getTrackSetLabel(OFString& value,
const long signed int pos) const
{
return DcmIODUtil::getStringValueFromItem(DCM_TrackSetLabel, *m_Item, value, pos);
}
OFCondition TrcTrackSet::getTrackSetDescription(OFString& value,
const long signed int pos) const
{
return DcmIODUtil::getStringValueFromItem(DCM_TrackSetDescription, *m_Item, value, pos);
}
OFCondition TrcTrackSet::getRecommendedDisplayCIELabValue(Uint16& L,
Uint16& a,
Uint16& b)
{
Uint16 myL, mya, myb;
myL = mya = myb = 0;
DcmElement *elem = NULL;
if (m_Item->findAndGetElement(DCM_RecommendedDisplayCIELabValue, elem).good() )
{
if (elem->getUint16(myL, 0).good())
{
L = myL;
if (elem->getUint16(mya, 1).good())
{
a = mya;
if (elem->getUint16(myb, 2).good())
{
b = myb;
return EC_Normal;
}
}
}
}
return IOD_EC_InvalidElementValue;
}
OFCondition TrcTrackSet::getRecommendedLineThickness(Float32& value,
const long unsigned int pos)
{
return m_Item->findAndGetFloat32(DCM_RecommendedLineThickness, value, pos);
}
OFCondition TrcTrackSet::getLaterality(TrcTypes::E_TrackSetLaterality& laterality)
{
OFCondition result;
OFString value, designator;
CodeSequenceMacro* mod = m_Anatomy.getModifier(0);
if (mod)
{
mod->getCodingSchemeDesignator(designator);
mod->getCodingSchemeDesignator(value);
if (value.empty() && designator.empty())
{
laterality = TrcTypes::LAT_UNKNOWN;
}
else if (designator == "SRT") // all laterality codes are from SNOMED
{
if (value == "G-A100")
{
laterality = TrcTypes::LAT_RIGHT;
}
else if (value == "G-A101")
{
laterality = TrcTypes::LAT_LEFT;
}
else if (value == "G-A102")
{
laterality = TrcTypes::LAT_RIGHT_AND_LEFT;
}
else if (value == "G-A103")
{
laterality = TrcTypes::LAT_UNILATERAL;
}
else
{
laterality = TrcTypes::LAT_ERROR;
result = IOD_EC_InvalidLaterality;
}
}
else
{
laterality = TrcTypes::LAT_ERROR;
result = IOD_EC_InvalidLaterality;
}
}
else
{
laterality = TrcTypes::LAT_UNKNOWN;
}
return result;
}
CodeSequenceMacro& TrcTrackSet::getDiffusionAcquisitionCode()
{
return m_DiffusionAcquisitionCode;
}
CodeSequenceMacro& TrcTrackSet::getDiffusionModelCode()
{
return m_DiffusionModelCode;
}
OFVector<CodeSequenceMacro*>& TrcTrackSet::getTrackingAlgorithmIdentification()
{
return m_TrackingAlgorithmIdentification;
}
CodeWithModifiers& TrcTrackSet::getTrackSetAnatomy()
{
return m_Anatomy;
}
const OFVector< TrcTrackSetStatistic* >& TrcTrackSet::getTrackSetStatistics()
{
return m_TrackSetStatistics;
}
const OFVector< TrcTracksStatistic* >& TrcTrackSet::getTrackStatistics()
{
return m_TrackStatistics;
}
size_t TrcTrackSet::getNumberOfTracks()
{
return m_Tracks.size();
}
size_t TrcTrackSet::getNumberOfTrackSetStatistics()
{
return m_TrackSetStatistics.size();
}
size_t TrcTrackSet::getNumberOfTrackStatistics()
{
return m_TrackStatistics.size();
}
size_t TrcTrackSet::getNumberOfMeasurements()
{
return m_Measurements.size();
}
OFCondition TrcTrackSet::findMeasurementsByType(const CodeSequenceMacro& type,
OFVector< size_t >& measurementNumbers)
{
OFVector<TrcMeasurement*>::const_iterator it = m_Measurements.begin();
for (size_t m = 0; it != m_Measurements.end(); m++)
{
if ( (*it)->getType().compare(type) == 0 )
{
measurementNumbers.push_back(m);
}
it++;
}
return EC_Normal;
}
OFCondition TrcTrackSet::getMeasurement(const size_t measurementIndex,
const TrcMeasurement*& measurement)
{
if (measurementIndex > m_Measurements.size() - 1)
{
return TRC_EC_NoSuchMeasurement;
}
measurement = m_Measurements[measurementIndex];
return EC_Normal;
}
void TrcTrackSet::getMeasurementInfos(OFVector< OFPair< CodeSequenceMacro, CodeSequenceMacro > >& typesAndUnits)
{
OFVector<TrcMeasurement*>::const_iterator it = m_Measurements.begin();
while (it != m_Measurements.end())
{
typesAndUnits.push_back( OFMake_pair( (*it)->getType(), (*it)->getUnits() ) );
it++;
}
}
OFCondition TrcTrackSet::addTrack(const Float32* pointData,
const size_t numPoints,
const Uint16* recommendedCIELabColors,
const size_t numColors,
TrcTrack*& result)
{
OFCondition cond = TrcTrack::create(pointData, numPoints, recommendedCIELabColors, numColors, result);
if (cond.good())
{
m_Tracks.push_back(result);
}
return cond;
}
OFCondition TrcTrackSet::addMeasurement(const CodeSequenceMacro& measurementCode,
const CodeSequenceMacro& measurementUnitCodes,
TrcMeasurement*& measurement)
{
OFCondition result = TrcMeasurement::create(measurementCode, measurementUnitCodes, measurement);
if (result.good())
{
m_Measurements.push_back(measurement);
}
return result;
}
OFCondition TrcTrackSet::addTrackStatistics(const CodeSequenceMacro& typeCode,
const CodeSequenceMacro& typeModifierCode,
const CodeSequenceMacro& unitsCode,
const Float32* values,
const size_t numValues,
TrcTracksStatistic*& statistic)
{
statistic = new TrcTracksStatistic();
if (!statistic)
return EC_MemoryExhausted;
if (numValues != m_Tracks.size())
{
DCMTRACT_ERROR("There must be as many track statistic values as number of tracks (" << m_Tracks.size() << ")");
return TRC_EC_InvalidStatisticData;
}
OFCondition result = statistic->set(typeCode, typeModifierCode, unitsCode, values, numValues);
if (result.good())
{
m_TrackStatistics.push_back(statistic);
}
else
{
delete statistic;
statistic = NULL;
}
return result;
}
OFCondition TrcTrackSet::addTrackSetStatistic(const CodeSequenceMacro& typeCode,
const CodeSequenceMacro& typeModifierCode,
const CodeSequenceMacro& unitsCode,
const Float64 value,
TrcTrackSetStatistic*& statistic)
{
statistic = new TrcTrackSetStatistic();
if (!statistic)
return EC_MemoryExhausted;
OFCondition result = statistic->set(typeCode, typeModifierCode, unitsCode, value);
if (result.good())
{
m_TrackSetStatistics.push_back(statistic);
}
else
{
delete statistic;
statistic = NULL;
}
return result;
}
OFCondition TrcTrackSet::setTrackSetLabel(const OFString& value,
const OFBool checkValue)
{
OFCondition result = (checkValue) ? DcmLongString::checkStringValue(value, "1") : EC_Normal;
if (result.good())
result = m_Item->putAndInsertOFStringArray(DCM_TrackSetLabel, value);
return result;
}
OFCondition TrcTrackSet::setTrackSetDescription(const OFString& value,
const OFBool checkValue)
{
OFCondition result = (checkValue) ? DcmUnlimitedText::checkStringValue(value, "1") : EC_Normal;
if (result.good())
result = m_Item->putAndInsertOFStringArray(DCM_TrackSetDescription, value);
return result;
}
OFCondition TrcTrackSet::setRecommendedDisplayCIELabValue(const Uint16 L,
const Uint16 a,
const Uint16 b)
{
DcmElement* elem = newDicomElement(DCM_RecommendedDisplayCIELabValue);
if (elem)
{
if (elem->putUint16(L, 0).good())
{
if (elem->putUint16(a, 1).good())
{
if (elem->putUint16(b, 2).good())
{
if (m_Item->insert(elem, OFTrue /* replace old */).good())
{
return EC_Normal;
}
}
}
}
}
else
{
return EC_MemoryExhausted;
}
return EC_InternalError;
}
OFCondition TrcTrackSet::setRecommendedLineThickness(const Float32& value,
const OFBool checkValue)
{
(void)checkValue;
return m_Item->putAndInsertFloat32(DCM_RecommendedLineThickness, value, 0);
}
OFCondition TrcTrackSet::readTracks(DcmItem& source)
{
return DcmIODUtil::readSubSequence(source, DCM_TrackSequence, m_Tracks, getRules()->getByTag(DCM_TrackSequence));
}
OFCondition TrcTrackSet::readMeasurements(DcmItem& source)
{
DcmIODUtil::readSubSequence(source, DCM_MeasurementsSequence, m_Measurements, getRules()->getByTag(DCM_MeasurementsSequence));
if (checkMeasurements().bad())
{
DCMTRACT_WARN("Ignoring missing or superfluous Measurements");
}
return EC_Normal;
}
OFCondition TrcTrackSet::setLaterality(const TrcTypes::E_TrackSetLaterality value,
const OFBool checkValue)
{
(void)checkValue;
CodeSequenceMacro anatomy;
switch(value)
{
case TrcTypes::LAT_RIGHT: anatomy.set("G-A100", "SRT", "Right"); break;
case TrcTypes::LAT_LEFT: anatomy.set("G-A101", "SRT", "Left"); break;
case TrcTypes::LAT_RIGHT_AND_LEFT: anatomy.set("G-A102", "SRT", "Right and left"); break;
case TrcTypes::LAT_UNILATERAL: anatomy.set("G-A103", "SRT", "Unilateral"); break;
default: return IOD_EC_InvalidLaterality;
}
CodeSequenceMacro* mod = m_Anatomy.getModifier(0);
if (!mod)
{
mod = new CodeSequenceMacro();
if (!mod)
{
return EC_MemoryExhausted;
}
*mod = anatomy;
m_Anatomy.addModifier(*mod);
}
else
{
*mod = anatomy;
}
return EC_Normal;;
}
OFCondition TrcTrackSet::checkMeasurements()
{
size_t numTracks = m_Tracks.size();
for (size_t i = 0; i < m_Measurements.size(); i++)
{
TrcMeasurement *m = m_Measurements[i];
size_t numEntries = m->getValues().size();
if (numEntries < numTracks)
{
DCMTRACT_WARN("Measurement #" << i << " misses data for " << numTracks - numEntries << " tracks");
return TRC_EC_MeasurementDataMissing;
}
else if (numEntries > numTracks)
{
DCMTRACT_WARN("Measurement #" << i << " has data for " << numEntries - numTracks << " too many tracks");
return TRC_EC_MeasurementDataMissing;
}
}
return EC_Normal;
}
OFCondition TrcTrackSet::readTrackSetStatistics(DcmItem& source)
{
(void)source;
DcmIODUtil::readSubSequence(source, DCM_TrackSetStatisticsSequence, m_TrackSetStatistics, m_Rules->getByTag(DCM_TrackSetStatisticsSequence));
return EC_Normal;
}
OFCondition TrcTrackSet::readTrackStatistics(DcmItem& source)
{
(void)source;
DcmIODUtil::readSubSequence(source, DCM_TrackStatisticsSequence, m_TrackStatistics, m_Rules->getByTag(DCM_TrackStatisticsSequence));
return EC_Normal;
}
OFCondition TrcTrackSet::writeTracks(OFCondition& result,
DcmItem& destination)
{
if (result.good())
{
DcmIODUtil::writeSubSequence(result, DCM_TrackSequence, m_Tracks, destination, getRules()->getByTag(DCM_TrackSequence));
}
return result;
}
OFCondition TrcTrackSet::writeMeasurements(OFCondition& result,
DcmItem& destination)
{
if (result.good())
{
result = checkMeasurements();
if (result.bad())
{
DCMTRACT_ERROR("Measurements have too much or to less data");
return result;
}
DcmIODUtil::writeSubSequence(result, DCM_MeasurementsSequence, m_Measurements, destination, getRules()->getByTag(DCM_MeasurementsSequence));
}
return result;
}
void TrcTrackSet::writeTrackSetStatistics(OFCondition& result,
DcmItem& destination)
{
DcmIODUtil::writeSubSequence(result, DCM_TrackSetStatisticsSequence, m_TrackSetStatistics, destination, m_Rules->getByTag(DCM_TrackSetStatisticsSequence));
}
void TrcTrackSet::writeTrackStatistics(OFCondition& result,
DcmItem& destination)
{
DcmIODUtil::writeSubSequence(result, DCM_TrackStatisticsSequence, m_TrackStatistics, destination, m_Rules->getByTag(DCM_TrackStatisticsSequence));
}
| 30.007386 | 197 | 0.673837 | palmerc |
d69a69a6afaa5dde964cdd4dd8712faedac7e8e2 | 513 | cpp | C++ | C++/FuzzBuzz.cpp | RDxR10/Hacktoberfest-2020-FizzBuzz | c9a8e3a0ac1ff9886c013a6b5628b7f64eb0d342 | [
"Unlicense"
] | 80 | 2020-10-01T00:32:34.000Z | 2021-01-08T21:56:09.000Z | C++/FuzzBuzz.cpp | RDxR10/Hacktoberfest-2020-FizzBuzz | c9a8e3a0ac1ff9886c013a6b5628b7f64eb0d342 | [
"Unlicense"
] | 672 | 2020-09-30T22:53:47.000Z | 2020-11-01T12:39:59.000Z | C++/FuzzBuzz.cpp | RDxR10/Hacktoberfest-2020-FizzBuzz | c9a8e3a0ac1ff9886c013a6b5628b7f64eb0d342 | [
"Unlicense"
] | 618 | 2020-09-30T22:21:12.000Z | 2020-10-31T21:28:06.000Z | // Fuzz Buzz
// Author: Sewern Kaminski
#include <array>
#include <iostream>
#include <numeric>
using namespace std;
int main() {
cout << "Fizz buzz" << endl;
auto print = []( int v ) {
auto f = !(v % 3);
auto b = !(v % 5);
cout << ( f && b ? "fizzbuzz" :
f ? "fizz" :
b ? "buzz" : to_string( v )) << endl;
};
array<int,100> tab;
iota ( tab.begin(), tab.end(), 1 );
for_each ( tab.begin(), tab.end(), print );
}
| 19 | 60 | 0.45614 | RDxR10 |
d69bd4e87451980d1397581d4bd8a84cb9ad90ae | 5,915 | cpp | C++ | src/bazel/bazel.cpp | cppan/cppan | b4bbdf5e56f9d237f2820301152b7024ca10907b | [
"Apache-2.0"
] | 117 | 2016-03-14T08:26:32.000Z | 2021-12-09T10:17:34.000Z | src/bazel/bazel.cpp | fuyanbin/cppan | 77e0f8d6f3e372cd191e9b3af1704403f824c0de | [
"Apache-2.0"
] | 55 | 2016-06-30T10:01:27.000Z | 2019-08-10T19:18:37.000Z | src/bazel/bazel.cpp | fuyanbin/cppan | 77e0f8d6f3e372cd191e9b3af1704403f824c0de | [
"Apache-2.0"
] | 25 | 2017-04-21T06:38:17.000Z | 2022-02-02T05:02:25.000Z | /*
* Copyright (C) 2016-2017, Egor Pugin
*
* 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 "bazel.h"
#include "driver.h"
#include "../common/yaml.h"
#include <boost/algorithm/string.hpp>
#include <primitives/filesystem.h>
#include <pystring.h>
#include <algorithm>
#include <regex>
namespace {
void trimQuotes(std::string &s)
{
if (s.empty())
return;
if (s.front() == '\"')
s = s.substr(1);
if (s.empty())
return;
if (s.back() == '\"')
s = s.substr(0, s.size() - 1);
//s = s.substr(s.find_first_not_of("\""));
//s = s.substr(0, s.find_last_not_of("\"") + 1);
}
std::string prepare_project_name(const std::string &s)
{
std::string t = s;
std::replace(t.begin(), t.end(), '-', '_');
std::replace(t.begin(), t.end(), '+', 'p');
return t;
}
}
namespace bazel
{
void Parameter::trimQuotes()
{
::trimQuotes(name);
Values vls;
for (auto &v : values)
{
auto s = v;
::trimQuotes(s);
vls.insert(s);
}
values = vls;
}
void Function::trimQuotes()
{
::trimQuotes(name);
for (auto &p : parameters)
p.trimQuotes();
}
void File::trimQuotes()
{
for (auto &f : functions)
f.trimQuotes();
}
Values File::getFiles(const Name &name, const std::string &bazel_target_function)
{
Values values;
for (auto &f : functions)
{
if (!(
pystring::endswith(f.name, "cc_library") ||
pystring::endswith(f.name, "cc_binary") ||
pystring::endswith(f.name, bazel_target_function)
))
continue;
auto i = std::find_if(f.parameters.begin(), f.parameters.end(), [](const auto &p)
{
return "name" == p.name;
});
if (i == f.parameters.end() || i->values.empty() ||
(prepare_project_name(*i->values.begin()) != name && *i->values.begin() != name))
continue;
for (auto &n : { "hdrs", "public_hdrs" })
{
i = std::find_if(f.parameters.begin(), f.parameters.end(), [&n](const auto &p)
{
return p.name == n;
});
if (i != f.parameters.end())
{
// check if we has a variable
for (auto &v : i->values)
{
auto p = parameters.find(v);
if (p != parameters.end())
values.insert(p->second.values.begin(), p->second.values.end());
else
values.insert(i->values.begin(), i->values.end());
}
}
}
i = std::find_if(f.parameters.begin(), f.parameters.end(), [](const auto &p)
{
return "srcs" == p.name;
});
if (i != f.parameters.end())
{
// check if we has a variable
for (auto &v : i->values)
{
auto p = parameters.find(v);
if (p != parameters.end())
values.insert(p->second.values.begin(), p->second.values.end());
else
values.insert(i->values.begin(), i->values.end());
}
}
}
return values;
}
File parse(const std::string &s)
{
BazelParserDriver pd;
pd.parse(s);
pd.bazel_file.trimQuotes();
return pd.bazel_file;
}
} // namespace bazel
void process_bazel(const path &p, const std::string &libname = "cc_library", const std::string &binname = "cc_binary")
{
auto prepare_dep_name = [](auto s)
{
//if (s.find("//") == 0)
//return std::string();
prepare_project_name(s);
boost::replace_all(s, ":", "");
boost::replace_all(s, "+", "p");
return s;
};
auto b = read_file(p);
auto file = bazel::parse(b);
yaml root;
auto projects = root["projects"];
for (auto &f : file.functions)
{
enum
{
unk,
lib,
bin,
};
int type = unk;
if (pystring::endswith(f.name, libname))
type = lib;
else if (pystring::endswith(f.name, binname))
type = bin;
else
continue;
auto i = std::find_if(f.parameters.begin(), f.parameters.end(), [](const auto &p)
{
return "name" == p.name;
});
if (i == f.parameters.end() || i->values.empty())
continue;
auto pname = prepare_project_name(*i->values.begin());
auto project = projects[pname];
if (type == lib)
project["type"] = "lib";
project["import_from_bazel"] = true;
project["bazel_target_name"] = *i->values.begin();
project["bazel_target_function"] = type == lib ? libname : binname;
for (auto &n : { "deps", "external_deps" })
{
i = std::find_if(f.parameters.begin(), f.parameters.end(), [&n](const auto &p)
{
return n == p.name;
});
if (!(i == f.parameters.end() || i->values.empty()))
{
for (auto &d : i->values)
{
auto d2 = prepare_dep_name(d);
if (!d2.empty())
project["dependencies"].push_back(d2);
}
}
}
}
std::cout << dump_yaml_config(root);
}
| 26.524664 | 118 | 0.503804 | cppan |
d69f2607ef62aa2a02a8735ddcd4e553543ac26f | 7,507 | hpp | C++ | src/providers/gdrive/include/jconer/value.hpp | webosose/com.webos.service.storageaccess | 9d1c912c5654ff9df33206d0d367359b04e03e22 | [
"Apache-2.0"
] | null | null | null | src/providers/gdrive/include/jconer/value.hpp | webosose/com.webos.service.storageaccess | 9d1c912c5654ff9df33206d0d367359b04e03e22 | [
"Apache-2.0"
] | 1 | 2021-06-22T22:18:47.000Z | 2021-06-22T22:18:47.000Z | src/providers/gdrive/include/jconer/value.hpp | webosose/com.webos.service.storageaccess | 9d1c912c5654ff9df33206d0d367359b04e03e22 | [
"Apache-2.0"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2014 Justin (Jianfeng) Lin
//
// 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 __JCONER_VALUE_HPP__
#define __JCONER_VALUE_HPP__
#include <string>
#include <map>
#include <vector>
#include "jconer/allocator.hpp"
#include "common/logging.hpp"
#define NULL_VALUE 0
namespace JCONER {
typedef int NULL_TYPE;
enum ValueType {
VT_OBJECT = 0,
VT_ARRAY,
VT_INTEGER,
VT_STRING,
VT_REAL,
VT_TRUE,
VT_FALSE,
VT_NULL
};
enum InsertError {
IE_SUC = 0,
IE_SELF,
IE_NULL
};
class JValue {
public:
JValue(ValueType type);
inline ValueType type() { return _type; }
virtual ~JValue();
virtual JValue* deepcopy() = 0;
virtual void printout() = 0;
static inline bool isString(const JValue* value) { return value->_type == VT_STRING;}
static inline bool isInteger(const JValue* value) { return value->_type == VT_INTEGER;}
static inline bool isReal(const JValue* value) { return value->_type == VT_REAL;}
static inline bool isTrue(const JValue* value) { return value->_type == VT_TRUE;}
static inline bool isFalse(const JValue* value) { return value->_type == VT_FALSE;}
static inline bool isNull(const JValue* value) { return value->_type == VT_NULL;}
static inline bool isObject(const JValue* value) { return value->_type == VT_OBJECT;}
static inline bool isArray(const JValue* value) { return value->_type == VT_ARRAY;}
inline bool isString() { return _type == VT_STRING; }
inline bool isInteger() { return _type == VT_INTEGER; }
inline bool isReal() { return _type == VT_REAL; }
inline bool isTrue() { return _type == VT_TRUE; }
inline bool isFalse() { return _type == VT_FALSE; }
inline bool isNull() { return _type == VT_NULL;}
inline bool isObject() { return _type == VT_OBJECT; }
inline bool isArray() { return _type == VT_ARRAY; }
std::string getString();
long getInteger();
bool getBool();
double getReal();
JValue* get(size_t i);
JValue* get(std::string key);
int size();
std::vector<std::string> getKeys();
bool contain(std::string key);
#if false
void* operator new(size_t size) throw (std::bad_alloc) {
return allocate(size);
}
void operator delete(void* ptr) throw () {
}
#endif
protected:
ValueType _type;
};
class JNull : public JValue {
public:
static JNull* getInstance() {
return &_instance;
}
inline NULL_TYPE getValue() { return NULL_VALUE; }
void printout();
JValue* deepcopy();
private:
JNull();
static JNull _instance;
};
class JInt : public JValue {
public:
JInt(const long value);
inline long getValue() { return _value; }
void printout();
JValue* deepcopy();
private:
long _value;
};
class JReal : public JValue {
public:
JReal(const double value);
inline double getValue() { return _value; }
void printout();
JValue* deepcopy();
private:
double _value;
};
class JString : public JValue {
public:
JString(const std::string value);
JString(const char* str);
inline std::string getValue() { return _value; }
std::string getAsciiValue();
void printout();
JValue* deepcopy();
private:
std::string _value;
};
class JTrue : public JValue {
public:
static JTrue* getInstance() {
return &_instance;
}
inline bool getValue() { return true; }
void printout();
JValue* deepcopy();
JTrue();
private:
//JTrue();
static JTrue _instance;
};
class JFalse : public JValue {
public:
static JFalse* getInstance() {
return &_instance;
}
inline bool getValue() { return true; }
void printout();
JValue* deepcopy();
JFalse();
private:
//JFalse();
static JFalse _instance;
};
class JArray : public JValue {
public:
JArray();
JArray(const std::vector<JValue*>& array);
~JArray();
inline std::vector<JValue*> getArray() { return _array; }
inline int size() { return _array.size(); }
void printout();
inline JValue* get(size_t i) {
if (i < _array.size())
return _array[i];
else
return NULL;
}
InsertError append(JValue* element);
void append(const long value);
void append(const size_t value);
void append(const int value);
void append(const std::string value);
void append(const char* str);
void append(const bool value);
void append(const double value);
void appendNull();
JValue* pop_back();
JValue* pop(size_t i);
JValue* deepcopy();
private:
std::vector<JValue*> _array;
};
class JObject : public JValue {
public:
JObject();
JObject(const std::map<std::string, JValue*>& object);
~JObject();
inline std::map<std::string, JValue*> getObject() { return _object; }
inline int size() { return _object.size(); }
void printout();
inline bool contain(std::string key) {
if (_object.find(key) != _object.end()) {
return true;
} else {
return false;
}
}
inline JValue* get(std::string key) {
if (_object.find(key) != _object.end()) {
return _object[key];
} else {
return NULL;
}
}
std::vector<std::string> getKeys();
InsertError put(const std::string, JValue*);
void put(const std::string, const long);
void put(const std::string, const size_t);
void put(const std::string, const int);
void put(const std::string, const std::string);
void put(const std::string, const char*);
void put(const std::string, const bool);
void put(const std::string, const double);
void put(const std::string);
JValue* pop(std::string key);
JValue* deepcopy();
private:
std::map<std::string, JValue*> _object;
};
}
#endif
| 29.439216 | 95 | 0.597309 | webosose |
d6a3c92878e07465c39e9ffbe2242c9e33961b52 | 1,383 | cpp | C++ | lang/C++/vector-products.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 5 | 2021-01-29T20:08:05.000Z | 2022-03-22T06:16:05.000Z | lang/C++/vector-products.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C++/vector-products.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2018-11-09T22:08:40.000Z | 2018-11-09T22:08:40.000Z | #include <iostream>
template< class T >
class D3Vector {
template< class U >
friend std::ostream & operator<<( std::ostream & , const D3Vector<U> & ) ;
public :
D3Vector( T a , T b , T c ) {
x = a ;
y = b ;
z = c ;
}
T dotproduct ( const D3Vector & rhs ) {
T scalar = x * rhs.x + y * rhs.y + z * rhs.z ;
return scalar ;
}
D3Vector crossproduct ( const D3Vector & rhs ) {
T a = y * rhs.z - z * rhs.y ;
T b = z * rhs.x - x * rhs.z ;
T c = x * rhs.y - y * rhs.x ;
D3Vector product( a , b , c ) ;
return product ;
}
D3Vector triplevec( D3Vector & a , D3Vector & b ) {
return crossproduct ( a.crossproduct( b ) ) ;
}
T triplescal( D3Vector & a, D3Vector & b ) {
return dotproduct( a.crossproduct( b ) ) ;
}
private :
T x , y , z ;
} ;
template< class T >
std::ostream & operator<< ( std::ostream & os , const D3Vector<T> & vec ) {
os << "( " << vec.x << " , " << vec.y << " , " << vec.z << " )" ;
return os ;
}
int main( ) {
D3Vector<int> a( 3 , 4 , 5 ) , b ( 4 , 3 , 5 ) , c( -5 , -12 , -13 ) ;
std::cout << "a . b : " << a.dotproduct( b ) << "\n" ;
std::cout << "a x b : " << a.crossproduct( b ) << "\n" ;
std::cout << "a . b x c : " << a.triplescal( b , c ) << "\n" ;
std::cout << "a x b x c : " << a.triplevec( b , c ) << "\n" ;
return 0 ;
}
| 25.145455 | 75 | 0.469993 | ethansaxenian |
d6a41b8b757b51b953a443e92e18313f1b5cc65a | 1,543 | cpp | C++ | util/generic/function_ut.cpp | HeyLey/catboost | f472aed90604ebe727537d9d4a37147985e10ec2 | [
"Apache-2.0"
] | 2 | 2019-07-10T10:49:09.000Z | 2020-06-19T11:40:04.000Z | util/generic/function_ut.cpp | HeyLey/catboost | f472aed90604ebe727537d9d4a37147985e10ec2 | [
"Apache-2.0"
] | 6 | 2020-02-18T22:12:29.000Z | 2020-02-18T22:31:26.000Z | util/generic/function_ut.cpp | HeyLey/catboost | f472aed90604ebe727537d9d4a37147985e10ec2 | [
"Apache-2.0"
] | 1 | 2019-07-01T20:59:01.000Z | 2019-07-01T20:59:01.000Z | #include "function.h"
#include "typetraits.h"
#include <library/unittest/registar.h>
Y_UNIT_TEST_SUITE(TestFunctionSignature) {
int FF(double x) {
return (int)x;
}
int FFF(double x, char xx) {
return (int)x + (int)xx;
}
struct A {
int F(double x) {
return FF(x);
}
};
Y_UNIT_TEST(TestPlainFunc) {
UNIT_ASSERT_TYPES_EQUAL(TFunctionSignature<decltype(FF)>, decltype(FF));
}
Y_UNIT_TEST(TestMethod) {
UNIT_ASSERT_TYPES_EQUAL(TFunctionSignature<decltype(&A::F)>, decltype(FF));
}
Y_UNIT_TEST(TestLambda) {
auto f = [](double x) -> int {
return FF(x);
};
UNIT_ASSERT_TYPES_EQUAL(TFunctionSignature<decltype(f)>, decltype(FF));
}
Y_UNIT_TEST(TestFunction) {
std::function<int(double)> f(FF);
UNIT_ASSERT_TYPES_EQUAL(TFunctionSignature<decltype(f)>, decltype(FF));
}
template <class F>
void TestCT() {
#define FA(x) TFunctionArg<F, x>
UNIT_ASSERT_TYPES_EQUAL(FA(0), double);
UNIT_ASSERT_TYPES_EQUAL(FA(1), char);
UNIT_ASSERT_TYPES_EQUAL(TFunctionResult<F>, int);
#undef FA
}
Y_UNIT_TEST(TestTypeErasureTraits) {
TestCT<std::function<int(double, char)>>();
}
Y_UNIT_TEST(TestPlainFunctionTraits) {
TestCT<decltype(FFF)>();
}
Y_UNIT_TEST(TestLambdaTraits) {
auto fff = [](double xx, char xxx) -> int {
return FFF(xx, xxx);
};
TestCT<decltype(fff)>();
}
}
| 22.042857 | 83 | 0.594945 | HeyLey |
d6a689479090886a8191b98c2c0a863737cf536e | 901 | cc | C++ | exercises/RIF_PUNT/rifpunt.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | 3 | 2021-11-05T16:25:50.000Z | 2022-02-10T14:06:00.000Z | exercises/RIF_PUNT/rifpunt.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | null | null | null | exercises/RIF_PUNT/rifpunt.cc | mfranzil/Programmazione1UniTN | 0aee3ec51d424039afcabfa9de80046c1d5be7d9 | [
"MIT"
] | 2 | 2018-10-31T14:53:40.000Z | 2020-01-09T22:34:37.000Z | // Example 7.1, page 187
// Schaum's Outline of Programming with C++ by John R. Hubbard
// Copyright McGraw-Hill, 1996
using namespace std;
#include <iostream>
int main()
{
float x = 44.44;
cout << "x = " << x << endl;
cout << "\t&x = " << &x << endl; // prints address of x
float* p = &x; // p points to x
cout << "\np = " << p << endl;
cout << "\t&p = " << &p << endl; // prints address of p
cout << "\t*p = " << *p << endl; // prints object p points to
*p = 77.77;
cout << "\np = " << p << endl;
cout << "\t&p = " << &p << endl;
cout << "\t*p = " << *p << endl;
cout << "x = " << x << endl;
cout << "\t&x = " << &x << endl;
float* q = &x; // q points to x
cout << "\nq = " << q << endl;
cout << "\t&q = " << &q << endl;
cout << "\t*q = " << *q << endl;
cout << "x = " << x << endl;
cout << "\t&x = " << &x << endl;
return 0;
}
| 29.064516 | 65 | 0.438402 | mfranzil |
d6a70cf1677b668a8b9b1d6a1a8f5fe6c2711a1f | 1,757 | hpp | C++ | Yannq/Serializers/SerializeRBM.hpp | cecri/yannq | b78c1f86a255059f06b34dd5e538449e7261d0ee | [
"BSD-3-Clause"
] | null | null | null | Yannq/Serializers/SerializeRBM.hpp | cecri/yannq | b78c1f86a255059f06b34dd5e538449e7261d0ee | [
"BSD-3-Clause"
] | null | null | null | Yannq/Serializers/SerializeRBM.hpp | cecri/yannq | b78c1f86a255059f06b34dd5e538449e7261d0ee | [
"BSD-3-Clause"
] | null | null | null | #ifndef YANNQ_SEREALIZAERS_SERIALIZERBM_HPP
#define YANNQ_SEREALIZAERS_SERIALIZERBM_HPP
#include <cereal/access.hpp>
#include <cereal/types/memory.hpp>
#include "Machines/RBM.hpp"
CEREAL_CLASS_VERSION(yannq::RBM<float>, 1);
CEREAL_CLASS_VERSION(yannq::RBM<std::complex<float>>, 1);
CEREAL_CLASS_VERSION(yannq::RBM<double>, 1);
CEREAL_CLASS_VERSION(yannq::RBM<std::complex<double>>, 1);
CEREAL_CLASS_VERSION(yannq::RBM<long double>, 1);
CEREAL_CLASS_VERSION(yannq::RBM<std::complex<long double>>, 1);
namespace cereal
{
template<class Archive, typename T>
void save(Archive & ar, const yannq::RBM<T>& m, uint32_t const /*version*/)
{
bool useBias = m.useBias();
ar(useBias);
ar(m.getN(),m.getM());
ar(m.getW());
if(!useBias)
return ;
ar(m.getA(),m.getB());
}
template<class Archive, typename T>
void load(Archive & ar, yannq::RBM<T>& m, uint32_t const /*version*/)
{
bool useBias;
ar(useBias);
m.setUseBias(useBias);
int N, M;
ar(N, M);
m.resize(N, M);
typename yannq::RBM<T>::Matrix W;
ar(W);
m.setW(W);
if(!useBias)
return ;
typename yannq::RBM<T>::Vector A, B;
ar(A, B);
m.setA(A);
m.setB(B);
}
template <typename T>
struct LoadAndConstruct<yannq::RBM<T> >
{
template<class Archive>
static void load_and_construct(Archive& ar, cereal::construct<yannq::RBM<T> >& construct, uint32_t const /*version*/)
{
bool useBias;
ar(useBias);
int n,m;
ar(n, m);
construct(n, m, useBias);
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> W;
ar(W);
construct->setW(W);
if(!useBias)
return ;
Eigen::Matrix<T, Eigen::Dynamic, 1> A;
Eigen::Matrix<T, Eigen::Dynamic, 1> B;
ar(A, B);
construct->setA(A);
construct->setB(B);
}
};
}//namespace cereal
#endif//YANNQ_SEREALIZAERS_SERIALIZERBM_HPP
| 20.430233 | 119 | 0.684121 | cecri |
d6ab23a4c48bc2f8cadc95a726f4aff1166dfa3d | 2,164 | hpp | C++ | libs/python/include/python/math/py_tensor.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | 3 | 2019-07-11T08:49:27.000Z | 2021-09-07T16:49:15.000Z | libs/python/include/python/math/py_tensor.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | libs/python/include/python/math/py_tensor.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | 2 | 2019-07-13T12:45:22.000Z | 2021-03-12T08:48:57.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "math/tensor.hpp"
#include "python/fetch_pybind.hpp"
namespace py = pybind11;
namespace fetch {
namespace math {
template <typename T>
void BuildTensor(std::string const &custom_name, pybind11::module &module)
{
using ArrayType = typename fetch::math::Tensor<T>;
py::class_<ArrayType, std::shared_ptr<ArrayType>>(module, custom_name.c_str())
.def(py::init<std::vector<SizeType> const &>())
.def("ToString", &ArrayType::ToString)
.def("Size", &ArrayType::size)
.def("Fill", [](ArrayType &a, T val) { return a.Fill(val); })
.def("Slice", [](ArrayType &a, SizeType i) { return a.Slice(i); })
.def("Slice", [](ArrayType const &a, SizeType i) { return a.Slice(i); })
.def("At", [](ArrayType &a, SizeType i) { return a.At(i); })
// TODO (private 877)
.def("Set", (void (ArrayType::*)(SizeType const &, T)) & ArrayType::Set)
.def("Set", (void (ArrayType::*)(SizeType const &, SizeType const &, T)) & ArrayType::Set)
.def("Set", (void (ArrayType::*)(SizeType const &, SizeType const &, SizeType const &, T)) &
ArrayType::Set)
.def("Set", (void (ArrayType::*)(SizeType const &, SizeType const &, SizeType const &,
SizeType const &, T)) &
ArrayType::Set);
}
} // namespace math
} // namespace fetch
| 40.830189 | 98 | 0.581793 | devjsc |
d6ad493472925a996ded91157d873f53c5300317 | 4,335 | cpp | C++ | Coconuts/src/editor/standalone/panels/SceneOverview.cpp | filhoDaMain/Coconuts | 007cfdea11e2bc7bbb8ffa38747629b111b4e196 | [
"Apache-2.0"
] | 3 | 2020-05-02T15:18:19.000Z | 2022-01-26T06:18:18.000Z | Coconuts/src/editor/standalone/panels/SceneOverview.cpp | filhoDaMain/Coconuts | 007cfdea11e2bc7bbb8ffa38747629b111b4e196 | [
"Apache-2.0"
] | 4 | 2021-07-19T21:55:59.000Z | 2021-10-04T20:19:17.000Z | Coconuts/src/editor/standalone/panels/SceneOverview.cpp | filhoDaMain/Coconuts | 007cfdea11e2bc7bbb8ffa38747629b111b4e196 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 Andre Temprilho
*
* 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 "SceneOverview.h"
#include <coconuts/editor.h>
#include <string>
#include <coconuts/Logger.h>
// ECS Components
#include <coconuts/ecs/components/TagComponent.h>
#include <coconuts/ecs/components/OrthoCameraComponent.h>
#include <coconuts/ecs/components/TransformComponent.h>
#include <coconuts/ecs/components/SpriteComponent.h>
#include <coconuts/ecs/components/BehaviorComponent.h>
namespace Coconuts {
namespace Panels
{
bool SceneOverview::Init(GameLayer*& gameLayer, ComponentInspector* componentInspector)
{
m_GameLayerPtr = gameLayer;
m_ComponentInspectorPtr = componentInspector;
m_CurrentSelectedEntityPtr = new Coconuts::Entity();
return true;
}
void SceneOverview::Draw()
{
if ( m_GameLayerPtr->IsActiveSceneUpdated() )
{
GetLastSceneUpdate();
}
ImGui::Begin("Scene Overview");
for (Entity thisEntity : sceneEntities)
{
/* Draw all entities */
if (DrawNode(thisEntity))
{
/**
* thisEntity is currently selected.
* Update Component Inspector panel context to draw its
* components.
*/
/* Avoid spawn of unnecessary context-changes */
if (m_CurrentSelectedEntityPtr->GetId() != thisEntity.GetId())
{
*m_CurrentSelectedEntityPtr = thisEntity;
m_ComponentInspectorPtr->ChangeContext(m_CurrentSelectedEntityPtr);
}
}
ImGui::Spacing();
}
ImGui::End();
}
void SceneOverview::GetLastSceneUpdate()
{
/* Get tmp vector from Game Layer with al entities */
std::vector<Entity> last = m_GameLayerPtr->GetActiveSceneEntities();
/* Free heap vector and re-allocate */
sceneEntities = std::vector<Entity>();
sceneEntities.resize(last.size());
/* Copy */
sceneEntities = last;
}
bool SceneOverview::DrawNode(Entity& entity)
{
std::string tag = entity.GetComponent<TagComponent>().tag;
static uint64_t context_id = 0;
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_OpenOnArrow;
flags |= context_id == entity.GetId() ? ImGuiTreeNodeFlags_Selected : 0;
bool open = ImGui::TreeNodeEx(tag.c_str() , flags);
if (ImGui::IsItemClicked())
{
context_id = entity.GetId();
}
/* Draw simple components */
if (open)
{
ImGui::TextDisabled("ID: %llu", entity.GetId());
/* Camera */
if (entity.HasComponent<OrthoCameraComponent>())
{
ImGui::Text("Camera");
}
/* Transform */
if (entity.HasComponent<TransformComponent>())
{
ImGui::Text("Transform");
}
/* Sprite */
if (entity.HasComponent<SpriteComponent>())
{
ImGui::Text("Sprite");
}
/* Behavior */
if (entity.HasComponent<BehaviorComponent>())
{
ImGui::Text("Behavior");
}
ImGui::TreePop();
}
/**
* This entity is currently selected.
*/
if (flags & ImGuiTreeNodeFlags_Selected)
{
return true;
}
return false;
}
}
} | 29.691781 | 102 | 0.551788 | filhoDaMain |
d6b08477bf23e331ade748dcf013b997dff9fe83 | 1,751 | cpp | C++ | Source/ToolExampleEditor/CustomDataType/ReimportExampleDataFactory.cpp | ScottKirvan/ToolExample | 71f90211b70bdebbf7e171f127b9b6d103735889 | [
"MIT"
] | 3 | 2021-03-10T21:00:13.000Z | 2021-12-11T12:33:17.000Z | Source/ToolExampleEditor/CustomDataType/ReimportExampleDataFactory.cpp | ScottKirvan/ToolExample | 71f90211b70bdebbf7e171f127b9b6d103735889 | [
"MIT"
] | 1 | 2021-02-08T02:34:07.000Z | 2021-02-08T02:44:58.000Z | Source/ToolExampleEditor/CustomDataType/ReimportExampleDataFactory.cpp | ScottKirvan/ToolExample | 71f90211b70bdebbf7e171f127b9b6d103735889 | [
"MIT"
] | 3 | 2021-03-11T10:13:30.000Z | 2021-08-18T13:30:57.000Z | #include "ReimportExampleDataFactory.h"
#include "ToolExampleEditor/ToolExampleEditor.h"
#include "ExampleDataFactory.h"
#include "ToolExample/CustomDataType/ExampleData.h"
bool UReimportExampleDataFactory::CanReimport(UObject* Obj, TArray<FString>& OutFilenames)
{
UExampleData* ExampleData = Cast<UExampleData>(Obj);
if (ExampleData)
{
OutFilenames.Add(UAssetImportData::ResolveImportFilename(ExampleData->SourceFilePath, ExampleData->GetOutermost()));
return true;
}
return false;
}
void UReimportExampleDataFactory::SetReimportPaths(UObject* Obj, const TArray<FString>& NewReimportPaths)
{
UExampleData* ExampleData = Cast<UExampleData>(Obj);
if (ExampleData && ensure(NewReimportPaths.Num() == 1))
{
ExampleData->SourceFilePath = UAssetImportData::SanitizeImportFilename(NewReimportPaths[0], ExampleData->GetOutermost());
}
}
EReimportResult::Type UReimportExampleDataFactory::Reimport(UObject* Obj)
{
UExampleData* ExampleData = Cast<UExampleData>(Obj);
if (!ExampleData)
{
return EReimportResult::Failed;
}
const FString Filename = UAssetImportData::ResolveImportFilename(ExampleData->SourceFilePath, ExampleData->GetOutermost());
if (!FPaths::GetExtension(Filename).Equals(TEXT("xmp")))
{
return EReimportResult::Failed;
}
CurrentFilename = Filename;
FString Data;
if (FFileHelper::LoadFileToString(Data, *CurrentFilename))
{
const TCHAR* Ptr = *Data;
ExampleData->Modify();
ExampleData->MarkPackageDirty();
UExampleDataFactory::MakeExampleDataFromText(ExampleData, Ptr, Ptr + Data.Len());
// save the source file path and timestamp
ExampleData->SourceFilePath = UAssetImportData::SanitizeImportFilename(CurrentFilename, ExampleData->GetOutermost());
}
return EReimportResult::Succeeded;
}
| 31.267857 | 124 | 0.780126 | ScottKirvan |
d6b8056d8c7995f7ae69b3cd1d986d6217a82df1 | 2,711 | hpp | C++ | modules/filter/include/filter/parallel.hpp | aversiveplusplus/aversiveplusplus | 5f5fe9faca50197fd6207e2c816efa7e9af6c804 | [
"BSD-3-Clause"
] | 29 | 2016-01-27T09:43:44.000Z | 2020-03-12T04:16:02.000Z | modules/filter/include/filter/parallel.hpp | aversiveplusplus/aversiveplusplus | 5f5fe9faca50197fd6207e2c816efa7e9af6c804 | [
"BSD-3-Clause"
] | 20 | 2016-01-22T15:59:33.000Z | 2016-10-28T10:22:45.000Z | modules/filter/include/filter/parallel.hpp | aversiveplusplus/aversiveplusplus | 5f5fe9faca50197fd6207e2c816efa7e9af6c804 | [
"BSD-3-Clause"
] | 6 | 2016-02-11T14:09:04.000Z | 2018-03-17T00:18:35.000Z | /*
Copyright (c) 2015, Xenomorphales
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 Aversive++ nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FILTER_PARALLEL_HPP
#define FILTER_PARALLEL_HPP
#include <base/type_traits.hpp>
#include <filter/filter.hpp>
namespace Aversive {
namespace Filter {
template <class First, class Second>
class Parallel :
public AdaptableFilter<typename First::InputType, typename First::OutputType, Parallel<First, Second>> {
public:
using InputType = typename First::InputType;
using OutputType = typename First::OutputType;
static_assert(
TypeEqual<typename First::InputType, typename Second::InputType>::VALUE &&
TypeEqual<typename First::OutputType, typename Second::OutputType>::VALUE,
"ERROR : incompatibles filters in parallel"
);
private:
using FirstFilter = AdaptableFilter<typename First::InputType, typename First::OutputType, First>;
using SecondFilter = AdaptableFilter<typename Second::InputType, typename Second::OutputType, Second>;
FirstFilter& first;
SecondFilter& second;
public:
inline Parallel(FirstFilter& first, SecondFilter& second)
: first(first), second(second) {
}
inline OutputType operator()(InputType value) {
return second(value) + first(value);
}
};
}
}
#endif//FILTER_PARALLEL_HPP
| 35.671053 | 110 | 0.766138 | aversiveplusplus |
d6b86363a81241a571f4c5376de9bf63ad60c01b | 3,893 | cpp | C++ | src/Graphics/Window.cpp | jkbz64/Zadymka | 16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7 | [
"MIT"
] | 2 | 2020-03-18T16:13:04.000Z | 2021-07-30T12:18:52.000Z | src/Graphics/Window.cpp | jkbz64/Zadymka | 16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7 | [
"MIT"
] | null | null | null | src/Graphics/Window.cpp | jkbz64/Zadymka | 16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7 | [
"MIT"
] | null | null | null | #include <Graphics/Window.hpp>
#include <Graphics/Shader.hpp>
#include <Graphics/Drawable.hpp>
#include <Input.hpp>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <Graphics/DefaultRenderer.hpp>
#include <ImGui.hpp>
namespace
{
template <typename T>
constexpr float normalize(T value)
{
return value < 0 ? 0 : static_cast<float>(value) / 255.f;
}
}
Window::Window() :
RenderTarget(new DefaultRenderer(m_camera)),
m_window(nullptr),
m_isOpen(false),
m_style(Window::Style::Windowed)
{
}
Window::~Window()
{
Input::setWindow(nullptr);
ImGUI::setWindow(nullptr);
if(m_window)
glfwDestroyWindow(getNativeWindow());
}
GLFWwindow* Window::getNativeWindow()
{
return m_window;
}
void Window::create(const glm::uvec2& size, const std::string& title, const Style& style)
{
if(size.x == 0 || size.y == 0)
{
m_isOpen = false;
throw std::runtime_error("Window size must be > 0");
}
m_size = size;
m_title = title;
m_style = style;
if(m_window)
glfwDestroyWindow(getNativeWindow());
switch(m_style)
{
case Style::Windowed:
m_window = glfwCreateWindow(m_size.x, m_size.y, title.c_str(), NULL, NULL);
break;
case Style::Fullscreen:
m_window = glfwCreateWindow(m_size.x, m_size.y, title.c_str(), glfwGetPrimaryMonitor(), NULL);
break;
case Style::FullscreenWindowed:
auto monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwWindowHint(GLFW_RED_BITS, mode->redBits);
glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
m_window = glfwCreateWindow(mode->width, mode->height, title.c_str(), monitor, NULL);
break;
}
m_isOpen = true;
glfwMakeContextCurrent(getNativeWindow());
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
glfwSetWindowUserPointer(getNativeWindow(), this);
glfwSetFramebufferSizeCallback(getNativeWindow(), [](GLFWwindow* window, int width, int height)
{
auto w = static_cast<Window*>(glfwGetWindowUserPointer(window));
w->m_size.x = width;
w->m_size.y = height;
glViewport(0, 0, width, height);
});
Input::setWindow(getNativeWindow());
ImGUI::setWindow(getNativeWindow());
}
bool Window::isOpen()
{
if(m_window)
return !glfwWindowShouldClose(getNativeWindow()) && m_isOpen;
return false;
}
void Window::clear(unsigned int r, unsigned int g, unsigned int b, unsigned int a)
{
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(normalize(r), normalize(g), normalize(b), normalize(a));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void Window::display()
{
glfwSwapBuffers(getNativeWindow());
glfwPollEvents();
}
void Window::close()
{
if(m_isOpen)
m_isOpen = false;
}
const std::string& Window::title() const
{
return m_title;
}
void Window::setTitle(const std::string& title)
{
m_title = title;
if(m_isOpen)
glfwSetWindowTitle(getNativeWindow(), m_title.c_str());
}
void Window::resize(const glm::uvec2& size)
{
if(size.x == 0 || size.y == 0)
return;
m_size = size;
if(m_isOpen)
glfwSetWindowSize(getNativeWindow(), m_size.x, m_size.y);
}
const glm::uvec2& Window::size()
{
return m_size;
}
glm::vec2 Window::mapToWorld(const glm::vec2 &pos)
{
auto& camera = m_camera;
const auto cameraSize = glm::vec2(camera.size());
auto halfSize = cameraSize;
halfSize /= 2.f;
const auto& cameraCenter = camera.center();
const glm::vec2 factor = glm::vec2(pos.x / m_size.x, pos.y / m_size.y);
return (cameraCenter - halfSize) + cameraSize * factor;
} | 25.279221 | 102 | 0.660416 | jkbz64 |
d6baa311765f24126537b56fc7ff802bd700f952 | 1,922 | cpp | C++ | src/main/cpp/castling.cpp | hayanige/pulse_plus | 6b9e8517820109f02d566121afcb0e9a84cb2918 | [
"MIT"
] | null | null | null | src/main/cpp/castling.cpp | hayanige/pulse_plus | 6b9e8517820109f02d566121afcb0e9a84cb2918 | [
"MIT"
] | null | null | null | src/main/cpp/castling.cpp | hayanige/pulse_plus | 6b9e8517820109f02d566121afcb0e9a84cb2918 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2013-2016 Phokham Nonava
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
#include "castling.h"
#include "color.h"
#include "castlingtype.h"
namespace pulse {
bool Castling::isValid(int castling) {
switch (castling) {
case WHITE_KINGSIDE:
case WHITE_QUEENSIDE:
case BLACK_KINGSIDE:
case BLACK_QUEENSIDE:
return true;
default:
return false;
}
}
int Castling::valueOf(int color, int castlingtype) {
switch (color) {
case Color::WHITE:
switch (castlingtype) {
case CastlingType::KINGSIDE:
return WHITE_KINGSIDE;
case CastlingType::QUEENSIDE:
return WHITE_QUEENSIDE;
default:
throw std::exception();
}
case Color::BLACK:
switch (castlingtype) {
case CastlingType::KINGSIDE:
return BLACK_KINGSIDE;
case CastlingType::QUEENSIDE:
return BLACK_QUEENSIDE;
default:
throw std::exception();
}
default:
throw std::exception();
}
}
int Castling::getType(int castling) {
switch (castling) {
case WHITE_KINGSIDE:
case BLACK_KINGSIDE:
return CastlingType::KINGSIDE;
case WHITE_QUEENSIDE:
case BLACK_QUEENSIDE:
return CastlingType::QUEENSIDE;
default:
throw std::exception();
}
}
int Castling::getColor(int castling) {
switch (castling) {
case WHITE_KINGSIDE:
case WHITE_QUEENSIDE:
return Color::WHITE;
case BLACK_KINGSIDE:
case BLACK_QUEENSIDE:
return Color::BLACK;
default:
throw std::exception();
}
}
}
| 24.641026 | 69 | 0.546306 | hayanige |
d6bbe5228a57754b9883e9a03e40c79b7ab2b10e | 3,640 | cpp | C++ | _Deprecated/Db_2021/EntryPoint/EntryPoint.cpp | DexterDreeeam/DxtSdk2021 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | 1 | 2021-11-18T03:57:54.000Z | 2021-11-18T03:57:54.000Z | _Deprecated/Db_2021/EntryPoint/EntryPoint.cpp | DexterDreeeam/P9 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | null | null | null | _Deprecated/Db_2021/EntryPoint/EntryPoint.cpp | DexterDreeeam/P9 | 2dd8807b4ebe1d65221095191eaa7938bc5e9e78 | [
"MIT"
] | null | null | null | #include "../DbCore/Interface.hpp"
const s64 port = 39901;
const char* ip;
struct client_context
{
network_connect connect;
ref<P9::Platform::platform> platform;
};
static void client_handler(void* p)
{
client_context* p_context = (client_context*)p;
network_connect connect = p_context->connect;
auto r_platform = p_context->platform;
char* buf = new char[2048];
escape_function ef = [=]() mutable
{
delete[] buf;
delete p_context;
connect.destroy();
print("Client disconnect to server.\n");
};
while (1)
{
print("Waiting client query....\n");
s64 msg_len;
boole checker;
checker = connect.receive(buf, msg_len);
if (!checker || msg_len <= 0)
{
break;
}
string query = buf;
string rst;
boole is_error_happens = boole::False;
print("Received client query, start process...\n");
try
{
auto op1 = r_platform->parse_operation_message(query);
rst = r_platform->handle_operation(op1);
}
catch (P9_assert_exception ex)
{
is_error_happens = boole::True;
rst = "Assert error happens when process query.";
err(rst.data());
err("error_code: %ll, expected_condition: %s, information: %s, file: %s, line: ll.",
ex.error_code, ex.expect_condition, ex.information, ex.file, ex.line);
print("%s\n", rst.data());
}
catch (...)
{
is_error_happens = boole::True;
rst = "Unknown error happens when process query.";
log(rst.data());
print("%s\n", rst.data());
}
print("Finish client query, send result back to client...\n");
if (rst.size() == 0 || !connect.send(rst.data(), rst.size() + 1))
{
is_error_happens = boole::True;
log("Error happens when send result back.");
print("Error happens when send result back.\n");
}
print("Complete query.\n");
}
}
void server_entry_point()
{
print("Init DB server...\n");
auto r_platfrom = ref<P9::Platform::platform>::new_instance();
r_platfrom->load(P9_FOLDER "p1/");
network_server ns;
ns.init(port);
print("Complete DB init...\n");
print("Waiting Client connect...\n");
while (!am_i_terminated())
{
client_context* p_context = new client_context();
ns.new_connect(p_context->connect);
print("Client connected to server.\n");
p_context->platform = r_platfrom;
thread t;
t.init(client_handler);
t.start(p_context);
t.uninit();
object::report();
}
ns.uninit();
}
void read_file_send_query(const char* path)
{
char buf[8000];
file f;
f.init_input(path);
s64 len;
f.input(buf, 8000, len);
buf[len] = 0;
f.uninit();
string query(buf);
network_client nc;
nc.init(ip, port);
nc.send(query.data(), query.size() + 1);
nc.receive(buf, len);
print("Result: %s.\n", buf);
nc.uninit();
}
void client_entry_point(const char* json_file_path)
{
read_file_send_query(json_file_path);
}
int main(int argc, char* argv[])
{
if (argc == 2 && str_equal_case_insensitive(argv[1], "host"))
{
server_entry_point();
return 0;
}
else if (argc == 3)
{
ip = argv[1];
client_entry_point(argv[2]);
return 0;
}
print("input parameters: \n \"Host\" or \"20.40.99.127 ./json_query_file.json\"\n");
return -1;
}
| 25.277778 | 96 | 0.560989 | DexterDreeeam |
d6bc8e308587489d0aaabe14e1c06328e14d0012 | 630 | cpp | C++ | lldb/source/Utility/Baton.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | lldb/source/Utility/Baton.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | lldb/source/Utility/Baton.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | //===-- Baton.cpp ---------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Utility/Baton.h"
void lldb_private::UntypedBaton::GetDescription(llvm::raw_ostream &s,
lldb::DescriptionLevel level,
unsigned indentation) const {}
| 45 | 80 | 0.465079 | medismailben |
d6bda410f7f9f02b5a01512c65e6da0b164d22a5 | 968 | cpp | C++ | Tutorial2/12.Menghitung_Kalimat.cpp | azminawwar/tutorial_cpp | 0ec79e9c7f5f77bab38bc23dfc9e81a70897faa8 | [
"MIT"
] | 12 | 2020-03-06T04:18:13.000Z | 2021-11-02T01:28:21.000Z | Tutorial2/12.Menghitung_Kalimat.cpp | azminawwar/tutorial_cpp | 0ec79e9c7f5f77bab38bc23dfc9e81a70897faa8 | [
"MIT"
] | 1 | 2020-10-02T10:02:37.000Z | 2020-10-02T10:02:37.000Z | Tutorial2/12.Menghitung_Kalimat.cpp | azminawwar/tutorial_cpp | 0ec79e9c7f5f77bab38bc23dfc9e81a70897faa8 | [
"MIT"
] | 9 | 2019-11-02T09:33:47.000Z | 2021-12-16T14:24:49.000Z | #include <iostream>
using namespace std;
//deklarasi fungsi
int itungKalimat(string x);
int itungKata(string x);
int main() {
//membuat variabel dan pointernya
string kalimat;
string *pointer_kalimat = &kalimat;
cout<<"Masukkan Kalimat Anda = ";
//input beserta spasi
getline(cin,kalimat);
//pemanggilan fungsi
cout<<"Jumlah Kalimat Anda Adalah = "<<itungKalimat(*pointer_kalimat)<<endl;
cout<<"Jumlah Karakter Anda Adalah = "<<itungKata(*pointer_kalimat)<<endl;
}
int itungKalimat(string x){
//inisialisator spasi sebagai 1 kalimat
int spasi = 1;
//foreach kata menjadi char array
for (char cacah : x){
//hitung spasi
if (isspace(cacah,cin.getloc())){
++spasi;
}
}
return spasi;
}
int itungKata(string x){
int karakter = 0;
//foreach kata menjadi array
for (char cacah : x){
//dihitung berapa kali loop
karakter++;
}
return karakter;
} | 26.162162 | 80 | 0.637397 | azminawwar |
d6c0283daa7ab3e68424f8c9ecd3e391294f8f2d | 1,562 | hpp | C++ | include/RED4ext/Types/generated/game/ui/SideScrollerMiniGameLogicControllerAdvanced.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Types/generated/game/ui/SideScrollerMiniGameLogicControllerAdvanced.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Types/generated/game/ui/SideScrollerMiniGameLogicControllerAdvanced.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/Types/generated/Vector2.hpp>
#include <RED4ext/Types/generated/game/ui/SideScrollerCheatCode.hpp>
#include <RED4ext/Types/generated/ink/CompoundWidgetReference.hpp>
#include <RED4ext/Types/generated/ink/WidgetLogicController.hpp>
#include <RED4ext/Types/generated/ink/WidgetReference.hpp>
namespace RED4ext
{
namespace game::ui {
struct SideScrollerMiniGameLogicControllerAdvanced : ink::WidgetLogicController
{
static constexpr const char* NAME = "gameuiSideScrollerMiniGameLogicControllerAdvanced";
static constexpr const char* ALIAS = "MinigameLogicControllerAdvanced";
uint8_t unk68[0xB0 - 0x68]; // 68
float baseSpeed; // B0
Vector2 playerColliderPositionOffset; // B4
Vector2 playerColliderSizeOffset; // BC
uint8_t unkC4[0xC8 - 0xC4]; // C4
ink::CompoundWidgetReference gameplayRoot; // C8
CName playerLibraryName; // E0
DynArray<ink::WidgetReference> layers; // E8
DynArray<game::ui::SideScrollerCheatCode> cheatCodes; // F8
uint8_t unk108[0x120 - 0x108]; // 108
DynArray<CName> acceptableCheatKeys; // 120
uint8_t unk130[0x138 - 0x130]; // 130
};
RED4EXT_ASSERT_SIZE(SideScrollerMiniGameLogicControllerAdvanced, 0x138);
} // namespace game::ui
using MinigameLogicControllerAdvanced = game::ui::SideScrollerMiniGameLogicControllerAdvanced;
} // namespace RED4ext
| 38.097561 | 94 | 0.772087 | Cyberpunk-Extended-Development-Team |
d6c066061dc148d9477d273b723084296c5ca0a9 | 3,135 | cxx | C++ | Victre/generation/createDuct.cxx | DIDSR/VICTRE_PIPELINE | e4108430705ad0e4c8d51fe360f999929dcc9a92 | [
"CC0-1.0"
] | 4 | 2021-06-24T23:57:56.000Z | 2022-03-17T01:23:04.000Z | Victre/generation/createDuct.cxx | DIDSR/VICTRE_PIPELINE | e4108430705ad0e4c8d51fe360f999929dcc9a92 | [
"CC0-1.0"
] | null | null | null | Victre/generation/createDuct.cxx | DIDSR/VICTRE_PIPELINE | e4108430705ad0e4c8d51fe360f999929dcc9a92 | [
"CC0-1.0"
] | 5 | 2021-05-22T18:53:12.000Z | 2022-03-27T20:34:15.000Z | /*
* create_duct.cxx
*
* Created on: Dec 22, 2014
* Author: cgg
*/
#include "createDuct.hxx"
using namespace std;
namespace po = boost::program_options;
/* This function creates a duct tree within a given compartment, inserts it into the segmented
* breast and saves the tree */
void generate_duct(vtkImageData* breast, po::variables_map vm, vtkPoints* TDLUloc, vtkDoubleArray* TDLUattr,
unsigned char compartmentId, int* boundBox, tissueStruct* tissue, double* sposPtr, double* sdirPtr, int seed){
double spos[3];
double sdir[3];
for(int i=0; i<3; i++){
spos[i] = sposPtr[i];
sdir[i] = sdirPtr[i];
}
// declare ductTreeInit struct and fill information
ductTreeInit treeInit;
treeInit.seed = seed;
// bounds of duct simulation derived from breast structure
int startInd[3] = {boundBox[0], boundBox[2], boundBox[4]};
int endInd[3] = {boundBox[1], boundBox[3], boundBox[5]};
//startPos
breast->GetPoint(breast->ComputePointId(startInd), treeInit.startPos);
//endPos
breast->GetPoint(breast->ComputePointId(endInd), treeInit.endPos);
// size of voxels
treeInit.nVox[0] = boundBox[1]-boundBox[0];
treeInit.nVox[1] = boundBox[3]-boundBox[2];
treeInit.nVox[2] = boundBox[5]-boundBox[4];
treeInit.nFill[0] = vm["ductTree.nFillX"].as<uint>();
treeInit.nFill[1] = vm["ductTree.nFillY"].as<uint>();
treeInit.nFill[2] = vm["ductTree.nFillZ"].as<uint>();
for(int i=0; i<3; i++){
treeInit.prefDir[i] = sdir[i];
}
treeInit.boundBox = boundBox;
treeInit.compartmentId = compartmentId;
treeInit.tissue = tissue;
treeInit.breast = breast;
treeInit.TDLUloc = TDLUloc;
treeInit.TDLUattr = TDLUattr;
ductTree myTree(vm, &treeInit);
// root of tree
double srad = vm["ductTree.initRad"].as<double>();
// initialize fill map based on distance to start position
int fillExtent[6];
myTree.fill->GetExtent(fillExtent);
#pragma omp parallel for
for(int a=fillExtent[0]; a<=fillExtent[1]; a++){
for(int b=fillExtent[2]; b<=fillExtent[3]; b++){
for(int c=fillExtent[4]; c<=fillExtent[5]; c++){
double* v = static_cast<double*>(myTree.fill->GetScalarPointer(a,b,c));
// set distance to 0 if fill voxel is not in compartment, otherwise
// initialize with squared distance to tree base
// fill voxel location
vtkIdType id;
int coord[3];
coord[0] = a;
coord[1] = b;
coord[2] = c;
id = myTree.fill->ComputePointId(coord);
// get spatial coordinates of fill voxel
double pos[3];
myTree.fill->GetPoint(id,pos);
// compare to nearest breast voxel id
unsigned char* breastVal = static_cast<unsigned char *>(breast->GetScalarPointer());
if(breastVal[breast->FindPoint(pos)] == compartmentId){
// inside compartment
v[0] = vtkMath::Distance2BetweenPoints(spos, pos);
} else {
// outside compartment, set distance to zero
v[0] = 0.0;
}
}
}
}
myTree.head = new ductBr(spos, sdir, srad, &myTree);
//cout << "Finished duct tree " << myTree.id << " with " << myTree.TDLUloc->GetNumberOfPoints() << " TDLUs, " <<
// myTree.numBranch << " branches created\n";
return;
}
| 24.685039 | 115 | 0.67177 | DIDSR |
d6c0b28547642bb3f96856736d88ea6bc8b24a0a | 3,831 | cc | C++ | chrome/browser/ui/sad_tab_helper.cc | leiferikb/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-11-15T15:17:43.000Z | 2021-11-15T15:17:43.000Z | chrome/browser/ui/sad_tab_helper.cc | houseoflifeproperty/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/sad_tab_helper.cc | houseoflifeproperty/bitpop-private | 4c967307d228e86f07f2576068a169e846c833ca | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:24:02.000Z | 2020-11-04T07:24:02.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/sad_tab_helper.h"
#include "base/logging.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/ui/sad_tab.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#if defined(TOOLKIT_VIEWS)
#include "chrome/browser/ui/views/sad_tab_view.h"
#include "ui/views/widget/widget.h"
#endif
DEFINE_WEB_CONTENTS_USER_DATA_KEY(SadTabHelper)
SadTabHelper::~SadTabHelper() {
}
SadTabHelper::SadTabHelper(content::WebContents* web_contents)
: content::WebContentsObserver(web_contents) {
registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_CONNECTED,
content::Source<content::WebContents>(web_contents));
}
void SadTabHelper::RenderViewGone(base::TerminationStatus status) {
// Only show the sad tab if we're not in browser shutdown, so that WebContents
// objects that are not in a browser (e.g., HTML dialogs) and thus are
// visible do not flash a sad tab page.
if (browser_shutdown::GetShutdownType() != browser_shutdown::NOT_VALID)
return;
if (sad_tab_)
return;
if (status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION ||
status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED ||
status == base::TERMINATION_STATUS_PROCESS_CRASHED)
InstallSadTab(status);
}
void SadTabHelper::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_CONNECTED, type);
if (sad_tab_) {
#if defined(TOOLKIT_VIEWS)
sad_tab_->Close();
// See http://crbug.com/117668. When the Widget is being destructed, we
// want calls to sad_tab() to return NULL.
scoped_ptr<views::Widget> local_sad_tab;
local_sad_tab.swap(sad_tab_);
#elif defined(TOOLKIT_GTK) || defined(OS_MACOSX)
sad_tab_->Close();
#else
#error Unknown platform
#endif
sad_tab_.reset();
}
}
void SadTabHelper::InstallSadTab(base::TerminationStatus status) {
chrome::SadTabKind kind =
(status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) ?
chrome::SAD_TAB_KIND_KILLED : chrome::SAD_TAB_KIND_CRASHED;
#if defined(TOOLKIT_VIEWS)
views::Widget::InitParams sad_tab_params(
views::Widget::InitParams::TYPE_CONTROL);
// It is not possible to create a native_widget_win that has no parent in
// and later re-parent it.
// TODO(avi): This is a cheat. Can this be made cleaner?
sad_tab_params.parent = web_contents()->GetView()->GetNativeView();
#if defined(OS_WIN) && !defined(USE_AURA)
// Crash data indicates we can get here when the parent is no longer valid.
// Attempting to create a child window with a bogus parent crashes. So, we
// don't show a sad tab in this case in hopes the tab is in the process of
// shutting down.
if (!IsWindow(sad_tab_params.parent))
return;
#endif
sad_tab_params.ownership =
views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
sad_tab_.reset(new views::Widget);
sad_tab_->Init(sad_tab_params);
sad_tab_->SetContentsView(new SadTabView(web_contents(), kind));
views::Widget::ReparentNativeView(
sad_tab_->GetNativeView(), web_contents()->GetView()->GetNativeView());
gfx::Rect bounds;
web_contents()->GetView()->GetContainerBounds(&bounds);
sad_tab_->SetBounds(gfx::Rect(bounds.size()));
#elif defined(TOOLKIT_GTK) || defined(OS_MACOSX)
sad_tab_.reset(chrome::SadTab::Create(web_contents(), kind));
sad_tab_->Show();
#else
#error Unknown platform
#endif
}
| 36.836538 | 80 | 0.734534 | leiferikb |
d6c1460fa282081f4dc5ec2f5ee957c06181edd9 | 22,926 | cpp | C++ | src/libandroidfw/LoadedArsc.cpp | mnlsm/aapt | 86553bc9bc0edacaf15cc4cbea278e6c641f93be | [
"Apache-2.0"
] | null | null | null | src/libandroidfw/LoadedArsc.cpp | mnlsm/aapt | 86553bc9bc0edacaf15cc4cbea278e6c641f93be | [
"Apache-2.0"
] | null | null | null | src/libandroidfw/LoadedArsc.cpp | mnlsm/aapt | 86553bc9bc0edacaf15cc4cbea278e6c641f93be | [
"Apache-2.0"
] | 1 | 2019-06-22T09:06:34.000Z | 2019-06-22T09:06:34.000Z | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define ATRACE_TAG ATRACE_TAG_RESOURCES
#include "androidfw/LoadedArsc.h"
#include <cstddef>
#include <limits>
//#include "android-base/logging.h"
#include "android-base/stringprintf.h"
#include "utils/ByteOrder.h"
#include "utils/Trace.h"
#ifdef _WIN32
#include <windows.h>
#ifdef ERROR
#undef ERROR
#endif
#endif
#include "androidfw/ByteBucketArray.h"
#include "androidfw/Chunk.h"
#include "androidfw/ResourceUtils.h"
#include "androidfw/Util.h"
using android::base::StringPrintf;
namespace android {
static const int kAppPackageId = 0x7f;
// Element of a TypeSpec array. See TypeSpec.
struct Type {
// The configuration for which this type defines entries.
// This is already converted to host endianness.
ResTable_config configuration;
// Pointer to the mmapped data where entry definitions are kept.
const ResTable_type* type;
};
// TypeSpec is going to be immediately proceeded by
// an array of Type structs, all in the same block of memory.
struct TypeSpec {
// Pointer to the mmapped data where flags are kept.
// Flags denote whether the resource entry is public
// and under which configurations it varies.
const ResTable_typeSpec* type_spec;
// The number of types that follow this struct.
// There is a type for each configuration
// that entries are defined for.
size_t type_count;
// Trick to easily access a variable number of Type structs
// proceeding this struct, and to ensure their alignment.
const Type types[0];
};
// TypeSpecPtr points to the block of memory that holds
// a TypeSpec struct, followed by an array of Type structs.
// TypeSpecPtr is a managed pointer that knows how to delete
// itself.
using TypeSpecPtr = util::unique_cptr<TypeSpec>;
namespace {
// Builder that helps accumulate Type structs and then create a single
// contiguous block of memory to store both the TypeSpec struct and
// the Type structs.
class TypeSpecPtrBuilder {
public:
TypeSpecPtrBuilder(const ResTable_typeSpec* header) : header_(header) {}
void AddType(const ResTable_type* type) {
ResTable_config config;
config.copyFromDtoH(type->config);
types_.push_back(Type{config, type});
}
TypeSpecPtr Build() {
// Check for overflow.
if ((UINT_MAX - sizeof(TypeSpec)) / sizeof(Type) < types_.size()) {
return {};
}
TypeSpec* type_spec = (TypeSpec*)::malloc(sizeof(TypeSpec) + (types_.size() * sizeof(Type)));
type_spec->type_spec = header_;
type_spec->type_count = types_.size();
memcpy(type_spec + 1, types_.data(), types_.size() * sizeof(Type));
return TypeSpecPtr(type_spec);
}
private:
DISALLOW_COPY_AND_ASSIGN(TypeSpecPtrBuilder);
const ResTable_typeSpec* header_;
std::vector<Type> types_;
};
} // namespace
bool LoadedPackage::FindEntry(uint8_t type_idx, uint16_t entry_idx, const ResTable_config& config,
LoadedArscEntry* out_entry, ResTable_config* out_selected_config,
uint32_t* out_flags) const {
ATRACE_CALL();
// If the type IDs are offset in this package, we need to take that into account when searching
// for a type.
const TypeSpecPtr& ptr = type_specs_[type_idx - type_id_offset_];
if (ptr == nullptr) {
return false;
}
// Don't bother checking if the entry ID is larger than
// the number of entries.
if (entry_idx >= dtohl(ptr->type_spec->entryCount)) {
return false;
}
const ResTable_config* best_config = nullptr;
const ResTable_type* best_type = nullptr;
uint32_t best_offset = 0;
for (uint32_t i = 0; i < ptr->type_count; i++) {
const Type* type = &ptr->types[i];
if (type->configuration.match(config) &&
(best_config == nullptr || type->configuration.isBetterThan(*best_config, &config))) {
// The configuration matches and is better than the previous selection.
// Find the entry value if it exists for this configuration.
size_t entry_count = dtohl(type->type->entryCount);
if (entry_idx < entry_count) {
const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>(
reinterpret_cast<const uint8_t*>(type->type) + dtohs(type->type->header.headerSize));
const uint32_t offset = dtohl(entry_offsets[entry_idx]);
if (offset != ResTable_type::NO_ENTRY) {
// There is an entry for this resource, record it.
best_config = &type->configuration;
best_type = type->type;
best_offset = offset + dtohl(type->type->entriesStart);
}
}
}
}
if (best_type == nullptr) {
return false;
}
const uint32_t* flags = reinterpret_cast<const uint32_t*>(ptr->type_spec + 1);
*out_flags = dtohl(flags[entry_idx]);
*out_selected_config = *best_config;
const ResTable_entry* best_entry = reinterpret_cast<const ResTable_entry*>(
reinterpret_cast<const uint8_t*>(best_type) + best_offset);
out_entry->entry = best_entry;
out_entry->type_string_ref = StringPoolRef(&type_string_pool_, best_type->id - 1);
out_entry->entry_string_ref = StringPoolRef(&key_string_pool_, dtohl(best_entry->key.index));
return true;
}
// The destructor gets generated into arbitrary translation units
// if left implicit, which causes the compiler to complain about
// forward declarations and incomplete types.
LoadedArsc::~LoadedArsc() {}
bool LoadedArsc::FindEntry(uint32_t resid, const ResTable_config& config,
LoadedArscEntry* out_entry, ResTable_config* out_selected_config,
uint32_t* out_flags) const {
ATRACE_CALL();
const uint8_t package_id = get_package_id(resid);
const uint8_t type_id = get_type_id(resid);
const uint16_t entry_id = get_entry_id(resid);
if (type_id == 0) {
return false;
}
for (const auto& loaded_package : packages_) {
if (loaded_package->package_id_ == package_id) {
return loaded_package->FindEntry(type_id - 1, entry_id, config, out_entry,
out_selected_config, out_flags);
}
}
return false;
}
const LoadedPackage* LoadedArsc::GetPackageForId(uint32_t resid) const {
const uint8_t package_id = get_package_id(resid);
for (const auto& loaded_package : packages_) {
if (loaded_package->package_id_ == package_id) {
return loaded_package.get();
}
}
return nullptr;
}
static bool VerifyType(const Chunk& chunk) {
ATRACE_CALL();
const ResTable_type* header = chunk.header<ResTable_type, kResTableTypeMinSize>();
const size_t entry_count = dtohl(header->entryCount);
if (entry_count > USHRT_MAX) {
return false;
}
// Make sure that there is enough room for the entry offsets.
const size_t offsets_offset = chunk.header_size();
const size_t entries_offset = dtohl(header->entriesStart);
const size_t offsets_length = sizeof(uint32_t) * entry_count;
if (offsets_offset + offsets_length > entries_offset) {
return false;
}
if (entries_offset > chunk.size()) {
return false;
}
if (entries_offset & 0x03) {
return false;
}
// Check each entry offset.
const uint32_t* offsets =
reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint8_t*>(header) + offsets_offset);
for (size_t i = 0; i < entry_count; i++) {
uint32_t offset = dtohl(offsets[i]);
if (offset != ResTable_type::NO_ENTRY) {
// Check that the offset is aligned.
if (offset & 0x03) {
return false;
}
// Check that the offset doesn't overflow.
if (offset > UINT_MAX - entries_offset) {
// Overflow in offset.
return false;
}
offset += entries_offset;
if (offset > chunk.size() - sizeof(ResTable_entry)) {
return false;
}
const ResTable_entry* entry = reinterpret_cast<const ResTable_entry*>(
reinterpret_cast<const uint8_t*>(header) + offset);
const size_t entry_size = dtohs(entry->size);
if (entry_size < sizeof(*entry)) {
return false;
}
// Check the declared entrySize.
if (entry_size > chunk.size() || offset > chunk.size() - entry_size) {
return false;
}
// If this is a map entry, then keep validating.
if (entry_size >= sizeof(ResTable_map_entry)) {
const ResTable_map_entry* map = reinterpret_cast<const ResTable_map_entry*>(entry);
const size_t map_entry_count = dtohl(map->count);
size_t map_entries_start = offset + entry_size;
if (map_entries_start & 0x03) {
return false;
}
// Each entry is sizeof(ResTable_map) big.
if (map_entry_count > ((chunk.size() - map_entries_start) / sizeof(ResTable_map))) {
return false;
}
// Great, all the map entries fit!.
} else {
// There needs to be room for one Res_value struct.
if (offset + entry_size > chunk.size() - sizeof(Res_value)) {
return false;
}
const Res_value* value = reinterpret_cast<const Res_value*>(
reinterpret_cast<const uint8_t*>(entry) + entry_size);
const size_t value_size = dtohs(value->size);
if (value_size < sizeof(Res_value)) {
return false;
}
if (value_size > chunk.size() || offset + entry_size > chunk.size() - value_size) {
return false;
}
}
}
}
return true;
}
void LoadedPackage::CollectConfigurations(bool exclude_mipmap,
std::set<ResTable_config>* out_configs) const {
char16_t mipmap[] = { 'm', 'i', 'p', 'm', 'a', 'p', '\0' };
const std::u16string kMipMap(mipmap);
const size_t type_count = type_specs_.size();
for (size_t i = 0; i < type_count; i++) {
const util::unique_cptr<TypeSpec>& type_spec = type_specs_[i];
if (type_spec != nullptr) {
if (exclude_mipmap) {
const int type_idx = type_spec->type_spec->id - 1;
size_t type_name_len;
const char16_t* type_name16 = type_string_pool_.stringAt(type_idx, &type_name_len);
if (type_name16 != nullptr) {
if (kMipMap.compare(0, std::u16string::npos, type_name16, type_name_len) == 0) {
// This is a mipmap type, skip collection.
continue;
}
}
const char* type_name = type_string_pool_.string8At(type_idx, &type_name_len);
if (type_name != nullptr) {
if (strncmp(type_name, "mipmap", type_name_len) == 0) {
// This is a mipmap type, skip collection.
continue;
}
}
}
for (size_t j = 0; j < type_spec->type_count; j++) {
out_configs->insert(type_spec->types[j].configuration);
}
}
}
}
void LoadedPackage::CollectLocales(bool canonicalize, std::set<std::string>* out_locales) const {
char temp_locale[RESTABLE_MAX_LOCALE_LEN];
const size_t type_count = type_specs_.size();
for (size_t i = 0; i < type_count; i++) {
const util::unique_cptr<TypeSpec>& type_spec = type_specs_[i];
if (type_spec != nullptr) {
for (size_t j = 0; j < type_spec->type_count; j++) {
const ResTable_config& configuration = type_spec->types[j].configuration;
if (configuration.locale != 0) {
configuration.getBcp47Locale(temp_locale, canonicalize);
std::string locale(temp_locale);
out_locales->insert(std::move(locale));
}
}
}
}
}
uint32_t LoadedPackage::FindEntryByName(const std::u16string& type_name,
const std::u16string& entry_name) const {
ssize_t type_idx = type_string_pool_.indexOfString(type_name.data(), type_name.size());
if (type_idx < 0) {
return 0u;
}
ssize_t key_idx = key_string_pool_.indexOfString(entry_name.data(), entry_name.size());
if (key_idx < 0) {
return 0u;
}
const TypeSpec* type_spec = type_specs_[type_idx].get();
if (type_spec == nullptr) {
return 0u;
}
for (size_t ti = 0; ti < type_spec->type_count; ti++) {
const Type* type = &type_spec->types[ti];
size_t entry_count = dtohl(type->type->entryCount);
for (size_t entry_idx = 0; entry_idx < entry_count; entry_idx++) {
const uint32_t* entry_offsets = reinterpret_cast<const uint32_t*>(
reinterpret_cast<const uint8_t*>(type->type) + dtohs(type->type->header.headerSize));
const uint32_t offset = dtohl(entry_offsets[entry_idx]);
if (offset != ResTable_type::NO_ENTRY) {
const ResTable_entry* entry =
reinterpret_cast<const ResTable_entry*>(reinterpret_cast<const uint8_t*>(type->type) +
dtohl(type->type->entriesStart) + offset);
if (dtohl(entry->key.index) == static_cast<uint32_t>(key_idx)) {
// The package ID will be overridden by the caller (due to runtime assignment of package
// IDs for shared libraries).
return make_resid(0x00, type_idx + type_id_offset_ + 1, entry_idx);
}
}
}
}
return 0u;
}
std::unique_ptr<LoadedPackage> LoadedPackage::Load(const Chunk& chunk) {
ATRACE_CALL();
std::unique_ptr<LoadedPackage> loaded_package{new LoadedPackage()};
const size_t kMinPackageSize =
sizeof(ResTable_package) - sizeof(decltype(ResTable_package::typeIdOffset));
const ResTable_package* header = chunk.header<ResTable_package, kMinPackageSize>();
if (header == nullptr) {
return {};
}
loaded_package->package_id_ = dtohl(header->id);
if (loaded_package->package_id_ == 0) {
// Package ID of 0 means this is a shared library.
loaded_package->dynamic_ = true;
}
if (header->header.headerSize >= sizeof(ResTable_package)) {
uint32_t type_id_offset = dtohl(header->typeIdOffset);
if (type_id_offset > UCHAR_MAX) {
return {};
}
loaded_package->type_id_offset_ = static_cast<int>(type_id_offset);
}
util::ReadUtf16StringFromDevice(header->name, arraysize(header->name),
&loaded_package->package_name_);
// A TypeSpec builder. We use this to accumulate the set of Types
// available for a TypeSpec, and later build a single, contiguous block
// of memory that holds all the Types together with the TypeSpec.
std::unique_ptr<TypeSpecPtrBuilder> types_builder;
// Keep track of the last seen type index. Since type IDs are 1-based,
// this records their index, which is 0-based (type ID - 1).
uint8_t last_type_idx = 0;
ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
while (iter.HasNext()) {
const Chunk child_chunk = iter.Next();
switch (child_chunk.type()) {
case RES_STRING_POOL_TYPE: {
const uintptr_t pool_address =
reinterpret_cast<uintptr_t>(child_chunk.header<ResChunk_header>());
const uintptr_t header_address = reinterpret_cast<uintptr_t>(header);
if (pool_address == header_address + dtohl(header->typeStrings)) {
// This string pool is the type string pool.
status_t err = loaded_package->type_string_pool_.setTo(
child_chunk.header<ResStringPool_header>(), child_chunk.size());
if (err != NO_ERROR) {
return {};
}
} else if (pool_address == header_address + dtohl(header->keyStrings)) {
// This string pool is the key string pool.
status_t err = loaded_package->key_string_pool_.setTo(
child_chunk.header<ResStringPool_header>(), child_chunk.size());
if (err != NO_ERROR) {
return {};
}
} else {
}
} break;
case RES_TABLE_TYPE_SPEC_TYPE: {
ATRACE_NAME("LoadTableTypeSpec");
// Starting a new TypeSpec, so finish the old one if there was one.
if (types_builder) {
TypeSpecPtr type_spec_ptr = types_builder->Build();
if (type_spec_ptr == nullptr) {
return {};
}
loaded_package->type_specs_.editItemAt(last_type_idx) = std::move(type_spec_ptr);
types_builder = {};
last_type_idx = 0;
}
const ResTable_typeSpec* type_spec = child_chunk.header<ResTable_typeSpec>();
if (type_spec == nullptr) {
return {};
}
if (type_spec->id == 0) {
return {};
}
if (loaded_package->type_id_offset_ + static_cast<int>(type_spec->id) >
UCHAR_MAX) {
return {};
}
// The data portion of this chunk contains entry_count 32bit entries,
// each one representing a set of flags.
// Here we only validate that the chunk is well formed.
const size_t entry_count = dtohl(type_spec->entryCount);
// There can only be 2^16 entries in a type, because that is the ID
// space for entries (EEEE) in the resource ID 0xPPTTEEEE.
if (entry_count > UCHAR_MAX) {
return {};
}
if (entry_count * sizeof(uint32_t) > chunk.data_size()) {
return {};
}
last_type_idx = type_spec->id - 1;
types_builder = util::make_unique<TypeSpecPtrBuilder>(type_spec);
} break;
case RES_TABLE_TYPE_TYPE: {
const ResTable_type* type = child_chunk.header<ResTable_type, kResTableTypeMinSize>();
if (type == nullptr) {
return {};
}
if (type->id == 0) {
return {};
}
// Type chunks must be preceded by their TypeSpec chunks.
if (!types_builder || type->id - 1 != last_type_idx) {
return {};
}
if (!VerifyType(child_chunk)) {
return {};
}
types_builder->AddType(type);
} break;
case RES_TABLE_LIBRARY_TYPE: {
const ResTable_lib_header* lib = child_chunk.header<ResTable_lib_header>();
if (lib == nullptr) {
return {};
}
if (child_chunk.data_size() / sizeof(ResTable_lib_entry) < dtohl(lib->count)) {
return {};
}
loaded_package->dynamic_package_map_.reserve(dtohl(lib->count));
const ResTable_lib_entry* const entry_begin =
reinterpret_cast<const ResTable_lib_entry*>(child_chunk.data_ptr());
const ResTable_lib_entry* const entry_end = entry_begin + dtohl(lib->count);
for (auto entry_iter = entry_begin; entry_iter != entry_end; ++entry_iter) {
std::string package_name;
util::ReadUtf16StringFromDevice(entry_iter->packageName,
arraysize(entry_iter->packageName), &package_name);
if (dtohl(entry_iter->packageId) >= UCHAR_MAX) {
return {};
}
loaded_package->dynamic_package_map_.emplace_back(std::move(package_name),
dtohl(entry_iter->packageId));
}
} break;
default:
break;
}
}
// Finish the last TypeSpec.
if (types_builder) {
TypeSpecPtr type_spec_ptr = types_builder->Build();
if (type_spec_ptr == nullptr) {
return {};
}
loaded_package->type_specs_.editItemAt(last_type_idx) = std::move(type_spec_ptr);
}
if (iter.HadError()) {
return {};
}
return loaded_package;
}
bool LoadedArsc::LoadTable(const Chunk& chunk, bool load_as_shared_library) {
ATRACE_CALL();
const ResTable_header* header = chunk.header<ResTable_header>();
if (header == nullptr) {
return false;
}
const size_t package_count = dtohl(header->packageCount);
size_t packages_seen = 0;
packages_.reserve(package_count);
ChunkIterator iter(chunk.data_ptr(), chunk.data_size());
while (iter.HasNext()) {
const Chunk child_chunk = iter.Next();
switch (child_chunk.type()) {
case RES_STRING_POOL_TYPE:
// Only use the first string pool. Ignore others.
if (global_string_pool_.getError() == NO_INIT) {
status_t err = global_string_pool_.setTo(child_chunk.header<ResStringPool_header>(),
child_chunk.size());
if (err != NO_ERROR) {
return false;
}
} else {
}
break;
case RES_TABLE_PACKAGE_TYPE: {
if (packages_seen + 1 > package_count) {
return false;
}
packages_seen++;
std::unique_ptr<LoadedPackage> loaded_package = LoadedPackage::Load(child_chunk);
if (!loaded_package) {
return false;
}
// Mark the package as dynamic if we are forcefully loading the Apk as a shared library.
if (loaded_package->package_id_ == kAppPackageId) {
loaded_package->dynamic_ = load_as_shared_library;
}
loaded_package->system_ = system_;
packages_.push_back(std::move(loaded_package));
} break;
default:
break;
}
}
if (iter.HadError()) {
return false;
}
return true;
}
std::unique_ptr<const LoadedArsc> LoadedArsc::Load(const void* data, size_t len, bool system,
bool load_as_shared_library) {
ATRACE_CALL();
// Not using make_unique because the constructor is private.
std::unique_ptr<LoadedArsc> loaded_arsc(new LoadedArsc());
loaded_arsc->system_ = system;
ChunkIterator iter(data, len);
while (iter.HasNext()) {
const Chunk chunk = iter.Next();
switch (chunk.type()) {
case RES_TABLE_TYPE:
if (!loaded_arsc->LoadTable(chunk, load_as_shared_library)) {
return {};
}
break;
default:
break;
}
}
if (iter.HadError()) {
return {};
}
// Need to force a move for mingw32.
return std::move(loaded_arsc);
}
} // namespace android
| 33.964444 | 100 | 0.62379 | mnlsm |
d6c2411a777c7752c8a0f78e84086e0e3df44f61 | 1,280 | cc | C++ | third_party/blink/renderer/core/css/css_custom_ident_value.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/css/css_custom_ident_value.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/css/css_custom_ident_value.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/css/css_custom_ident_value.h"
#include "third_party/blink/renderer/core/css/css_markup.h"
#include "third_party/blink/renderer/core/css/properties/css_unresolved_property.h"
#include "third_party/blink/renderer/platform/wtf/text/string_builder.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
CSSCustomIdentValue::CSSCustomIdentValue(const AtomicString& str)
: CSSValue(kCustomIdentClass),
string_(str),
property_id_(CSSPropertyInvalid) {}
CSSCustomIdentValue::CSSCustomIdentValue(CSSPropertyID id)
: CSSValue(kCustomIdentClass), string_(), property_id_(id) {
DCHECK(IsKnownPropertyID());
}
String CSSCustomIdentValue::CustomCSSText() const {
if (IsKnownPropertyID()) {
return CSSUnresolvedProperty::Get(property_id_)
.GetPropertyNameAtomicString();
}
StringBuilder builder;
SerializeIdentifier(string_, builder);
return builder.ToString();
}
void CSSCustomIdentValue::TraceAfterDispatch(blink::Visitor* visitor) {
CSSValue::TraceAfterDispatch(visitor);
}
} // namespace blink
| 32.820513 | 83 | 0.778125 | zipated |
d6c287728f25639f7599e72c752eba49a3fa691f | 4,455 | cpp | C++ | src/DriveTrain.cpp | shiruz/SampleCode | 2fb3d8701bbb86f6609341a636f05134132b2efd | [
"MIT"
] | null | null | null | src/DriveTrain.cpp | shiruz/SampleCode | 2fb3d8701bbb86f6609341a636f05134132b2efd | [
"MIT"
] | null | null | null | src/DriveTrain.cpp | shiruz/SampleCode | 2fb3d8701bbb86f6609341a636f05134132b2efd | [
"MIT"
] | null | null | null | #include "main.h"
//Veriables for tweaking the drive train.
bool IsBreaking = false;
bool IsForward = true;
//Returns true/false as to wheter the drive wheels have
//reached their position goal set by driveForDistance
bool AtDistanceDriveGoal(int threshold) {
return (abs(FLMotor.get_position() - FLMotor.get_target_position()) < threshold) &&(abs(FLMotor.get_position() - FLMotor.get_target_position()) < threshold);
}
//Sets drive trains target, but does not wait for them to reach their target
void Drive(double leftInches, double rightInches, int speed) {
FRMotor.move_relative(leftInches, speed);
BRMotor.move_relative(rightInches, -speed);
pros::delay(10);
FLMotor.move_relative(rightInches, speed);
BLMotor.move_relative(leftInches, -speed);
}
//Turns the robot to the target position
void Rotate(double turn, int speed) {
FLMotor.move_relative(turn , speed);
FRMotor.move_relative(-turn, speed);
BLMotor.move_relative(turn, speed);
BRMotor.move_relative(-turn, speed);
}
//Function for setting the drive trian breaks
void BrakeDriveTrain() {
IsBreaking = true;
FLMotor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD);
FRMotor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD);
BLMotor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD);
BRMotor.set_brake_mode(pros::E_MOTOR_BRAKE_HOLD);
FLMotor.move_relative(0,200);
FRMotor.move_relative(0,200);
BLMotor.move_relative(0,200);
BRMotor.move_relative(0,200);
}
//Function for releasing the drive train breaks
void UnBrakeDriveTrain() {
IsBreaking = false;
FLMotor.set_brake_mode(pros::E_MOTOR_BRAKE_COAST);
FRMotor.set_brake_mode(pros::E_MOTOR_BRAKE_COAST);
BLMotor.set_brake_mode(pros::E_MOTOR_BRAKE_COAST);
BRMotor.set_brake_mode(pros::E_MOTOR_BRAKE_COAST);
}
//Function for seting the cap flipper side to be the front side
void SetBackwords() {
FLMotor.set_reversed(true);
FRMotor.set_reversed(false);
BLMotor.set_reversed(true);
BRMotor.set_reversed(false);
IsForward = false;
}
//Function for seting the ball shooter side to be the front side
void SetForwards() {
FLMotor.set_reversed(false);
FRMotor.set_reversed(true);
BLMotor.set_reversed(false);
BRMotor.set_reversed(true);
IsForward = true;
}
//Thread for all drive train controls.
void DriveTrain_fn(void* param) {
int LeftControls = master.get_analog(ANALOG_LEFT_Y);
int RightControls = master.get_analog(ANALOG_RIGHT_Y);
//Setting the right motors to be reversed
FLMotor.set_reversed(false);
FRMotor.set_reversed(true);
BLMotor.set_reversed(false);
BRMotor.set_reversed(true);
while (true) {
//Gets the joistics position and maps them to a veriable.
LeftControls = master.get_analog(ANALOG_LEFT_Y);
RightControls = master.get_analog(ANALOG_RIGHT_Y);
//Switches the motor sides if the drive train is reversed.
if (IsBreaking != true) {
if (IsForward == true) {
FLMotor.move(LeftControls);
BLMotor.move(LeftControls);
FRMotor.move(RightControls);
BRMotor.move(RightControls);
}
else {
FLMotor.move(RightControls);
BLMotor.move(RightControls);
FRMotor.move(LeftControls);
BRMotor.move(LeftControls);
}
}
if (master.get_digital_new_press(DIGITAL_UP)) {
if (IsBreaking == true) {
UnBrakeDriveTrain();
}
else {
BrakeDriveTrain();
}
}
//Drive train break controls.
if (master.get_digital_new_press(DIGITAL_DOWN)) {
if (IsBreaking == true) {
UnBrakeDriveTrain();
Rotate(1580, 50);
}
else {
BrakeDriveTrain();
Rotate(1580, 50);
}
}
//Drive train directional controls.
if (master.get_digital_new_press(DIGITAL_L1)) {
SetBackwords();
}
if (master.get_digital_new_press(DIGITAL_R1)) {
SetForwards();
}
if (IsForward == true) {
//Rotate 90
if (master.get_digital_new_press(DIGITAL_LEFT)) {
Rotate(790, 50);
pros::delay(1200);
}
else if (master.get_digital_new_press(DIGITAL_RIGHT)) {
Rotate(-790, 50);
pros::delay(1200);
}
}
else {
//Rotate 90
if (master.get_digital_new_press(DIGITAL_LEFT)) {
Rotate(-790, 50);
pros::delay(1200);
}
else if (master.get_digital_new_press(DIGITAL_RIGHT)) {
Rotate(790, 50);
pros::delay(1200);
}
}
}
}
| 27 | 159 | 0.683726 | shiruz |
d6c2afef18e6106cc75075c52b23268618675eb5 | 3,430 | cc | C++ | services/network/dns_config_change_manager_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | services/network/dns_config_change_manager_unittest.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | services/network/dns_config_change_manager_unittest.cc | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/network/dns_config_change_manager.h"
#include <climits>
#include <utility>
#include "base/run_loop.h"
#include "base/test/task_environment.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace network {
namespace {
class TestDnsConfigChangeManagerClient
: public mojom::DnsConfigChangeManagerClient {
public:
explicit TestDnsConfigChangeManagerClient(DnsConfigChangeManager* manager) {
mojo::Remote<mojom::DnsConfigChangeManager> manager_remote;
manager->AddReceiver(manager_remote.BindNewPipeAndPassReceiver());
manager_remote->RequestNotifications(receiver_.BindNewPipeAndPassRemote());
}
void OnDnsConfigChanged() override {
num_notifications_++;
if (num_notifications_ >= num_notifications_expected_)
run_loop_.Quit();
}
int num_notifications() { return num_notifications_; }
void WaitForNotification(int num_notifications_expected) {
num_notifications_expected_ = num_notifications_expected;
if (num_notifications_ < num_notifications_expected_)
run_loop_.Run();
}
private:
int num_notifications_ = 0;
int num_notifications_expected_ = INT_MAX;
base::RunLoop run_loop_;
mojo::Receiver<mojom::DnsConfigChangeManagerClient> receiver_{this};
DISALLOW_COPY_AND_ASSIGN(TestDnsConfigChangeManagerClient);
};
class DnsConfigChangeManagerTest : public testing::Test {
public:
DnsConfigChangeManagerTest() {}
DnsConfigChangeManager* manager() { return &manager_; }
TestDnsConfigChangeManagerClient* client() { return &client_; }
private:
base::test::TaskEnvironment task_environment_;
std::unique_ptr<net::NetworkChangeNotifier> notifier_mock_ =
net::NetworkChangeNotifier::CreateMockIfNeeded();
DnsConfigChangeManager manager_;
TestDnsConfigChangeManagerClient client_{&manager_};
DISALLOW_COPY_AND_ASSIGN(DnsConfigChangeManagerTest);
};
TEST_F(DnsConfigChangeManagerTest, Notification) {
EXPECT_EQ(0, client()->num_notifications());
net::NetworkChangeNotifier::NotifyObserversOfDNSChangeForTests();
client()->WaitForNotification(1);
EXPECT_EQ(1, client()->num_notifications());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, client()->num_notifications());
}
TEST_F(DnsConfigChangeManagerTest, MultipleNotification) {
EXPECT_EQ(0, client()->num_notifications());
net::NetworkChangeNotifier::NotifyObserversOfDNSChangeForTests();
net::NetworkChangeNotifier::NotifyObserversOfDNSChangeForTests();
client()->WaitForNotification(2);
EXPECT_EQ(2, client()->num_notifications());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, client()->num_notifications());
}
TEST_F(DnsConfigChangeManagerTest, MultipleClients) {
TestDnsConfigChangeManagerClient client2(manager());
EXPECT_EQ(0, client()->num_notifications());
EXPECT_EQ(0, client2.num_notifications());
net::NetworkChangeNotifier::NotifyObserversOfDNSChangeForTests();
client()->WaitForNotification(1);
client2.WaitForNotification(1);
EXPECT_EQ(1, client()->num_notifications());
EXPECT_EQ(1, client2.num_notifications());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, client()->num_notifications());
EXPECT_EQ(1, client2.num_notifications());
}
} // namespace
} // namespace network
| 31.46789 | 79 | 0.774052 | sarang-apps |
d6c2bc7c8f35690769cadfcc074d78082ef4214d | 2,892 | cpp | C++ | tagGame/ControllerPursue.cpp | funge/ai4games | b72be3648fa0da611b999aa01aec8560728bcdd7 | [
"MIT"
] | 1 | 2020-01-11T18:53:53.000Z | 2020-01-11T18:53:53.000Z | tagGame/ControllerPursue.cpp | funge/ai4games | b72be3648fa0da611b999aa01aec8560728bcdd7 | [
"MIT"
] | null | null | null | tagGame/ControllerPursue.cpp | funge/ai4games | b72be3648fa0da611b999aa01aec8560728bcdd7 | [
"MIT"
] | 1 | 2019-08-27T17:24:27.000Z | 2019-08-27T17:24:27.000Z | // ----------------------------------------------------------------------------
//
// tagGame - Example code from the book:
//
// Artficial Intelligence for Computer Games: An Introduction
// by John David Funge
//
// www.ai4games.org
//
// Source code distributed under the Copyright (c) 2003-2007, John David Funge
// Original author: John David Funge (www.jfunge.com)
//
// Licensed under the Academic Free License version 3.0
// (for details see LICENSE.txt in this directory).
//
// ----------------------------------------------------------------------------
#include "ControllerPursue.h"
#include "Perception.h"
#include "Timer.h"
#include "Util2D.h"
using namespace tagGame;
using namespace std;
ControllerPursue::ControllerPursue(PerceptionPtr perception) :
Controller(perception),
isAngry(false)
{
}
ControllerPursue::~ControllerPursue()
{
}
void ControllerPursue::calcAction()
{
// Currently always chases nearest, TODO: take anger into account
RealVec v(perception->nearestCharacterPosition().relativeTo(perception->myPosition()));
// go as fast as possible all the time!
// TODO: consider predicating speed on v.length()
action.setDesiredSpeed(1.0);
action.setDesiredDirection(v.normalize());
}
Character* ControllerPursue::calcWhoToChase()
{
Real const minChaseDist = Real(10);
Real const minChaseRatio = 0.5;
Character* const c(perception->nearestCharacter());
Character* const t(perception->getTagged());
// Sometimes it is obvious who to chase
if (c == t) { return c; }
Real const dc = perception->distanceToNearestCharacter();
// If a character is really close, chase them no matter what
// Note: minChaseDist is part of the character definition passed in
// to the controller's constructor
if (dc < minChaseDist) { return c; }
Real const dt = perception->distanceToTagged();
// If the character who last tagged me is a lot farther away forget it
// Note: minChaseRatio is also part of the character definition
if (dt/dc < minChaseRatio) { return c; }
// OK, it's reasonable to chase the character who last tagged me
return t;
}
void ControllerPursue::calcIsAngry()
{
if (!perception->myselfTagged())
{ // If I'm not tagged then don't be angry
isAngry = false;
return;
}
// If I'm tagged and angry then stay angry
if (isAngry) { return; }
// If I'm tagged and not angry then there's a small chance I'll get angry
Real probAngry = 0.1;
// But if I just got tagged, then I get angry in proportion
// to how often I've been tagged recently
if (perception->myselfRecentlyTagged())
{
int const n(max(9, perception->myRecentTaggedCount()));
probAngry = Real(n)/Real(10);
}
Real const r = MathUtil::uniform01();
if (r < probAngry) { isAngry = true; }
else { isAngry = false; }
}
| 28.633663 | 90 | 0.647994 | funge |
d6c312ae5a2cd1de1511c43c115d350036a0fd58 | 2,019 | cpp | C++ | Amazon/14 - Burning Tree.cpp | thisisbipin/-6Companies30days | 5d4b8a10cb00f395f3f12812de82588d10fb2426 | [
"MIT"
] | null | null | null | Amazon/14 - Burning Tree.cpp | thisisbipin/-6Companies30days | 5d4b8a10cb00f395f3f12812de82588d10fb2426 | [
"MIT"
] | null | null | null | Amazon/14 - Burning Tree.cpp | thisisbipin/-6Companies30days | 5d4b8a10cb00f395f3f12812de82588d10fb2426 | [
"MIT"
] | null | null | null | class Solution {
unordered_map<Node*, Node*> parent;
public:
Node* populate(Node* root, int target) {
queue<Node*> q;
q.push(root);
Node* tar = NULL;
bool check = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
Node* temp = q.front();
q.pop();
if (temp->data == target && check == 0) {
tar = temp;
check = 1;
}
if (temp->left != NULL) {
parent[temp->left] = temp;
q.push(temp->left);
}
if (temp->right != NULL) {
parent[temp->right] = temp;
q.push(temp->right);
}
}
}
return tar;
}
int minTime(Node* root, int target)
{
Node* getval = populate(root, target);
if (getval == NULL)
return 0;
unordered_set<Node*> vis;
int res = 0;
queue<Node*> q;
q.push(getval);
while (!q.empty()) {
int qs = q.size();
bool found = false;
while (qs--) {
Node* temp = q.front();
q.pop();
vis.insert(temp);
if ((parent[temp]) && (vis.find(parent[temp]) == vis.end())) {
q.push(parent[temp]);
found = true;
}
if ((temp->left != NULL) && (vis.find(temp->left) == vis.end())) {
q.push(temp->left);
found = true;
}
if ((temp->right != NULL) && (vis.find(temp->right) == vis.end())) {
q.push(temp->right);
found = true;
}
}
if (found)
res++;
}
return res;
}
}; | 30.590909 | 85 | 0.34522 | thisisbipin |
d6c390d5dd7a4d95ce241765a17f952fc87a3bd4 | 1,528 | hpp | C++ | indexer/locality_object.hpp | ToshUxanoff/omim | a8acb5821c72bd78847d1c49968b14d15b1e06ee | [
"Apache-2.0"
] | 1 | 2021-07-02T08:45:02.000Z | 2021-07-02T08:45:02.000Z | indexer/locality_object.hpp | ToshUxanoff/omim | a8acb5821c72bd78847d1c49968b14d15b1e06ee | [
"Apache-2.0"
] | 1 | 2020-06-15T15:16:23.000Z | 2020-06-15T15:59:19.000Z | indexer/locality_object.hpp | maksimandrianov/omim | cbc5a80d09d585afbda01e471887f63b9d3ab0c2 | [
"Apache-2.0"
] | 1 | 2018-10-01T10:27:21.000Z | 2018-10-01T10:27:21.000Z | #pragma once
#include "geometry/point2d.hpp"
#include "base/buffer_vector.hpp"
#include "base/geo_object_id.hpp"
#include <cstdint>
#include <vector>
namespace indexer
{
// Class for intermediate objects used to build LocalityIndex.
class LocalityObject
{
public:
// Decodes id stored in LocalityIndex. See GetStoredId().
static base::GeoObjectId FromStoredId(uint64_t storedId)
{
return base::GeoObjectId(storedId >> 2 | storedId << 62);
}
// We need LocalityIndex object id to be at most numeric_limits<int64_t>::max().
// We use incremental encoding for ids and need to keep ids of close object close if it is possible.
// To ensure it we move two leading bits which encodes object type to the end of id.
uint64_t GetStoredId() const { return m_id << 2 | m_id >> 62; }
void Deserialize(char const * data);
template <typename ToDo>
void ForEachPoint(ToDo && toDo) const
{
for (auto const & p : m_points)
toDo(p);
}
template <typename ToDo>
void ForEachTriangle(ToDo && toDo) const
{
for (size_t i = 2; i < m_triangles.size(); i += 3)
toDo(m_triangles[i - 2], m_triangles[i - 1], m_triangles[i]);
}
void SetForTests(uint64_t id, m2::PointD point)
{
m_id = id;
m_points.clear();
m_points.push_back(point);
}
private:
uint64_t m_id = 0;
std::vector<m2::PointD> m_points;
// m_triangles[3 * i], m_triangles[3 * i + 1], m_triangles[3 * i + 2] form the i-th triangle.
buffer_vector<m2::PointD, 32> m_triangles;
};
} // namespace indexer
| 26.344828 | 102 | 0.683246 | ToshUxanoff |
d6cc3d7aec44b32084bf0600aa0548d33238e79c | 2,126 | cpp | C++ | test/crypto.cpp | cisco/mlspp | 2276e3828927126d053b7e6f9191acadd8b6ccb7 | [
"BSD-2-Clause"
] | 47 | 2018-04-04T18:19:39.000Z | 2022-01-13T16:40:39.000Z | test/crypto.cpp | cisco/mlspp | 2276e3828927126d053b7e6f9191acadd8b6ccb7 | [
"BSD-2-Clause"
] | 73 | 2018-09-19T22:27:52.000Z | 2022-03-30T13:43:44.000Z | test/crypto.cpp | cisco/mlspp | 2276e3828927126d053b7e6f9191acadd8b6ccb7 | [
"BSD-2-Clause"
] | 34 | 2018-03-02T21:15:44.000Z | 2022-01-13T21:58:15.000Z | #include <doctest/doctest.h>
#include <mls/crypto.h>
#include <string>
using namespace mls;
TEST_CASE("Basic HPKE")
{
auto info = random_bytes(100);
auto aad = random_bytes(100);
auto original = random_bytes(100);
for (auto suite_id : all_supported_suites) {
auto suite = CipherSuite{ suite_id };
auto s = bytes{ 0, 1, 2, 3 };
auto x = HPKEPrivateKey::generate(suite);
auto y = HPKEPrivateKey::derive(suite, { 0, 1, 2, 3 });
REQUIRE(x == x);
REQUIRE(y == y);
REQUIRE(x != y);
auto gX = x.public_key;
auto gY = y.public_key;
REQUIRE(gX == gX);
REQUIRE(gY == gY);
REQUIRE(gX != gY);
auto encrypted = gX.encrypt(suite, info, aad, original);
auto decrypted = x.decrypt(suite, info, aad, encrypted);
REQUIRE(original == decrypted);
}
}
TEST_CASE("HPKE Key Serialization")
{
for (auto suite_id : all_supported_suites) {
auto suite = CipherSuite{ suite_id };
auto x = HPKEPrivateKey::derive(suite, { 0, 1, 2, 3 });
auto gX = x.public_key;
HPKEPublicKey parsed{ gX.data };
REQUIRE(parsed == gX);
auto gX2 = tls::get<HPKEPublicKey>(tls::marshal(gX));
REQUIRE(gX2 == gX);
}
}
TEST_CASE("Basic Signature")
{
for (auto suite_id : all_supported_suites) {
auto suite = CipherSuite{ suite_id };
auto a = SignaturePrivateKey::generate(suite);
auto b = SignaturePrivateKey::generate(suite);
REQUIRE(a == a);
REQUIRE(b == b);
REQUIRE(a != b);
REQUIRE(a.public_key == a.public_key);
REQUIRE(b.public_key == b.public_key);
REQUIRE(a.public_key != b.public_key);
auto message = from_hex("01020304");
auto signature = a.sign(suite, message);
REQUIRE(a.public_key.verify(suite, message, signature));
}
}
TEST_CASE("Signature Key Serializion")
{
for (auto suite_id : all_supported_suites) {
auto suite = CipherSuite{ suite_id };
auto x = SignaturePrivateKey::generate(suite);
auto gX = x.public_key;
SignaturePublicKey parsed{ gX.data };
REQUIRE(parsed == gX);
auto gX2 = tls::get<SignaturePublicKey>(tls::marshal(gX));
REQUIRE(gX2 == gX);
}
}
| 23.88764 | 62 | 0.64064 | cisco |
d6cccc0fe0c90e787c54b72f2308bbb21f75a1ee | 13,313 | cpp | C++ | overlay/HardHook_x86.cpp | bogie/mumble | 48c3a19aba885177e2b7a17f90bf5617104b18fa | [
"BSD-3-Clause"
] | 2 | 2016-03-08T07:57:21.000Z | 2017-12-30T22:01:10.000Z | overlay/HardHook_x86.cpp | bogie/mumble | 48c3a19aba885177e2b7a17f90bf5617104b18fa | [
"BSD-3-Clause"
] | null | null | null | overlay/HardHook_x86.cpp | bogie/mumble | 48c3a19aba885177e2b7a17f90bf5617104b18fa | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Mumble Developers 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 FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "HardHook.h"
#include "ods.h"
void *HardHook::pCode = NULL;
unsigned int HardHook::uiCode = 0;
const int HardHook::CODEREPLACESIZE = 6;
const int HardHook::CODEPROTECTSIZE = 16;
/**
* @brief Constructs a new hook without actually injecting.
*/
HardHook::HardHook() : bTrampoline(false), call(0), baseptr(NULL) {
for (int i = 0; i < CODEREPLACESIZE; ++i) {
orig[i] = replace[i] = 0;
}
// assert(CODEREPLACESIZE == sizeof(orig) / sizeof(orig[0]));
// assert(CODEREPLACESIZE == sizeof(replace) / sizeof(replace[0]));
}
/**
* @brief Constructs a new hook by injecting given replacement function into func.
* @see HardHook::setup
* @param func Funktion to inject replacement into.
* @param replacement Function to inject into func.
*/
HardHook::HardHook(voidFunc func, voidFunc replacement)
: bTrampoline(false), call(0), baseptr(NULL) {
for (int i = 0; i < CODEREPLACESIZE; ++i)
orig[i] = replace[i] = 0;
setup(func, replacement);
}
/**
* @return Number of extra bytes.
*/
static unsigned int modrmbytes(unsigned char a, unsigned char b) {
unsigned char lower = (a & 0x0f);
if (a >= 0xc0) {
return 0;
} else if (a >= 0x80) {
if ((lower == 4) || (lower == 12))
return 5;
else
return 4;
} else if (a >= 0x40) {
if ((lower == 4) || (lower == 12))
return 2;
else
return 1;
} else {
if ((lower == 4) || (lower == 12)) {
if ((b & 0x07) == 0x05)
return 5;
else
return 1;
} else if ((lower == 5) || (lower == 13))
return 4;
return 0;
}
}
/**
* @brief Tries to construct a trampoline from original code.
*
* A trampoline is the replacement code that features the original code plus
* a jump back to the original instructions that follow.
* It is called to execute the original behavior. As it is a replacement for
* the original, the original can then be overwritten.
* The size of the trampoline is at least CODEREPLACESIZE. Thus, CODEREPLACESIZE
* bytes of the original code can afterwards be overwritten (and the trampoline
* called after those instructions for the original logic).
* CODEREPLACESIZE has to be smaller than CODEPROTECTSIZE.
*
* As commands must not be destroyed they have to be disassembled to get their length.
* All encountered commands will be part of the trampoline and stored in pCode (shared
* for all trampolines).
*
* If code is encountered that can not be moved into the trampoline (conditionals etc.)
* construction fails and NULL is returned. If enough commands can be saved the
* trampoline is finalized by appending a jump back to the original code. The return value
* in this case will be the address of the newly constructed trampoline.
*
* pCode + offset to trampoline:
* [SAVED CODE FROM ORIGINAL which is >= CODEREPLACESIZE bytes][JUMP BACK TO ORIGINAL CODE]
*
* @param porig Original code
* @return Pointer to trampoline on success. NULL if trampoline construction failed.
*/
void *HardHook::cloneCode(void **porig) {
if (! pCode || uiCode > 4000) {
pCode = VirtualAlloc(NULL, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
uiCode = 0;
}
// If we have no memory to clone to, return.
if (! pCode) {
return NULL;
}
unsigned char *o = (unsigned char *) *porig;
DWORD origProtect;
if (!VirtualProtect(o, CODEPROTECTSIZE, PAGE_EXECUTE_READ, &origProtect)) {
fods("HardHook: CloneCode failed; failed to make original code read and executable");
return NULL;
}
// Follow relative jumps to next instruction. On execution it doesn't make
// a difference if we actually perform all the jumps or directly jump to the
// end of the chain. Hence these jumps need not be part of the trampoline.
while (*o == 0xe9) { // JMP
unsigned char *tmp = o;
int *iptr = reinterpret_cast<int *>(o+1);
o += *iptr + 5;
fods("HardHook: CloneCode: Skipping jump from %p to %p", *porig, o);
*porig = o;
// Assume jump took us out of our read enabled zone, get rights for the new one
DWORD tempProtect;
VirtualProtect(tmp, CODEPROTECTSIZE, origProtect, &tempProtect);
if (!VirtualProtect(o, CODEPROTECTSIZE, PAGE_EXECUTE_READ, &origProtect)) {
fods("HardHook: CloneCode failed; failed to make jump target code read and executable");
return NULL;
}
}
unsigned char *n = (unsigned char *) pCode;
n += uiCode;
unsigned int idx = 0;
do {
unsigned char opcode = o[idx];
unsigned char a = o[idx+1];
unsigned char b = o[idx+2];
unsigned int extra = 0;
switch (opcode) {
case 0x50: // PUSH
case 0x51:
case 0x52:
case 0x53:
case 0x54:
case 0x55:
case 0x56:
case 0x57:
case 0x58: // POP
case 0x59:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5d:
case 0x5e:
case 0x5f:
break;
case 0x6a: // PUSH immediate
extra = 1;
break;
case 0x68: // PUSH immediate
extra = 4;
break;
case 0x81: // CMP immediate
extra = modrmbytes(a,b) + 5;
break;
case 0x83: // CMP
extra = modrmbytes(a,b) + 2;
break;
case 0x8b: // MOV
extra = modrmbytes(a,b) + 1;
break;
default: {
int rmop = ((a>>3) & 7);
if (opcode == 0xff && rmop == 6) { // PUSH memory
extra = modrmbytes(a,b) + 1;
break;
}
fods("HardHook: CloneCode failed; Unknown opcode %02x at %d: %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
opcode, idx, o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7], o[8], o[9], o[10], o[11]);
DWORD tempProtect;
VirtualProtect(o, CODEPROTECTSIZE, origProtect, &tempProtect);
return NULL;
break;
}
}
n[idx] = opcode;
++idx;
for (unsigned int i = 0; i < extra; ++i)
n[idx+i] = o[idx+i];
idx += extra;
} while (idx < CODEREPLACESIZE);
DWORD tempProtect;
VirtualProtect(o, CODEPROTECTSIZE, origProtect, &tempProtect);
// Add a relative jmp back to the original code, to after the copied code
n[idx++] = 0xe9;
int *iptr = reinterpret_cast<int *>(&n[idx]);
const int JMP_OP_SIZE = 5;
int offs = o - n - JMP_OP_SIZE;
*iptr = offs;
idx += 4;
uiCode += idx;
FlushInstructionCache(GetCurrentProcess(), n, idx);
fods("HardHook: trampoline creation successful at %p", n);
return n;
}
/**
* @brief Makes sure the given replacement function is run once func is called.
*
* Tries to construct a trampoline for the given function (@see HardHook::cloneCode)
* and then injects replacement function calling code into the first 6 bytes of the
* original function (@see HardHook::inject).
*
* @param func Pointer to function to redirect.
* @param replacement Pointer to code to redirect to.
*/
void HardHook::setup(voidFunc func, voidFunc replacement) {
if (baseptr)
return;
fods("HardHook: Setup: Asked to replace %p with %p", func, replacement);
unsigned char *fptr = reinterpret_cast<unsigned char *>(func);
unsigned char *nptr = reinterpret_cast<unsigned char *>(replacement);
call = (voidFunc) cloneCode((void **) &fptr);
if (call) {
bTrampoline = true;
} else {
// Could not create a trampoline. Use alternative method instead.
// This alternative method is dependant on the replacement code
// restoring before calling the original. Otherwise we get a jump recursion
bTrampoline = false;
call = func;
}
DWORD origProtect;
if (VirtualProtect(fptr, CODEPROTECTSIZE, PAGE_EXECUTE_READ, &origProtect)) {
replace[0] = 0x68; // PUSH immediate 1 Byte
unsigned char **iptr = reinterpret_cast<unsigned char **>(&replace[1]);
*iptr = nptr; // (imm. value = nptr) 4 Byte
replace[5] = 0xc3; // RETN 1 Byte
// Save original 6 bytes at start of original function
for (int i = 0; i < CODEREPLACESIZE; ++i)
orig[i] = fptr[i];
baseptr = fptr;
inject(true);
DWORD tempProtect;
VirtualProtect(fptr, CODEPROTECTSIZE, origProtect, &tempProtect);
} else {
fods("HardHook: setup failed; failed to make original code read and executable");
}
}
void HardHook::setupInterface(IUnknown *unkn, LONG funcoffset, voidFunc replacement) {
fods("HardHook: setupInterface: Replacing %p function #%ld", unkn, funcoffset);
void **ptr = reinterpret_cast<void **>(unkn);
ptr = reinterpret_cast<void **>(ptr[0]);
setup(reinterpret_cast<voidFunc>(ptr[funcoffset]), replacement);
}
void HardHook::reset() {
baseptr = 0;
bTrampoline = false;
call = NULL;
for (int i = 0; i < CODEREPLACESIZE; ++i) {
orig[i] = replace[i] = 0;
}
}
/**
* @brief Injects redirection code into the target function.
*
* Replaces the first 6 Bytes of the function indicated by baseptr
* with the replacement code previously generated (usually a jump
* to mumble code). If a trampoline is available this injection is not needed
* as control flow was already permanently redirected by HardHook::setup .
*
* @param force Perform injection even when trampoline is available.
*/
void HardHook::inject(bool force) {
if (! baseptr)
return;
if (! force && bTrampoline)
return;
DWORD origProtect;
if (VirtualProtect(baseptr, CODEREPLACESIZE, PAGE_EXECUTE_READWRITE, &origProtect)) {
for (int i = 0; i < CODEREPLACESIZE; ++i) {
baseptr[i] = replace[i]; // Replace with jump to new code
}
DWORD tempProtect;
VirtualProtect(baseptr, CODEREPLACESIZE, origProtect, &tempProtect);
FlushInstructionCache(GetCurrentProcess(), baseptr, CODEREPLACESIZE);
}
// Verify that the injection was successful
for (int i = 0; i < CODEREPLACESIZE; ++i) {
if (baseptr[i] != replace[i]) {
fods("HardHook: Injection failure noticed at byte %d", i);
}
}
}
/**
* @brief Restores the original code in a target function.
*
* Restores the first 6 Bytes of the function indicated by baseptr
* from previously stored original code in orig. If a trampoline is available this
* restoration is not needed as trampoline will correctly restore control
* flow.
*
* @param force If true injection will be reverted even when trampoline is available.
*/
void HardHook::restore(bool force) {
if (! baseptr)
return;
if (! force && bTrampoline)
return;
DWORD origProtect;
if (VirtualProtect(baseptr, CODEREPLACESIZE, PAGE_EXECUTE_READWRITE, &origProtect)) {
for (int i = 0; i < CODEREPLACESIZE; ++i)
baseptr[i] = orig[i];
DWORD tempProtect;
VirtualProtect(baseptr, CODEREPLACESIZE, origProtect, &tempProtect);
FlushInstructionCache(GetCurrentProcess(), baseptr, CODEREPLACESIZE);
}
}
void HardHook::print() {
fods("HardHook: code replacement: %02x %02x %02x %02x %02x => %02x %02x %02x %02x %02x (currently effective: %02x %02x %02x %02x %02x)",
orig[0], orig[1], orig[2], orig[3], orig[4],
replace[0], replace[1], replace[2], replace[3], replace[4],
baseptr[0], baseptr[1], baseptr[2], baseptr[3], baseptr[4]);
}
/**
* @brief Checks whether injected code is in good shape and injects if not yet injected.
*
* If injected code is not found injection is attempted unless 3rd party overwrote
* original code at injection location.
*/
void HardHook::check() {
if (memcmp(baseptr, replace, CODEREPLACESIZE) != 0) {
// The instructions do not match our replacement instructions
// If they match the original code, inject our hook.
if (memcmp(baseptr, orig, CODEREPLACESIZE) == 0) {
fods("HardHook: Reinjecting hook into function %p", baseptr);
inject(true);
} else {
fods("HardHook: Function %p replaced by third party. Lost injected hook.");
}
}
}
| 32.710074 | 138 | 0.670247 | bogie |
d6ce1fa6589c824a8248a0a7109b94c9e47788eb | 10,844 | cpp | C++ | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/fbterm/1.7+gitAUTOINC+c15430560a-r1/git/src/screen.cpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/fbterm/1.7+gitAUTOINC+c15430560a-r1/git/src/screen.cpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/fbterm/1.7+gitAUTOINC+c15430560a-r1/git/src/screen.cpp | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright © 2008-2010 dragchan <zgchan317@gmail.com>
* This file is part of FbTerm.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include "config.h"
#include "screen.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "fbconfig.h"
#include "fbdev.h"
#include "fbshellman.h"
#include "fbshm.h"
#include "font.h"
#ifdef ENABLE_VESA
#include "vesadev.h"
#endif
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define redraw(args...) (FbShellManager::instance()->redraw(args))
DEFINE_INSTANCE(Screen)
Screen* Screen::createInstance()
{
if (!Font::instance() || !FW(1) || !FH(1))
{
fprintf(stderr, "init font error!\n");
return 0;
}
Screen* pScreen = 0;
s8 shm_info[2];
Config::instance()->getOption("shared-mem", shm_info, sizeof(shm_info));
#ifdef ENABLE_VESA
s8 buf[16];
Config::instance()->getOption("vesa-mode", buf, sizeof(buf));
if (!strcmp(buf, "list"))
{
VesaDev::printModes();
return 0;
}
u32 mode = 0;
Config::instance()->getOption("vesa-mode", mode);
if (!mode)
{
if (strlen(shm_info))
pScreen = FbShm::initFbShm();
else
pScreen = FbDev::initFbDev();
}
if (!pScreen)
pScreen = VesaDev::initVesaDev(mode);
#else
if (strlen(shm_info))
pScreen = FbShm::initFbShm();
else
pScreen = FbDev::initFbDev();
#endif
if (!pScreen)
return 0;
if (pScreen->mRotateType == Rotate90 || pScreen->mRotateType == Rotate270)
{
u32 tmp = pScreen->mWidth;
pScreen->mWidth = pScreen->mHeight;
pScreen->mHeight = tmp;
}
if (!pScreen->mCols)
pScreen->mCols = pScreen->mWidth / FW(1);
if (!pScreen->mRows)
pScreen->mRows = pScreen->mHeight / FH(1);
if (!pScreen->mCols || !pScreen->mRows)
{
fprintf(stderr, "font size is too huge!\n");
delete pScreen;
return 0;
}
pScreen->initFillDraw();
return pScreen;
}
Screen::Screen()
{
mWidth = mHeight = 0;
mCols = mRows = 0;
mBitsPerPixel = mBytesPerLine = 0;
mScrollEnable = true;
mScrollType = Redraw;
mOffsetMax = 0;
mOffsetCur = 0;
mVMemBase = 0;
mPalette = 0;
u32 type = Rotate0;
Config::instance()->getOption("screen-rotate", type);
if (type > Rotate270)
type = Rotate0;
mRotateType = (RotateType)type;
}
Screen::~Screen()
{
Font::uninstance();
endFillDraw();
}
void Screen::showInfo(bool verbose)
{
if (!verbose)
return;
static const s8* const scrollstr[4] = {"redraw", "ypan", "ywrap", "xpan"};
printf("[screen] driver: %s, mode: %dx%d-%dbpp, scrolling: %s\n", drvId(),
mWidth, mHeight, mBitsPerPixel, scrollstr[mScrollType]);
}
void Screen::switchVc(bool enter)
{
mOffsetCur = 0;
setupOffset();
setupPalette(!enter);
if (enter && mPalette)
eraseMargin(true, mRows);
}
bool Screen::move(u16 scol, u16 srow, u16 dcol, u16 drow, u16 w, u16 h)
{
if (!mScrollEnable || mScrollType == Redraw || scol != dcol)
return false;
u16 top = MIN(srow, drow), bot = MAX(srow, drow) + h;
u16 left = scol, right = scol + w;
u32 noaccel_redraw_area = w * (bot - top - 1);
u32 accel_redraw_area = mCols * mRows - w * h;
if (noaccel_redraw_area <= accel_redraw_area)
return false;
if (mRotateType == Rotate0 || mRotateType == Rotate270)
mOffsetCur += FH((s32)srow - drow);
else
mOffsetCur -= FH((s32)srow - drow);
bool redraw_all = false;
if (mScrollType == YPan || mScrollType == XPan)
{
redraw_all = true;
if (mOffsetCur < 0)
mOffsetCur = mOffsetMax;
else if ((u32)mOffsetCur > mOffsetMax)
mOffsetCur = 0;
else
redraw_all = false;
}
else
{
if (mOffsetCur < 0)
mOffsetCur += mOffsetMax + 1;
else if ((u32)mOffsetCur > mOffsetMax)
mOffsetCur -= mOffsetMax + 1;
}
setupOffset();
if (top)
redraw(0, 0, mCols, top);
if (bot < mRows)
redraw(0, bot, mCols, mRows - bot);
if (left > 0)
redraw(0, top, left, bot - top - 1);
if (right < mCols)
redraw(right, top, mCols - right, bot - top - 1);
if (redraw_all)
{
eraseMargin(true, mRows);
}
else
{
eraseMargin(drow > srow, drow > srow ? (drow - srow) : (srow - drow));
}
return !redraw_all;
}
void Screen::eraseMargin(bool top, u16 h)
{
if (mWidth % FW(1))
{
fillRect(FW(mCols), top ? 0 : FH(mRows - h), mWidth % FW(1), FH(h), 0);
}
if (mHeight % FH(1))
{
fillRect(0, FH(mRows), mWidth, mHeight % FH(1), 0);
}
}
void Screen::drawText(u32 x, u32 y, u8 fc, u8 bc, u16 num, u16* text, bool* dw)
{
u32 startx, fw = FW(1);
u16 startnum, *starttext;
bool *startdw, draw_space = false, draw_text = false;
for (; num; num--, text++, dw++, x += fw)
{
if (*text == 0x20)
{
if (draw_text)
{
draw_text = false;
drawGlyphs(startx, y, fc, bc, startnum - num, starttext,
startdw);
}
if (!draw_space)
{
draw_space = true;
startx = x;
}
}
else
{
if (draw_space)
{
draw_space = false;
fillRect(startx, y, x - startx, FH(1), bc);
}
if (!draw_text)
{
draw_text = true;
starttext = text;
startdw = dw;
startnum = num;
startx = x;
}
if (*dw)
x += fw;
}
}
if (draw_text)
{
drawGlyphs(startx, y, fc, bc, startnum - num, starttext, startdw);
}
else if (draw_space)
{
fillRect(startx, y, x - startx, FH(1), bc);
}
}
void Screen::drawGlyphs(u32 x, u32 y, u8 fc, u8 bc, u16 num, u16* text,
bool* dw)
{
for (; num--; text++, dw++)
{
drawGlyph(x, y, fc, bc, *text, *dw);
x += *dw ? FW(2) : FW(1);
}
}
void Screen::adjustOffset(u32& x, u32& y)
{
if (mScrollType == XPan)
x += mOffsetCur;
else
y += mOffsetCur;
}
void Screen::fillRect(u32 x, u32 y, u32 w, u32 h, u8 color)
{
if (x >= mWidth || y >= mHeight || !w || !h)
return;
if (x + w > mWidth)
w = mWidth - x;
if (y + h > mHeight)
h = mHeight - y;
rotateRect(x, y, w, h);
adjustOffset(x, y);
for (; h--;)
{
if (mScrollType == YWrap && y > mOffsetMax)
y -= mOffsetMax + 1;
(this->*fill)(x, y++, w, color);
}
}
void Screen::drawGlyph(u32 x, u32 y, u8 fc, u8 bc, u16 code, bool dw)
{
if (x >= mWidth || y >= mHeight)
return;
s32 w = (dw ? FW(2) : FW(1)), h = FH(1);
if (x + w > mWidth)
w = mWidth - x;
if (y + h > mHeight)
h = mHeight - y;
Font::Glyph* glyph = (Font::Glyph*)Font::instance()->getGlyph(code);
if (!glyph)
{
fillRect(x, y, w, h, bc);
return;
}
s32 top = glyph->top;
if (top < 0)
top = 0;
s32 left = glyph->left;
if ((s32)x + left < 0)
left = -x;
s32 width = glyph->width;
if (width > w - left)
width = w - left;
if ((s32)x + left + width > (s32)mWidth)
width = mWidth - ((s32)x + left);
if (width < 0)
width = 0;
s32 height = glyph->height;
if (height > h - top)
height = h - top;
if (y + top + height > mHeight)
height = mHeight - (y + top);
if (height < 0)
height = 0;
if (top)
fillRect(x, y, w, top, bc);
if (left > 0)
fillRect(x, y + top, left, height, bc);
s32 right = width + left;
if (w > right)
fillRect((s32)x + right, y + top, w - right, height, bc);
s32 bot = top + height;
if (h > bot)
fillRect(x, y + bot, w, h - bot, bc);
x += left;
y += top;
if (x >= mWidth || y >= mHeight || !width || !height)
return;
u32 nwidth = width, nheight = height;
rotateRect(x, y, nwidth, nheight);
u8* pixmap = glyph->pixmap;
u32 wdiff = glyph->width - width, hdiff = glyph->height - height;
if (wdiff)
{
if (mRotateType == Rotate180)
pixmap += wdiff;
else if (mRotateType == Rotate270)
pixmap += wdiff * glyph->pitch;
}
if (hdiff)
{
if (mRotateType == Rotate90)
pixmap += hdiff;
else if (mRotateType == Rotate180)
pixmap += hdiff * glyph->pitch;
}
adjustOffset(x, y);
for (; nheight--; y++, pixmap += glyph->pitch)
{
if ((mScrollType == YWrap) && y > mOffsetMax)
y -= mOffsetMax + 1;
(this->*draw)(x, y, nwidth, fc, bc, pixmap);
}
}
void Screen::rotateRect(u32& x, u32& y, u32& w, u32& h)
{
u32 tmp;
switch (mRotateType)
{
case Rotate0:
break;
case Rotate90:
tmp = x;
x = mHeight - y - h;
y = tmp;
tmp = w;
w = h;
h = tmp;
break;
case Rotate180:
x = mWidth - x - w;
y = mHeight - y - h;
break;
case Rotate270:
tmp = y;
y = mWidth - x - w;
x = tmp;
tmp = w;
w = h;
h = tmp;
break;
}
}
void Screen::rotatePoint(u32 W, u32 H, u32& x, u32& y)
{
u32 tmp;
switch (mRotateType)
{
case Rotate0:
break;
case Rotate90:
tmp = x;
x = H - y - 1;
y = tmp;
break;
case Rotate180:
x = W - x - 1;
y = H - y - 1;
break;
case Rotate270:
tmp = y;
y = W - x - 1;
x = tmp;
break;
}
}
| 22.591667 | 79 | 0.503412 | sotaoverride |
d6d4069bf1a6d7a131bcb24d305e2772a1fd8a2a | 3,774 | hpp | C++ | libff/algebra/fields/binary/gf192.hpp | FardeenFindora/libff | 9be5f23075f9723840eb2ceb0016d24d69dfea8f | [
"MIT"
] | 115 | 2016-07-21T02:49:47.000Z | 2022-03-29T21:08:23.000Z | libff/algebra/fields/binary/gf192.hpp | FardeenFindora/libff | 9be5f23075f9723840eb2ceb0016d24d69dfea8f | [
"MIT"
] | 78 | 2017-03-08T16:43:56.000Z | 2022-02-01T03:12:35.000Z | libff/algebra/fields/binary/gf192.hpp | FardeenFindora/libff | 9be5f23075f9723840eb2ceb0016d24d69dfea8f | [
"MIT"
] | 72 | 2016-07-22T06:49:42.000Z | 2022-03-29T08:48:28.000Z | /**@file
*****************************************************************************
Declaration of GF(2^192) finite field.
*****************************************************************************
* @author This file is part of libff (see AUTHORS), migrated from libiop
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef LIBFF_ALGEBRA_GF192_HPP_
#define LIBFF_ALGEBRA_GF192_HPP_
#include <cstddef>
#include <cstdint>
#include <vector>
#include <libff/algebra/field_utils/bigint.hpp>
namespace libff {
/* gf192 implements the field GF(2)/(x^192 + x^7 + x^2 + x + 1).
Elements are represented internally with three uint64s */
class gf192 {
public:
#ifdef PROFILE_OP_COUNTS // NOTE: op counts are affected when you exponentiate with ^
static long long add_cnt;
static long long sub_cnt;
static long long mul_cnt;
static long long sqr_cnt;
static long long inv_cnt;
#endif
// x^192 + x^7 + x^2 + x + 1
static const constexpr uint64_t modulus_ = 0b10000111;
static const constexpr uint64_t num_bits = 192;
explicit gf192();
/* we need a constructor that only initializes the low half of value_ to
be able to do gf192(0) and gf192(1). */
explicit gf192(const uint64_t value_low);
explicit gf192(const uint64_t value_high, const uint64_t value_mid, const uint64_t value_low);
gf192& operator+=(const gf192 &other);
gf192& operator-=(const gf192 &other);
gf192& operator*=(const gf192 &other);
gf192& operator^=(const unsigned long pow);
template<mp_size_t m>
gf192& operator^=(const bigint<m> &pow);
gf192& square();
gf192& invert();
gf192 operator+(const gf192 &other) const;
gf192 operator-(const gf192 &other) const;
gf192 operator-() const;
gf192 operator*(const gf192 &other) const;
gf192 operator^(const unsigned long pow) const;
template<mp_size_t m>
gf192 operator^(const bigint<m> &pow) const;
gf192 squared() const;
gf192 inverse() const;
gf192 sqrt() const;
/**
* Returns the constituent bits in 64 bit words, in little-endian order.
* Only the right-most ceil_size_in_bits() bits are used; other bits are 0.
*/
std::vector<uint64_t> to_words() const;
/**
* Sets the field element from the given bits in 64 bit words, in little-endian order.
* Only the right-most ceil_size_in_bits() bits are used; other bits are ignored.
* Should always return true since the right-most bits are always valid.
*/
bool from_words(std::vector<uint64_t> words);
void randomize();
void clear();
bool operator==(const gf192 &other) const;
bool operator!=(const gf192 &other) const;
bool is_zero() const;
void print() const;
static gf192 random_element();
static gf192 zero();
static gf192 one();
static gf192 multiplicative_generator; // generator of gf192^*
static std::size_t ceil_size_in_bits() { return num_bits; }
static std::size_t floor_size_in_bits() { return num_bits; }
static constexpr std::size_t extension_degree() { return 192; }
template<mp_size_t n>
static constexpr bigint<n> field_char() { return bigint<n>(2); }
friend std::ostream& operator<<(std::ostream &out, const gf192 &el);
friend std::istream& operator>>(std::istream &in, gf192 &el);
private:
/* little-endian */
uint64_t value_[3];
};
#ifdef PROFILE_OP_COUNTS
long long gf192::add_cnt = 0;
long long gf192::sub_cnt = 0;
long long gf192::mul_cnt = 0;
long long gf192::sqr_cnt = 0;
long long gf192::inv_cnt = 0;
#endif
} // namespace libff
#include <libff/algebra/fields/binary/gf192.tcc>
#endif // namespace libff_ALGEBRA_GF192_HPP_
| 33.105263 | 98 | 0.646264 | FardeenFindora |
d6d4b7cc7b461f90d1cd27b769f2522ffc06152f | 5,426 | cpp | C++ | src/open_pulse/pulse_utils.cpp | jakelishman/qiskit-aer | 7512ecede820e0d2bc7ad7b6704bcf06a861ca3a | [
"Apache-2.0"
] | 313 | 2018-12-19T09:19:12.000Z | 2022-03-21T18:15:41.000Z | src/open_pulse/pulse_utils.cpp | jakelishman/qiskit-aer | 7512ecede820e0d2bc7ad7b6704bcf06a861ca3a | [
"Apache-2.0"
] | 933 | 2018-12-21T02:56:49.000Z | 2022-03-30T01:19:54.000Z | src/open_pulse/pulse_utils.cpp | jakelishman/qiskit-aer | 7512ecede820e0d2bc7ad7b6704bcf06a861ca3a | [
"Apache-2.0"
] | 313 | 2018-12-19T14:52:55.000Z | 2022-02-28T20:20:14.000Z | #include "pulse_utils.hpp"
#include "zspmv.hpp"
complex_t internal_expect_psi_csr(const py::array_t<complex_t>& data,
const py::array_t<int>& ind,
const py::array_t<int>& ptr,
const py::array_t<complex_t>& vec) {
auto data_raw = data.unchecked<1>();
auto vec_raw = vec.unchecked<1>();
auto ind_raw = ind.unchecked<1>();
auto ptr_raw = ptr.unchecked<1>();
auto nrows = vec.shape(0);
complex_t temp, expt = 0;
for (decltype(nrows) row = 0; row < nrows; row++) {
temp = 0;
auto vec_conj = std::conj(vec_raw[row]);
for (auto j = ptr_raw[row]; j < ptr_raw[row + 1]; j++) {
temp += data_raw[j] * vec_raw[ind_raw[j]];
}
expt += vec_conj * temp;
}
return expt;
}
complex_t internal_expect_psi(const py::array_t<complex_t>& data,
const py::array_t<complex_t>& vec) {
auto data_raw = data.unchecked<2>();
auto vec_raw = vec.unchecked<1>();
auto nrows = data.shape(0);
auto ncols = data.shape(1);
complex_t temp, expt = 0;
for (decltype(nrows) i = 0; i < nrows; i++) {
temp = 0;
auto vec_conj = std::conj(vec_raw[i]);
for (auto j = 0; j < ncols; j++) {
temp += data_raw(i, j) * vec_raw[j];
}
expt += vec_conj * temp;
}
return expt;
}
py::object expect_psi_csr(py::array_t<complex_t> data,
py::array_t<int> ind,
py::array_t<int> ptr,
py::array_t<complex_t> vec,
bool isherm){
complex_t expt = internal_expect_psi_csr(data, ind, ptr, vec);
if(isherm){
return py::cast(std::real(expt));
}
return py::cast(expt);
}
py::object expect_psi(py::array_t<complex_t> data,
py::array_t<complex_t> vec,
bool isherm){
complex_t expt = internal_expect_psi(data, vec);
if(isherm){
return py::cast(std::real(expt));
}
return py::cast(expt);
}
py::array_t<double> occ_probabilities(py::array_t<int> qubits,
py::array_t<complex_t> state,
py::list meas_ops){
auto meas_size = meas_ops.size();
py::array_t<double> probs(meas_size);
auto probs_raw = probs.mutable_unchecked<1>();
for(decltype(meas_size) i=0; i < meas_size; i++){
auto data = meas_ops[i].attr("data").attr("data").cast<py::array_t<complex_t>>();
probs_raw[i] = std::real(internal_expect_psi(data, state));
}
return probs;
}
void write_shots_memory(py::array_t<unsigned char> mem,
py::array_t<unsigned int> mem_slots,
py::array_t<double> probs,
py::array_t<double> rand_vals)
{
auto nrows = mem.shape(0);
auto nprobs = probs.shape(0);
unsigned char temp;
auto mem_raw = mem.mutable_unchecked<2>();
auto mem_slots_raw = mem_slots.unchecked<1>();
auto probs_raw = probs.unchecked<1>();
auto rand_vals_raw = rand_vals.unchecked<1>();
for(decltype(nrows) i = 0; i < nrows; i++){
for(decltype(nprobs) j = 0; j < nprobs; j++) {
temp = static_cast<unsigned char>(probs_raw[j] > rand_vals_raw[nprobs*i+j]);
if(temp) {
mem_raw(i, mem_slots_raw[j]) = temp;
}
}
}
}
void oplist_to_array(py::list A, py::array_t<complex_t> B, int start_idx)
{
auto lenA = A.size();
if((start_idx+lenA) > B.shape(0)) {
throw std::runtime_error(std::string("Input list does not fit into array if start_idx is ") + std::to_string(start_idx) + ".");
}
auto B_raw = B.mutable_unchecked<1>();
for(decltype(lenA) kk=0; kk < lenA; kk++){
auto item = A[kk].cast<py::list>();
B_raw[start_idx+kk] = complex_t(item[0].cast<double>(), item[1].cast<double>());
}
}
template <typename T>
T * get_raw_data(py::array_t<T> array)
{
return static_cast<T *>(array.request().ptr);
}
py::array_t<complex_t> spmv_csr(py::array_t<complex_t> data,
py::array_t<int> ind,
py::array_t<int> ptr,
py::array_t<complex_t> vec)
{
auto data_raw = get_raw_data(data);
auto ind_raw = get_raw_data(ind);
auto ptr_raw = get_raw_data(ptr);
auto vec_raw = get_raw_data(vec);
auto num_rows = vec.shape(0);
py::array_t<complex_t> out(num_rows);
auto out_raw = get_raw_data(out);
memset(&out_raw[0], 0, num_rows * sizeof(complex_t));
zspmvpy(data_raw, ind_raw, ptr_raw, vec_raw, 1.0, out_raw, num_rows);
return out;
}
py::array_t<complex_t> spmv(py::array_t<complex_t> data,
py::array_t<complex_t> vec)
{
auto data_raw = get_raw_data(data);
auto vec_raw = get_raw_data(vec);
auto num_columns = data.shape(0);
auto num_rows = data.shape(1);
py::array_t<complex_t> out(num_rows);
auto out_raw = get_raw_data(out);
memset(&out_raw[0], 0, num_rows * sizeof(complex_t));
for (auto row=0; row < num_rows; row++)
{
for (auto jj=0; jj <num_columns; jj++)
{
out_raw[row] += data_raw[row*num_columns + jj]*vec_raw[jj];
}
}
return out;
} | 31.546512 | 135 | 0.555474 | jakelishman |
d6d804e4cd407177e48858dd881f754f70a19c87 | 7,482 | cpp | C++ | alvr/server/cpp/alvr_server/OvrViveTrackerProxy.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 1,562 | 2020-12-01T15:02:21.000Z | 2022-03-31T13:37:51.000Z | alvr/server/cpp/alvr_server/OvrViveTrackerProxy.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 562 | 2020-12-01T20:10:13.000Z | 2022-03-31T22:57:13.000Z | alvr/server/cpp/alvr_server/OvrViveTrackerProxy.cpp | Firepal/ALVR | 834cac75663832638a129a6ba6b2901a7e8dd2ed | [
"MIT"
] | 184 | 2020-12-01T15:02:24.000Z | 2022-03-31T06:18:18.000Z | #include "OvrViveTrackerProxy.h"
#include "Settings.h"
#include "OvrHMD.h"
#include <cassert>
OvrViveTrackerProxy::OvrViveTrackerProxy(OvrHmd& owner)
: m_unObjectId(vr::k_unTrackedDeviceIndexInvalid),
m_HMDOwner(&owner)
{}
vr::DriverPose_t OvrViveTrackerProxy::GetPose()
{
assert(m_HMDOwner != nullptr);
return m_HMDOwner->GetPose();
}
vr::EVRInitError OvrViveTrackerProxy::Activate( vr::TrackedDeviceIndex_t unObjectId )
{
m_unObjectId = unObjectId;
assert(m_unObjectId != vr::k_unTrackedDeviceIndexInvalid);
const auto propertyContainer = vr::VRProperties()->TrackedDeviceToPropertyContainer( m_unObjectId );
// Normally a vive tracker emulator would (logically) always set the tracking system to "lighthouse" but in order to do space calibration
// with existing tools such as OpenVR Space calibrator and be able to calibrate to/from ALVR HMD (and the proxy tracker) space to/from
// a native HMD/tracked device which is already using "lighthouse" as the tracking system the proxy tracker needs to be in a different
// tracking system to treat them differently and prevent those tools doing the same space transform to the proxy tracker.
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_TrackingSystemName_String, Settings::Instance().mTrackingSystemName.c_str());//"lighthouse");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ModelNumber_String, "Vive Tracker Pro MV");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_SerialNumber_String, GetSerialNumber()); // Changed
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_RenderModelName_String, "{htc}vr_tracker_vive_1_0");
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_WillDriftInYaw_Bool, false);
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ManufacturerName_String, "HTC");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_TrackingFirmwareVersion_String, "1541800000 RUNNER-WATCHMAN$runner-watchman@runner-watchman 2018-01-01 FPGA 512(2.56/0/0) BL 0 VRC 1541800000 Radio 1518800000"); // Changed
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_HardwareRevision_String, "product 128 rev 2.5.6 lot 2000/0/0 0"); // Changed
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ConnectedWirelessDongle_String, "D0000BE000"); // Changed
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_DeviceIsWireless_Bool, true);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_DeviceIsCharging_Bool, false);
vr::VRProperties()->SetFloatProperty(propertyContainer, vr::Prop_DeviceBatteryPercentage_Float, 1.f); // Always charged
vr::HmdMatrix34_t l_transform = { -1.f, 0.f, 0.f, 0.f, 0.f, 0.f, -1.f, 0.f, 0.f, -1.f, 0.f, 0.f };
vr::VRProperties()->SetProperty(propertyContainer, vr::Prop_StatusDisplayTransform_Matrix34, &l_transform, sizeof(vr::HmdMatrix34_t), vr::k_unHmdMatrix34PropertyTag);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Firmware_UpdateAvailable_Bool, false);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Firmware_ManualUpdate_Bool, false);
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_Firmware_ManualUpdateURL_String, "https://developer.valvesoftware.com/wiki/SteamVR/HowTo_Update_Firmware");
vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_HardwareRevision_Uint64, 2214720000); // Changed
vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_FirmwareVersion_Uint64, 1541800000); // Changed
vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_FPGAVersion_Uint64, 512); // Changed
vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_VRCVersion_Uint64, 1514800000); // Changed
vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_RadioVersion_Uint64, 1518800000); // Changed
vr::VRProperties()->SetUint64Property(propertyContainer, vr::Prop_DongleVersion_Uint64, 8933539758); // Changed, based on vr::Prop_ConnectedWirelessDongle_String above
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_DeviceProvidesBatteryStatus_Bool, true);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_DeviceCanPowerOff_Bool, true);
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_Firmware_ProgrammingTarget_String, GetSerialNumber());
vr::VRProperties()->SetInt32Property(propertyContainer, vr::Prop_DeviceClass_Int32, vr::TrackedDeviceClass_GenericTracker);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Firmware_ForceUpdateRequired_Bool, false);
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ResourceRoot_String, "htc");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_RegisteredDeviceType_String, "ALVR/tracker/hmd_proxy");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_InputProfilePath_String, "{htc}/input/vive_tracker_profile.json");
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Identifiable_Bool, false);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_Firmware_RemindUpdate_Bool, false);
vr::VRProperties()->SetInt32Property(propertyContainer, vr::Prop_ControllerRoleHint_Int32, vr::TrackedControllerRole_Invalid);
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_ControllerType_String, "vive_tracker_waist");
vr::VRProperties()->SetInt32Property(propertyContainer, vr::Prop_ControllerHandSelectionPriority_Int32, -1);
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceOff_String, "{htc}/icons/tracker_status_off.png");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceSearching_String, "{htc}/icons/tracker_status_searching.gif");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceSearchingAlert_String, "{htc}/icons/tracker_status_searching_alert.gif");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceReady_String, "{htc}/icons/tracker_status_ready.png");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceReadyAlert_String, "{htc}/icons/tracker_status_ready_alert.png");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceNotReady_String, "{htc}/icons/tracker_status_error.png");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceStandby_String, "{htc}/icons/tracker_status_standby.png");
vr::VRProperties()->SetStringProperty(propertyContainer, vr::Prop_NamedIconPathDeviceAlertLow_String, "{htc}/icons/tracker_status_ready_low.png");
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_HasDisplayComponent_Bool, false);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_HasCameraComponent_Bool, false);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_HasDriverDirectModeComponent_Bool, false);
vr::VRProperties()->SetBoolProperty(propertyContainer, vr::Prop_HasVirtualDisplayComponent_Bool, false);
return vr::VRInitError_None;
}
void OvrViveTrackerProxy::update()
{
auto newPose = GetPose();
vr::VRServerDriverHost()->TrackedDevicePoseUpdated(m_unObjectId, newPose, sizeof(vr::DriverPose_t));
} | 88.023529 | 242 | 0.794306 | Firepal |
d6da3c0b96804dda2254ca409833c9e537d0dffe | 1,822 | hh | C++ | StRoot/StJetMaker/test/StjTrgMock.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StJetMaker/test/StjTrgMock.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StJetMaker/test/StjTrgMock.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | // -*- mode: c++;-*-
// $Id: StjTrgMock.hh,v 1.4 2008/11/03 23:07:18 tai Exp $
// Copyright (C) 2008 Tai Sakuma <sakuma@bnl.gov>
#ifndef STJTRGMOCK_H
#define STJTRGMOCK_H
#include "StjTrg.h"
class StjTrgMock : public StjTrg {
public:
StjTrgMock() { }
virtual ~StjTrgMock() { }
int id() { return _id; }
int runNumber() { return _runNumber; }
int eventId() { return _eventId; }
bool hard() const { return _hard; }
bool soft() const { return _soft; }
bool passed() const { return _passed; }
double prescale() { return _prescale; }
double vertexZ() { return _vertexZ; }
std::vector<int> towers() { return _towers; }
std::vector<int> towerDsmAdc() { return _towerDsmAdc; }
std::vector<unsigned int> towerAdc() { return _towerAdc; }
std::vector<double> towerEnergy() { return _towerEnergy; }
std::vector<double> towerEt() { return _towerEt; }
std::vector<int> jetPatches() { return _jetPatches; }
std::vector<int> jetPatchDsmAdc() { return _jetPatchDsmAdc; }
std::vector<unsigned int> jetPatchAdc() { return _jetPatchAdc; }
std::vector<double> jetPatchEnergy() { return _jetPatchEnergy; }
std::vector<double> jetPatchEt() { return _jetPatchEt; }
int _id;
int _runNumber;
int _eventId;
bool _hard;
bool _soft;
bool _passed;
double _prescale;
double _vertexZ;
std::vector<int> _towers;
std::vector<int> _towerDsmAdc;
std::vector<unsigned int> _towerAdc;
std::vector<double> _towerEnergy;
std::vector<double> _towerEt;
std::vector<int> _jetPatches;
std::vector<int> _jetPatchDsmAdc;
std::vector<unsigned int> _jetPatchAdc;
std::vector<double> _jetPatchEnergy;
std::vector<double> _jetPatchEt;
private:
ClassDef(StjTrgMock, 1)
};
#endif // STJTRGMOCK_H
| 27.19403 | 70 | 0.657519 | xiaohaijin |
d6dad91a05bac7cacc341f1799fd3505babae046 | 10,395 | cpp | C++ | utils.cpp | kubeeapp/Sprinks-Firmware | 5afb4e7184b1b34af7e123baa0dcd67adcfc6b8c | [
"Apache-2.0"
] | null | null | null | utils.cpp | kubeeapp/Sprinks-Firmware | 5afb4e7184b1b34af7e123baa0dcd67adcfc6b8c | [
"Apache-2.0"
] | null | null | null | utils.cpp | kubeeapp/Sprinks-Firmware | 5afb4e7184b1b34af7e123baa0dcd67adcfc6b8c | [
"Apache-2.0"
] | null | null | null | /* OpenSprinkler Unified (AVR/RPI/BBB/LINUX) Firmware
* Copyright (C) 2015 by Ray Wang (ray@opensprinkler.com)
*
* Utility functions
* Feb 2015 @ OpenSprinkler.com
*
* This file is part of the OpenSprinkler library
*
* 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 "utils.h"
#include "OpenSprinkler.h"
extern OpenSprinkler os;
#if defined(ARDUINO) // AVR
#ifdef ESP8266
#include <FS.h>
#else
#include <avr/eeprom.h>
#include "SdFat.h"
extern SdFat sd;
#endif
void write_to_file(const char *name, const char *data, int size, int pos, bool trunc) {
if (!os.status.has_sd) return;
char fn[12];
strcpy_P(fn, name);
#ifdef ESP8266
File f;
if(trunc) {
f = SPIFFS.open(fn, "w");
} else {
f = SPIFFS.open(fn, "r+");
if(!f) f = SPIFFS.open(fn, "w");
}
if(!f) {f.close(); return;}
if(pos) f.seek(pos, SeekSet);
if(size==0) {
f.write((byte*)" ", 1); // hack to circumvent SPIFFS bug involving writing empty file
} else {
f.write((byte*)data, size);
}
f.close();
#else
sd.chdir("/");
SdFile file;
int flag = O_CREAT | O_WRITE;
if (trunc) flag |= O_TRUNC;
int ret = file.open(fn, flag);
if(!ret) {
file.close();
return;
}
file.seekSet(pos);
file.write(data, size);
file.close();
#endif
}
bool read_from_file(const char *name, char *data, int maxsize, int pos) {
if (!os.status.has_sd) { data[0]=0; return false; }
char fn[12];
strcpy_P(fn, name);
#ifdef ESP8266
File f = SPIFFS.open(fn, "r");
if(!f) {
data[0]=0;
f.close();
return true; // return true but with empty string
}
if(pos) f.seek(pos, SeekSet);
int len = f.read((byte*)data, maxsize);
if(len>0) data[len]=0;
if(len==1 && data[0]==' ') data[0] = 0; // hack to circumvent SPIFFS bug involving writing empty file
data[maxsize-1]=0;
f.close();
return true;
#else
sd.chdir("/");
SdFile file;
int ret = file.open(fn, O_READ );
if(!ret) {
data[0]=0;
file.close();
return true; // return true but with empty string
}
file.seekSet(pos);
ret = file.fgets(data, maxsize);
data[maxsize-1]=0;
file.close();
return true;
#endif
}
void remove_file(const char *name) {
if (!os.status.has_sd) return;
char fn[12];
strcpy_P(fn, name);
#ifdef ESP8266
if(!SPIFFS.exists(fn)) return;
SPIFFS.remove(fn);
#else
sd.chdir("/");
if (!sd.exists(fn)) return;
sd.remove(fn);
#endif
}
#ifdef ESP8266
// nvm functions for ESP8266
// do not use File.readBytes or readBytesUntil because it's very slow
void nvm_read_block(void *dst, const void *src, int len) {
File f = SPIFFS.open(NVM_FILENAME, "r");
if(f) {
f.seek((unsigned int)src, SeekSet);
f.read((byte*)dst, len);
f.close();
}
}
void nvm_write_block(const void *src, void *dst, int len) {
File f = SPIFFS.open(NVM_FILENAME, "r+");
if(!f) f = SPIFFS.open(NVM_FILENAME, "w");
if(f) {
f.seek((unsigned int)dst, SeekSet);
f.write((byte*)src, len);
f.close();
}
}
byte nvm_read_byte(const byte *p) {
File f = SPIFFS.open(NVM_FILENAME, "r");
byte v = 0;
if(f) {
f.seek((unsigned int)p, SeekSet);
f.read((byte*)&v, 1);
f.close();
}
return v;
}
void nvm_write_byte(const byte *p, byte v) {
File f = SPIFFS.open(NVM_FILENAME, "r+");
if(!f) f = SPIFFS.open(NVM_FILENAME, "w");
if(f) {
f.seek((unsigned int)p, SeekSet);
f.write(&v, 1);
f.close();
}
}
#endif
#else // RPI/BBB/LINUX
void nvm_read_block(void *dst, const void *src, int len) {
FILE *fp = fopen(get_filename_fullpath(NVM_FILENAME), "rb");
if(fp) {
fseek(fp, (unsigned int)src, SEEK_SET);
fread(dst, 1, len, fp);
fclose(fp);
}
}
void nvm_write_block(const void *src, void *dst, int len) {
FILE *fp = fopen(get_filename_fullpath(NVM_FILENAME), "rb+");
if(!fp) {
fp = fopen(get_filename_fullpath(NVM_FILENAME), "wb+"); //This will open the file for editting after creation
}
if(fp) {
fseek(fp, (unsigned int)dst, SEEK_SET); //this fails silently without the above change
fwrite(src, 1, len, fp);
fclose(fp);
} else {
// file does not exist
}
}
byte nvm_read_byte(const byte *p) {
FILE *fp = fopen(get_filename_fullpath(NVM_FILENAME), "rb");
byte v = 0;
if(fp) {
fseek(fp, (unsigned int)p, SEEK_SET);
fread(&v, 1, 1, fp);
fclose(fp);
} else {
// file does not exist
}
return v;
}
void nvm_write_byte(const byte *p, byte v) {
FILE *fp = fopen(get_filename_fullpath(NVM_FILENAME), "rb+");
if(!fp) {
fp = fopen(get_filename_fullpath(NVM_FILENAME), "wb+"); //This will open the file for editting after creation
}
if(fp) {
fseek(fp, (unsigned int)p, SEEK_SET); //This fails silently without above change
fwrite(&v, 1, 1, fp);
fclose(fp);
} else {
// file does not exist
}
}
void write_to_file(const char *name, const char *data, int size, int pos, bool trunc) {
FILE *file;
if(trunc) {
file = fopen(get_filename_fullpath(name), "wb");
} else {
file = fopen(get_filename_fullpath(name), "r+b");
if(!file) {
file = fopen(get_filename_fullpath(name), "wb");
}
}
if (!file) { return; }
fseek(file, pos, SEEK_SET);
fwrite(data, 1, size, file);
fclose(file);
}
bool read_from_file(const char *name, char *data, int maxsize, int pos) {
FILE *file;
file = fopen(get_filename_fullpath(name), "rb");
if(!file) {
data[0] = 0;
return true;
}
int res;
fseek(file, pos, SEEK_SET);
if(fgets(data, maxsize, file)) {
res = strlen(data);
} else {
res = 0;
}
if (res <= 0) {
data[0] = 0;
}
data[maxsize-1]=0;
fclose(file);
return true;
}
void remove_file(const char *name) {
remove(get_filename_fullpath(name));
}
char* get_runtime_path() {
static char path[PATH_MAX];
static byte query = 1;
#ifdef __APPLE__
strcpy(path, "./");
return path;
#endif
if(query) {
if(readlink("/proc/self/exe", path, PATH_MAX ) <= 0) {
return NULL;
}
char* path_end = strrchr(path, '/');
if(path_end == NULL) {
return NULL;
}
path_end++;
*path_end=0;
query = 0;
}
return path;
}
char* get_filename_fullpath(const char *filename) {
static char fullpath[PATH_MAX];
strcpy(fullpath, get_runtime_path());
strcat(fullpath, filename);
return fullpath;
}
#if defined(OSPI)
unsigned int detect_rpi_rev() {
FILE * filp;
unsigned int rev;
char buf[512];
char term;
rev = 0;
filp = fopen ("/proc/cpuinfo", "r");
if (filp != NULL) {
while (fgets(buf, sizeof(buf), filp) != NULL) {
if (!strncasecmp("revision\t", buf, 9)) {
if (sscanf(buf+strlen(buf)-5, "%x%c", &rev, &term) == 2) {
if (term == '\n') break;
rev = 0;
}
}
}
fclose(filp);
}
return rev;
}
#endif
void delay(ulong howLong)
{
struct timespec sleeper, dummy ;
sleeper.tv_sec = (time_t)(howLong / 1000) ;
sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;
nanosleep (&sleeper, &dummy) ;
}
void delayMicrosecondsHard (ulong howLong)
{
struct timeval tNow, tLong, tEnd ;
gettimeofday (&tNow, NULL) ;
tLong.tv_sec = howLong / 1000000 ;
tLong.tv_usec = howLong % 1000000 ;
timeradd (&tNow, &tLong, &tEnd) ;
while (timercmp (&tNow, &tEnd, <))
gettimeofday (&tNow, NULL) ;
}
void delayMicroseconds (ulong howLong)
{
struct timespec sleeper ;
unsigned int uSecs = howLong % 1000000 ;
unsigned int wSecs = howLong / 1000000 ;
/**/ if (howLong == 0)
return ;
else if (howLong < 100)
delayMicrosecondsHard (howLong) ;
else
{
sleeper.tv_sec = wSecs ;
sleeper.tv_nsec = (long)(uSecs * 1000L) ;
nanosleep (&sleeper, NULL) ;
}
}
static uint64_t epochMilli, epochMicro ;
void initialiseEpoch()
{
struct timeval tv ;
gettimeofday (&tv, NULL) ;
epochMilli = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
epochMicro = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)(tv.tv_usec) ;
}
ulong millis (void)
{
struct timeval tv ;
uint64_t now ;
gettimeofday (&tv, NULL) ;
now = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ;
return (uint32_t)(now - epochMilli) ;
}
ulong micros (void)
{
struct timeval tv ;
uint64_t now ;
gettimeofday (&tv, NULL) ;
now = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)tv.tv_usec ;
return (uint32_t)(now - epochMicro) ;
}
#endif
// copy n-character string from program memory with ending 0
void strncpy_P0(char* dest, const char* src, int n) {
byte i;
for(i=0;i<n;i++) {
*dest=pgm_read_byte(src++);
dest++;
}
*dest=0;
}
// compare a string to nvm
byte strcmp_to_nvm(const char* src, int _addr) {
byte c1, c2;
byte *addr = (byte*)_addr;
while(1) {
c1 = nvm_read_byte(addr++);
c2 = *src++;
if (c1==0 || c2==0)
break;
if (c1!=c2) return 1;
}
return (c1==c2) ? 0 : 1;
}
// resolve water time
/* special values:
* 65534: sunrise to sunset duration
* 65535: sunset to sunrise duration
*/
ulong water_time_resolve(uint16_t v) {
if(v==65534) {
return (os.nvdata.sunset_time-os.nvdata.sunrise_time) * 60L;
} else if(v==65535) {
return (os.nvdata.sunrise_time+1440-os.nvdata.sunset_time) * 60L;
} else {
return v;
}
}
// encode a 16-bit signed water time (-600 to 600)
// to unsigned byte (0 to 240)
byte water_time_encode_signed(int16_t i) {
i=(i>600)?600:i;
i=(i<-600)?-600:i;
return (i+600)/5;
}
// decode a 8-bit unsigned byte (0 to 240)
// to a 16-bit signed water time (-600 to 600)
int16_t water_time_decode_signed(byte i) {
i=(i>240)?240:i;
return ((int16_t)i-120)*5;
}
| 22.548807 | 113 | 0.61645 | kubeeapp |
d6db8ea18140d8d8bb58dadd132c2cacc1e63187 | 1,221 | cpp | C++ | src/escape-http.cpp | lindenb/cmd-utils | 1967cbe20bc40676b8bd54ead7d89d80fcdb7a80 | [
"Apache-2.0"
] | 1 | 2019-12-16T06:48:13.000Z | 2019-12-16T06:48:13.000Z | src/escape-http.cpp | lindenb/cmd-utils | 1967cbe20bc40676b8bd54ead7d89d80fcdb7a80 | [
"Apache-2.0"
] | null | null | null | src/escape-http.cpp | lindenb/cmd-utils | 1967cbe20bc40676b8bd54ead7d89d80fcdb7a80 | [
"Apache-2.0"
] | 2 | 2018-09-01T21:34:31.000Z | 2019-12-12T00:30:38.000Z | #include "escape-http.tab.h"
#include "stringutils.hh"
using namespace std;
class EscapeHttp: public EscapeHttpBase {
private:
StringUtils utils;
public:
char x2c(int c0,int c1)
{
int digit;
digit = (c0 >= 'A' ? ((c0 & 0xdf) - 'A')+10 : (c0 - '0'));
digit *= 16;
digit += (c1 >= 'A' ? ((c1 & 0xdf) - 'A')+10 : (c1 - '0'));
return (char)digit;
}
virtual void processFILE(const char* f,std::FILE* in) {
int c1;
while((c1=fgetc(in))!=EOF)
{
if(c1==' ') { cout << "+" ; continue;}
if(!isalnum(c1)) {
char tmp[10];
sprintf(tmp,"%x", c1);
cout << "%" << tmp ;
continue;
}
if(c1!='%') { cout << (char)c1; continue;}
int c2 = fgetc(in);
if(c2==-1 ) { cout << '%'; break;}
if(!utils.isHex(c2)) { cout << "%" << (char)c2;continue;}
int c3 = fgetc(in);
if(c3==-1) { cout << "%" << (char)c2;break;}
if(!utils.isHex(c3)) { cout << "%" << (char)c2 << (char)c3;continue;}
cout << x2c(c2,c3);
}
}
virtual int main(int argc,char** argv)
{
int optind = parseOptions(argc,argv);
fManyOrStdin(optind,argc,argv);
return EXIT_SUCCESS;
}
};
int main(int argc,char** argv)
{
EscapeHttp app;
return app.main(argc,argv);
}
| 21.421053 | 75 | 0.536446 | lindenb |
d6e069b0325e0653a175304af01426ec8c2c77cc | 4,493 | cpp | C++ | projects/topshop/src/ImageCollector.cpp | jsvenus/MosaicUI | 5e01079eb29f82a5916dcbd8c8fd7936e322b873 | [
"MIT"
] | 1 | 2019-02-01T01:41:42.000Z | 2019-02-01T01:41:42.000Z | projects/topshop/src/ImageCollector.cpp | jsvenus/MosaicUI | 5e01079eb29f82a5916dcbd8c8fd7936e322b873 | [
"MIT"
] | null | null | null | projects/topshop/src/ImageCollector.cpp | jsvenus/MosaicUI | 5e01079eb29f82a5916dcbd8c8fd7936e322b873 | [
"MIT"
] | null | null | null | #include <topshop/ImageCollector.h>
#include <featurex/Config.h>
#include <topshop/Config.h>
#include <sys/time.h>
namespace top {
/* ------------------------------------------------------------------------- */
static ImageCollector* validate_new_file(std::string dir, std::string filename, void* user); /* validates the input in the dir watcher callback(s) */
static void on_rename(std::string dir, std::string filename, void* user); /* gets called when a new file is stored in the raw filepath */
static void limit_collected_files(std::deque<CollectedFile>& files, size_t maxfiles); /* will make sure that the lists with files will not become to big; it will remote the oldest when the list is full */
/* ------------------------------------------------------------------------- */
CollectedFile::CollectedFile() {
reset();
}
CollectedFile::~CollectedFile() {
reset();
}
void CollectedFile::reset() {
type = COL_FILE_TYPE_NONE;
dir.clear();
filename.clear();
timestamp = 0;
}
/* ------------------------------------------------------------------------- */
ImageCollector::ImageCollector()
:user(NULL)
,on_file(NULL)
,timestamp(0)
,delay(300e6)
{
}
ImageCollector::~ImageCollector() {
user = NULL;
on_file = NULL;
files.clear();
timestamp = 0;
delay = 0;
}
int ImageCollector::init(std::string filepath) {
if (0 != dir_watcher.init(filepath, on_rename, this)) {
RX_ERROR("Cannot init the raw dir watcher.");
return -1;
}
return 0;
}
void ImageCollector::update() {
#if !defined(NDEBUG)
if (NULL == on_file) {
RX_ERROR("No on_raw_file callback set.");
::exit(EXIT_FAILURE);
}
#endif
if (NULL == on_rename) {
RX_ERROR("on_rename not set. no need to update");
return;
}
dir_watcher.update();
uint64_t now = rx_hrtime();
/* check if we have raw files. */
if (now >= timestamp && NULL != on_file) {
timestamp = now + delay;
if (0 != files.size()) {
CollectedFile cfile = files.front();
on_file(this, cfile);
files.pop_front();
}
}
/* make sure the list with files will not become too large. */
size_t max_files = 5000;
limit_collected_files(files, max_files);
}
int ImageCollector::shutdown() {
int r = 0;
r = dir_watcher.shutdown();
if (0 != r) {
RX_ERROR("Failed to cleanly shutdown the raw dir watcher: %d", r);
}
files.clear();
timestamp = 0;
return 0;
}
/* ------------------------------------------------------------------------- */
static void on_rename(std::string dir, std::string filename, void* user) {
/* validate + get the handle to our image collector. */
ImageCollector* collector = validate_new_file(dir, filename, user);
if (NULL == collector) {
return;
}
CollectedFile cfile;
cfile.dir = dir;
cfile.filename = filename;
cfile.timestamp = rx_hrtime();
collector->files.push_back(cfile);
}
/* validates the given parameters and returns the ImageCollector* that we cast from a event handler */
static ImageCollector* validate_new_file(std::string dir, std::string filename, void* user) {
if (NULL == user) {
RX_ERROR("User pointer is NULL. Not supposed to happen.");
return NULL;
}
ImageCollector* collector = static_cast<ImageCollector*>(user);
if (NULL == collector) {
RX_ERROR("Cannot cast user pointer to the ImageCollector.");
return NULL;
}
if (0 == dir.size()) {
RX_ERROR("Got new file event but the dir value is empty. Not supposed to happen.");
return NULL;
}
if (0 == filename.size()) {
RX_ERROR("Got a new file event but the filename is empty. Not supposed to happen.");
return NULL;
}
std::string filepath = dir +"/" +filename;
if (false == rx_file_exists(filepath)) {
RX_ERROR("The file %s doesn't exist.", filepath.c_str());
return NULL;
}
return collector;
}
/* makes sure the given vector will not have too many items. */
void limit_collected_files(std::deque<CollectedFile>& files, size_t maxfiles) {
while (files.size() > maxfiles) {
RX_VERBOSE("Removing!");
files.pop_front();
}
}
/* ------------------------------------------------------------------------- */
} /* namespace top */
| 26.904192 | 216 | 0.56243 | jsvenus |
d6e7b4954d0d1c6ed0c89635596a5faa622770b6 | 341 | cpp | C++ | demos/processtofile/main.cpp | artoka/libsshqt | 5c69fbf478a1514380308e72815dbe02f2b290e6 | [
"MIT"
] | 6 | 2015-04-21T07:13:05.000Z | 2022-03-08T01:26:49.000Z | demos/processtofile/main.cpp | artoka/libsshqt | 5c69fbf478a1514380308e72815dbe02f2b290e6 | [
"MIT"
] | null | null | null | demos/processtofile/main.cpp | artoka/libsshqt | 5c69fbf478a1514380308e72815dbe02f2b290e6 | [
"MIT"
] | 4 | 2017-09-26T20:00:13.000Z | 2021-11-10T18:54:02.000Z |
#include <QtCore/QCoreApplication>
#include <QTimer>
#include "processtofile.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ProcessToFile *processtofile = new ProcessToFile;
QTimer::singleShot(0, processtofile, SLOT(processToFile()));
int ret = a.exec();
delete processtofile;
return ret;
}
| 21.3125 | 64 | 0.697947 | artoka |
d6ee3400abc7af650e928a6c22a69285344315ac | 322,018 | cpp | C++ | swig/csharp/gdal/gdal_wrap.cpp | VisualAwarenessTech/gdal-2.2.1 | 5ea1c6671d6f0f3b93e9e9bf2a71da618c834e8d | [
"Apache-2.0"
] | null | null | null | swig/csharp/gdal/gdal_wrap.cpp | VisualAwarenessTech/gdal-2.2.1 | 5ea1c6671d6f0f3b93e9e9bf2a71da618c834e8d | [
"Apache-2.0"
] | null | null | null | swig/csharp/gdal/gdal_wrap.cpp | VisualAwarenessTech/gdal-2.2.1 | 5ea1c6671d6f0f3b93e9e9bf2a71da618c834e8d | [
"Apache-2.0"
] | null | null | null | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.39
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */
#define SWIGCSHARP
#ifdef __cplusplus
/* SwigValueWrapper is described in swig.swg */
template<typename T> class SwigValueWrapper {
struct SwigMovePointer {
T *ptr;
SwigMovePointer(T *p) : ptr(p) { }
~SwigMovePointer() { delete ptr; }
SwigMovePointer& operator=(SwigMovePointer& rhs) { T* oldptr = ptr; ptr = 0; delete oldptr; ptr = rhs.ptr; rhs.ptr = 0; return *this; }
} pointer;
SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
SwigValueWrapper(const SwigValueWrapper<T>& rhs);
public:
SwigValueWrapper() : pointer(0) { }
SwigValueWrapper& operator=(const T& t) { SwigMovePointer tmp(new T(t)); pointer = tmp; return *this; }
operator T&() const { return *pointer.ptr; }
T *operator&() { return pointer.ptr; }
};
template <typename T> T SwigValueInit() {
return T();
}
#endif
/* -----------------------------------------------------------------------------
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
* ----------------------------------------------------------------------------- */
/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# elif defined(__HP_aCC)
/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif
/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif
/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
# elif defined(__ICC)
# define SWIGUNUSED __attribute__ ((__unused__))
# else
# define SWIGUNUSED
# endif
#endif
#ifndef SWIG_MSC_UNSUPPRESS_4505
# if defined(_MSC_VER)
# pragma warning(disable : 4505) /* unreferenced local function has been removed */
# endif
#endif
#ifndef SWIGUNUSEDPARM
# ifdef __cplusplus
# define SWIGUNUSEDPARM(p)
# else
# define SWIGUNUSEDPARM(p) p SWIGUNUSED
# endif
#endif
/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif
/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif
/* exporting methods */
#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
# ifndef GCC_HASCLASSVISIBILITY
# define GCC_HASCLASSVISIBILITY
# endif
#endif
#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
# define SWIGEXPORT __attribute__ ((visibility("default")))
# else
# define SWIGEXPORT
# endif
# endif
#endif
/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif
/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
# define _CRT_SECURE_NO_DEPRECATE
#endif
/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
# define _SCL_SECURE_NO_DEPRECATE
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/* Support for throwing C# exceptions from C/C++. There are two types:
* Exceptions that take a message and ArgumentExceptions that take a message and a parameter name. */
typedef enum {
SWIG_CSharpApplicationException,
SWIG_CSharpArithmeticException,
SWIG_CSharpDivideByZeroException,
SWIG_CSharpIndexOutOfRangeException,
SWIG_CSharpInvalidCastException,
SWIG_CSharpInvalidOperationException,
SWIG_CSharpIOException,
SWIG_CSharpNullReferenceException,
SWIG_CSharpOutOfMemoryException,
SWIG_CSharpOverflowException,
SWIG_CSharpSystemException
} SWIG_CSharpExceptionCodes;
typedef enum {
SWIG_CSharpArgumentException,
SWIG_CSharpArgumentNullException,
SWIG_CSharpArgumentOutOfRangeException
} SWIG_CSharpExceptionArgumentCodes;
typedef void (SWIGSTDCALL* SWIG_CSharpExceptionCallback_t)(const char *);
typedef void (SWIGSTDCALL* SWIG_CSharpExceptionArgumentCallback_t)(const char *, const char *);
typedef struct {
SWIG_CSharpExceptionCodes code;
SWIG_CSharpExceptionCallback_t callback;
} SWIG_CSharpException_t;
typedef struct {
SWIG_CSharpExceptionArgumentCodes code;
SWIG_CSharpExceptionArgumentCallback_t callback;
} SWIG_CSharpExceptionArgument_t;
static SWIG_CSharpException_t SWIG_csharp_exceptions[] = {
{ SWIG_CSharpApplicationException, NULL },
{ SWIG_CSharpArithmeticException, NULL },
{ SWIG_CSharpDivideByZeroException, NULL },
{ SWIG_CSharpIndexOutOfRangeException, NULL },
{ SWIG_CSharpInvalidCastException, NULL },
{ SWIG_CSharpInvalidOperationException, NULL },
{ SWIG_CSharpIOException, NULL },
{ SWIG_CSharpNullReferenceException, NULL },
{ SWIG_CSharpOutOfMemoryException, NULL },
{ SWIG_CSharpOverflowException, NULL },
{ SWIG_CSharpSystemException, NULL }
};
static SWIG_CSharpExceptionArgument_t SWIG_csharp_exceptions_argument[] = {
{ SWIG_CSharpArgumentException, NULL },
{ SWIG_CSharpArgumentNullException, NULL },
{ SWIG_CSharpArgumentOutOfRangeException, NULL },
};
static void SWIGUNUSED SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code, const char *msg) {
SWIG_CSharpExceptionCallback_t callback = SWIG_csharp_exceptions[SWIG_CSharpApplicationException].callback;
if ((size_t)code < sizeof(SWIG_csharp_exceptions)/sizeof(SWIG_CSharpException_t)) {
callback = SWIG_csharp_exceptions[code].callback;
}
callback(msg);
}
static void SWIGUNUSED SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code, const char *msg, const char *param_name) {
SWIG_CSharpExceptionArgumentCallback_t callback = SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentException].callback;
if ((size_t)code < sizeof(SWIG_csharp_exceptions_argument)/sizeof(SWIG_CSharpExceptionArgument_t)) {
callback = SWIG_csharp_exceptions_argument[code].callback;
}
callback(msg, param_name);
}
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionCallbacks_Gdal(
SWIG_CSharpExceptionCallback_t applicationCallback,
SWIG_CSharpExceptionCallback_t arithmeticCallback,
SWIG_CSharpExceptionCallback_t divideByZeroCallback,
SWIG_CSharpExceptionCallback_t indexOutOfRangeCallback,
SWIG_CSharpExceptionCallback_t invalidCastCallback,
SWIG_CSharpExceptionCallback_t invalidOperationCallback,
SWIG_CSharpExceptionCallback_t ioCallback,
SWIG_CSharpExceptionCallback_t nullReferenceCallback,
SWIG_CSharpExceptionCallback_t outOfMemoryCallback,
SWIG_CSharpExceptionCallback_t overflowCallback,
SWIG_CSharpExceptionCallback_t systemCallback) {
SWIG_csharp_exceptions[SWIG_CSharpApplicationException].callback = applicationCallback;
SWIG_csharp_exceptions[SWIG_CSharpArithmeticException].callback = arithmeticCallback;
SWIG_csharp_exceptions[SWIG_CSharpDivideByZeroException].callback = divideByZeroCallback;
SWIG_csharp_exceptions[SWIG_CSharpIndexOutOfRangeException].callback = indexOutOfRangeCallback;
SWIG_csharp_exceptions[SWIG_CSharpInvalidCastException].callback = invalidCastCallback;
SWIG_csharp_exceptions[SWIG_CSharpInvalidOperationException].callback = invalidOperationCallback;
SWIG_csharp_exceptions[SWIG_CSharpIOException].callback = ioCallback;
SWIG_csharp_exceptions[SWIG_CSharpNullReferenceException].callback = nullReferenceCallback;
SWIG_csharp_exceptions[SWIG_CSharpOutOfMemoryException].callback = outOfMemoryCallback;
SWIG_csharp_exceptions[SWIG_CSharpOverflowException].callback = overflowCallback;
SWIG_csharp_exceptions[SWIG_CSharpSystemException].callback = systemCallback;
}
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT void SWIGSTDCALL SWIGRegisterExceptionArgumentCallbacks_Gdal(
SWIG_CSharpExceptionArgumentCallback_t argumentCallback,
SWIG_CSharpExceptionArgumentCallback_t argumentNullCallback,
SWIG_CSharpExceptionArgumentCallback_t argumentOutOfRangeCallback) {
SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentException].callback = argumentCallback;
SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentNullException].callback = argumentNullCallback;
SWIG_csharp_exceptions_argument[SWIG_CSharpArgumentOutOfRangeException].callback = argumentOutOfRangeCallback;
}
/* Callback for returning strings to C# without leaking memory */
typedef char * (SWIGSTDCALL* SWIG_CSharpStringHelperCallback)(const char *);
static SWIG_CSharpStringHelperCallback SWIG_csharp_string_callback = NULL;
#ifdef __cplusplus
extern "C"
#endif
SWIGEXPORT void SWIGSTDCALL SWIGRegisterStringCallback_Gdal(SWIG_CSharpStringHelperCallback callback) {
SWIG_csharp_string_callback = callback;
}
/* Contract support */
#define SWIG_contract_assert(nullreturn, expr, msg) if (!(expr)) {SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, msg, ""); return nullreturn; } else
/* Errors in SWIG */
#define SWIG_UnknownError -1
#define SWIG_IOError -2
#define SWIG_RuntimeError -3
#define SWIG_IndexError -4
#define SWIG_TypeError -5
#define SWIG_DivisionByZero -6
#define SWIG_OverflowError -7
#define SWIG_SyntaxError -8
#define SWIG_ValueError -9
#define SWIG_SystemError -10
#define SWIG_AttributeError -11
#define SWIG_MemoryError -12
#define SWIG_NullReferenceError -13
SWIGINTERN void SWIG_CSharpException(int code, const char *msg) {
if (code == SWIG_ValueError) {
SWIG_CSharpExceptionArgumentCodes exception_code = SWIG_CSharpArgumentOutOfRangeException;
SWIG_CSharpSetPendingExceptionArgument(exception_code, msg, 0);
} else {
SWIG_CSharpExceptionCodes exception_code = SWIG_CSharpApplicationException;
switch(code) {
case SWIG_MemoryError:
exception_code = SWIG_CSharpOutOfMemoryException;
break;
case SWIG_IndexError:
exception_code = SWIG_CSharpIndexOutOfRangeException;
break;
case SWIG_DivisionByZero:
exception_code = SWIG_CSharpDivideByZeroException;
break;
case SWIG_IOError:
exception_code = SWIG_CSharpIOException;
break;
case SWIG_OverflowError:
exception_code = SWIG_CSharpOverflowException;
break;
case SWIG_RuntimeError:
case SWIG_TypeError:
case SWIG_SyntaxError:
case SWIG_SystemError:
case SWIG_UnknownError:
default:
exception_code = SWIG_CSharpApplicationException;
break;
}
SWIG_CSharpSetPendingException(exception_code, msg);
}
}
#include <stdexcept>
#include <iostream>
using namespace std;
#include "cpl_port.h"
#include "cpl_string.h"
#include "cpl_multiproc.h"
#include "cpl_http.h"
#include "cpl_vsi_error.h"
#include "gdal.h"
#include "gdal_priv.h"
#include "gdal_alg.h"
#include "gdalwarper.h"
typedef void GDALMajorObjectShadow;
typedef void GDALDriverShadow;
typedef void GDALDatasetShadow;
typedef void GDALRasterBandShadow;
typedef void GDALColorTableShadow;
typedef void GDALRasterAttributeTableShadow;
typedef void GDALTransformerInfoShadow;
typedef void GDALAsyncReaderShadow;
/* use this to not return the int returned by GDAL */
typedef int RETURN_NONE;
/* return value that is used for VSI methods that return -1 on error (and set errno) */
typedef int VSI_RETVAL;
void VeryQuietErrorHandler(CPLErr eclass, int code, const char *msg ) {
/* If the error class is CE_Fatal, we want to have a message issued
because the CPL support code does an abort() before any exception
can be generated */
#if defined(SWIGPERL)
AV* error_stack = get_av("Geo::GDAL::error", 0);
SV *error = newSVpv(msg, 0);
av_push(error_stack, error);
#endif
if (eclass == CE_Fatal ) {
CPLDefaultErrorHandler(eclass, code, msg );
}
}
void UseExceptions() {
CPLSetErrorHandler( (CPLErrorHandler) VeryQuietErrorHandler );
}
void DontUseExceptions() {
CPLSetErrorHandler( CPLDefaultErrorHandler );
}
void StringListDestroy(void *buffer_ptr) {
CSLDestroy((char**)buffer_ptr);
}
typedef char retStringAndCPLFree;
void Debug( const char *msg_class, const char *message ) {
CPLDebug( msg_class, "%s", message );
}
CPLErr SetErrorHandler( char const * pszCallbackName = NULL )
{
CPLErrorHandler pfnHandler = NULL;
if( pszCallbackName == NULL || EQUAL(pszCallbackName,"CPLQuietErrorHandler") )
pfnHandler = CPLQuietErrorHandler;
else if( EQUAL(pszCallbackName,"CPLDefaultErrorHandler") )
pfnHandler = CPLDefaultErrorHandler;
else if( EQUAL(pszCallbackName,"CPLLoggingErrorHandler") )
pfnHandler = CPLLoggingErrorHandler;
if ( pfnHandler == NULL )
return CE_Fatal;
CPLSetErrorHandler( pfnHandler );
return CE_None;
}
CPLErr PushErrorHandler( char const * pszCallbackName = NULL ) {
CPLErrorHandler pfnHandler = NULL;
if( pszCallbackName == NULL || EQUAL(pszCallbackName,"CPLQuietErrorHandler") )
pfnHandler = CPLQuietErrorHandler;
else if( EQUAL(pszCallbackName,"CPLDefaultErrorHandler") )
pfnHandler = CPLDefaultErrorHandler;
else if( EQUAL(pszCallbackName,"CPLLoggingErrorHandler") )
pfnHandler = CPLLoggingErrorHandler;
if ( pfnHandler == NULL )
return CE_Fatal;
CPLPushErrorHandler( pfnHandler );
return CE_None;
}
void Error( CPLErr msg_class = CE_Failure, int err_code = 0, const char* msg = "error" ) {
CPLError( msg_class, err_code, "%s", msg );
}
retStringAndCPLFree* EscapeString(int len, char *bin_string , int scheme) {
return CPLEscapeString((const char*)bin_string, len, scheme);
}
char **wrapper_VSIReadDirEx( const char * utf8_path, int nMaxFiles = 0 )
{
return VSIReadDirEx(utf8_path, nMaxFiles);
}
const char *wrapper_CPLGetConfigOption( const char * pszKey, const char * pszDefault = NULL )
{
return CPLGetConfigOption( pszKey, pszDefault );
}
void wrapper_VSIFileFromMemBuffer( const char* utf8_path, int nBytes, const GByte *pabyData)
{
GByte* pabyDataDup = (GByte*)VSIMalloc(nBytes);
if (pabyDataDup == NULL)
return;
memcpy(pabyDataDup, pabyData, nBytes);
VSIFCloseL(VSIFileFromMemBuffer(utf8_path, (GByte*) pabyDataDup, nBytes, TRUE));
}
int wrapper_HasThreadSupport()
{
return strcmp(CPLGetThreadingModel(), "stub") != 0;
}
VSILFILE *wrapper_VSIFOpenL( const char *utf8_path, const char *pszMode )
{
if (!pszMode) /* would lead to segfault */
pszMode = "r";
return VSIFOpenL( utf8_path, pszMode );
}
VSILFILE *wrapper_VSIFOpenExL( const char *utf8_path, const char *pszMode, int bSetError )
{
if (!pszMode) /* would lead to segfault */
pszMode = "r";
return VSIFOpenExL( utf8_path, pszMode, bSetError );
}
SWIGINTERN CPLXMLNode *new_CPLXMLNode__SWIG_0(char const *pszString){
return CPLParseXMLString( pszString );
}
SWIGINTERN CPLXMLNode *new_CPLXMLNode__SWIG_1(CPLXMLNodeType eType,char const *pszText){
return CPLCreateXMLNode(NULL, eType, pszText);
}
SWIGINTERN void delete_CPLXMLNode(CPLXMLNode *self){
CPLDestroyXMLNode( self );
}
SWIGINTERN retStringAndCPLFree *CPLXMLNode_SerializeXMLTree(CPLXMLNode *self){
return CPLSerializeXMLTree( self );
}
SWIGINTERN retStringAndCPLFree *CPLXMLNode_toString(CPLXMLNode *self){
return CPLSerializeXMLTree( self );
}
SWIGINTERN CPLXMLNode *CPLXMLNode_SearchXMLNode(CPLXMLNode *self,char const *pszElement){
return CPLSearchXMLNode(self, pszElement);
}
SWIGINTERN CPLXMLNode *CPLXMLNode_GetXMLNode(CPLXMLNode *self,char const *pszPath){
return CPLGetXMLNode( self, pszPath );
}
SWIGINTERN char const *CPLXMLNode_GetXMLValue(CPLXMLNode *self,char const *pszPath,char const *pszDefault){
return CPLGetXMLValue( self, pszPath, pszDefault );
}
SWIGINTERN void CPLXMLNode_AddXMLChild(CPLXMLNode *self,CPLXMLNode *psChild){
CPLAddXMLChild( self, psChild );
}
SWIGINTERN int CPLXMLNode_RemoveXMLChild(CPLXMLNode *self,CPLXMLNode *psChild){
return CPLRemoveXMLChild( self, psChild );
}
SWIGINTERN void CPLXMLNode_AddXMLSibling(CPLXMLNode *self,CPLXMLNode *psNewSibling){
CPLAddXMLSibling( self, psNewSibling );
}
SWIGINTERN CPLXMLNode *CPLXMLNode_CreateXMLElementAndValue(CPLXMLNode *self,char const *pszName,char const *pszValue){
return CPLCreateXMLElementAndValue( self, pszName, pszValue );
}
SWIGINTERN CPLXMLNode *CPLXMLNode_CloneXMLTree(CPLXMLNode *self,CPLXMLNode *psTree){
return CPLCloneXMLTree( psTree );
}
SWIGINTERN CPLXMLNode *CPLXMLNode_Clone(CPLXMLNode *self){
return CPLCloneXMLTree( self );
}
SWIGINTERN int CPLXMLNode_SetXMLValue(CPLXMLNode *self,char const *pszPath,char const *pszValue){
return CPLSetXMLValue( self, pszPath, pszValue );
}
SWIGINTERN void CPLXMLNode_StripXMLNamespace(CPLXMLNode *self,char const *pszNamespace,int bRecurse){
CPLStripXMLNamespace( self, pszNamespace, bRecurse );
}
SWIGINTERN char const *GDALMajorObjectShadow_GetDescription(GDALMajorObjectShadow *self){
return GDALGetDescription( self );
}
SWIGINTERN void GDALMajorObjectShadow_SetDescription(GDALMajorObjectShadow *self,char const *pszNewDesc){
GDALSetDescription( self, pszNewDesc );
}
SWIGINTERN char **GDALMajorObjectShadow_GetMetadataDomainList(GDALMajorObjectShadow *self){
return GDALGetMetadataDomainList( self );
}
SWIGINTERN char **GDALMajorObjectShadow_GetMetadata_List(GDALMajorObjectShadow *self,char const *pszDomain=""){
return GDALGetMetadata( self, pszDomain );
}
SWIGINTERN CPLErr GDALMajorObjectShadow_SetMetadata__SWIG_0(GDALMajorObjectShadow *self,char **papszMetadata,char const *pszDomain=""){
return GDALSetMetadata( self, papszMetadata, pszDomain );
}
SWIGINTERN CPLErr GDALMajorObjectShadow_SetMetadata__SWIG_1(GDALMajorObjectShadow *self,char *pszMetadataString,char const *pszDomain=""){
char *tmpList[2];
tmpList[0] = pszMetadataString;
tmpList[1] = 0;
return GDALSetMetadata( self, tmpList, pszDomain );
}
SWIGINTERN char const *GDALMajorObjectShadow_GetMetadataItem(GDALMajorObjectShadow *self,char const *pszName,char const *pszDomain=""){
return GDALGetMetadataItem( self, pszName, pszDomain);
}
SWIGINTERN CPLErr GDALMajorObjectShadow_SetMetadataItem(GDALMajorObjectShadow *self,char const *pszName,char const *pszValue,char const *pszDomain=""){
return GDALSetMetadataItem( self, pszName, pszValue, pszDomain);
}
SWIGINTERN GDALDatasetShadow *GDALDriverShadow_Create(GDALDriverShadow *self,char const *utf8_path,int xsize,int ysize,int bands=1,GDALDataType eType=GDT_Byte,char **options=0){
GDALDatasetShadow* ds = (GDALDatasetShadow*) GDALCreate( self,
utf8_path,
xsize,
ysize,
bands,
eType,
options );
return ds;
}
SWIGINTERN GDALDatasetShadow *GDALDriverShadow_CreateCopy(GDALDriverShadow *self,char const *utf8_path,GDALDatasetShadow *src,int strict=1,char **options=0,GDALProgressFunc callback=NULL,void *callback_data=NULL){
GDALDatasetShadow *ds = (GDALDatasetShadow*) GDALCreateCopy( self,
utf8_path,
src,
strict,
options,
callback,
callback_data );
return ds;
}
SWIGINTERN CPLErr GDALDriverShadow_Delete(GDALDriverShadow *self,char const *utf8_path){
return GDALDeleteDataset( self, utf8_path );
}
SWIGINTERN CPLErr GDALDriverShadow_Rename(GDALDriverShadow *self,char const *newName,char const *oldName){
return GDALRenameDataset( self, newName, oldName );
}
SWIGINTERN CPLErr GDALDriverShadow_CopyFiles(GDALDriverShadow *self,char const *newName,char const *oldName){
return GDALCopyDatasetFiles( self, newName, oldName );
}
SWIGINTERN int GDALDriverShadow_Register(GDALDriverShadow *self){
return GDALRegisterDriver( self );
}
SWIGINTERN void GDALDriverShadow_Deregister(GDALDriverShadow *self){
GDALDeregisterDriver( self );
}
char const *GDALDriverShadow_ShortName_get( GDALDriverShadow *h ) {
return GDALGetDriverShortName( h );
}
char const *GDALDriverShadow_LongName_get( GDALDriverShadow *h ) {
return GDALGetDriverLongName( h );
}
char const *GDALDriverShadow_HelpTopic_get( GDALDriverShadow *h ) {
return GDALGetDriverHelpTopic( h );
}
SWIGINTERN GDAL_GCP *new_GDAL_GCP(double x=0.0,double y=0.0,double z=0.0,double pixel=0.0,double line=0.0,char const *info="",char const *id=""){
GDAL_GCP *self = (GDAL_GCP*) CPLMalloc( sizeof( GDAL_GCP ) );
self->dfGCPX = x;
self->dfGCPY = y;
self->dfGCPZ = z;
self->dfGCPPixel = pixel;
self->dfGCPLine = line;
self->pszInfo = CPLStrdup( (info == 0) ? "" : info );
self->pszId = CPLStrdup( (id==0)? "" : id );
return self;
}
SWIGINTERN void delete_GDAL_GCP(GDAL_GCP *self){
if ( self->pszInfo )
CPLFree( self->pszInfo );
if ( self->pszId )
CPLFree( self->pszId );
CPLFree( self );
}
double GDAL_GCP_GCPX_get( GDAL_GCP *gcp ) {
return gcp->dfGCPX;
}
void GDAL_GCP_GCPX_set( GDAL_GCP *gcp, double dfGCPX ) {
gcp->dfGCPX = dfGCPX;
}
double GDAL_GCP_GCPY_get( GDAL_GCP *gcp ) {
return gcp->dfGCPY;
}
void GDAL_GCP_GCPY_set( GDAL_GCP *gcp, double dfGCPY ) {
gcp->dfGCPY = dfGCPY;
}
double GDAL_GCP_GCPZ_get( GDAL_GCP *gcp ) {
return gcp->dfGCPZ;
}
void GDAL_GCP_GCPZ_set( GDAL_GCP *gcp, double dfGCPZ ) {
gcp->dfGCPZ = dfGCPZ;
}
double GDAL_GCP_GCPPixel_get( GDAL_GCP *gcp ) {
return gcp->dfGCPPixel;
}
void GDAL_GCP_GCPPixel_set( GDAL_GCP *gcp, double dfGCPPixel ) {
gcp->dfGCPPixel = dfGCPPixel;
}
double GDAL_GCP_GCPLine_get( GDAL_GCP *gcp ) {
return gcp->dfGCPLine;
}
void GDAL_GCP_GCPLine_set( GDAL_GCP *gcp, double dfGCPLine ) {
gcp->dfGCPLine = dfGCPLine;
}
const char * GDAL_GCP_Info_get( GDAL_GCP *gcp ) {
return gcp->pszInfo;
}
void GDAL_GCP_Info_set( GDAL_GCP *gcp, const char * pszInfo ) {
if ( gcp->pszInfo )
CPLFree( gcp->pszInfo );
gcp->pszInfo = CPLStrdup(pszInfo);
}
const char * GDAL_GCP_Id_get( GDAL_GCP *gcp ) {
return gcp->pszId;
}
void GDAL_GCP_Id_set( GDAL_GCP *gcp, const char * pszId ) {
if ( gcp->pszId )
CPLFree( gcp->pszId );
gcp->pszId = CPLStrdup(pszId);
}
/* Duplicate, but transposed names for C# because
* the C# module outputs backwards names
*/
double GDAL_GCP_get_GCPX( GDAL_GCP *gcp ) {
return gcp->dfGCPX;
}
void GDAL_GCP_set_GCPX( GDAL_GCP *gcp, double dfGCPX ) {
gcp->dfGCPX = dfGCPX;
}
double GDAL_GCP_get_GCPY( GDAL_GCP *gcp ) {
return gcp->dfGCPY;
}
void GDAL_GCP_set_GCPY( GDAL_GCP *gcp, double dfGCPY ) {
gcp->dfGCPY = dfGCPY;
}
double GDAL_GCP_get_GCPZ( GDAL_GCP *gcp ) {
return gcp->dfGCPZ;
}
void GDAL_GCP_set_GCPZ( GDAL_GCP *gcp, double dfGCPZ ) {
gcp->dfGCPZ = dfGCPZ;
}
double GDAL_GCP_get_GCPPixel( GDAL_GCP *gcp ) {
return gcp->dfGCPPixel;
}
void GDAL_GCP_set_GCPPixel( GDAL_GCP *gcp, double dfGCPPixel ) {
gcp->dfGCPPixel = dfGCPPixel;
}
double GDAL_GCP_get_GCPLine( GDAL_GCP *gcp ) {
return gcp->dfGCPLine;
}
void GDAL_GCP_set_GCPLine( GDAL_GCP *gcp, double dfGCPLine ) {
gcp->dfGCPLine = dfGCPLine;
}
const char * GDAL_GCP_get_Info( GDAL_GCP *gcp ) {
return gcp->pszInfo;
}
void GDAL_GCP_set_Info( GDAL_GCP *gcp, const char * pszInfo ) {
if ( gcp->pszInfo )
CPLFree( gcp->pszInfo );
gcp->pszInfo = CPLStrdup(pszInfo);
}
const char * GDAL_GCP_get_Id( GDAL_GCP *gcp ) {
return gcp->pszId;
}
void GDAL_GCP_set_Id( GDAL_GCP *gcp, const char * pszId ) {
if ( gcp->pszId )
CPLFree( gcp->pszId );
gcp->pszId = CPLStrdup(pszId);
}
/* Returned size is in bytes or 0 if an error occurred. */
static
GIntBig ComputeDatasetRasterIOSize (int buf_xsize, int buf_ysize, int nPixelSize,
int nBands, int* bandMap, int nBandMapArrayLength,
GIntBig nPixelSpace, GIntBig nLineSpace, GIntBig nBandSpace,
int bSpacingShouldBeMultipleOfPixelSize )
{
if (buf_xsize <= 0 || buf_ysize <= 0)
{
CPLError(CE_Failure, CPLE_IllegalArg, "Illegal values for buffer size");
return 0;
}
if (nPixelSpace < 0 || nLineSpace < 0 || nBandSpace < 0)
{
CPLError(CE_Failure, CPLE_IllegalArg, "Illegal values for space arguments");
return 0;
}
if (nPixelSize == 0)
{
CPLError(CE_Failure, CPLE_IllegalArg, "Illegal value for data type");
return 0;
}
if( nPixelSpace == 0 )
nPixelSpace = nPixelSize;
else if ( bSpacingShouldBeMultipleOfPixelSize && (nPixelSpace % nPixelSize) != 0 )
{
CPLError(CE_Failure, CPLE_IllegalArg, "nPixelSpace should be a multiple of nPixelSize");
return 0;
}
if( nLineSpace == 0 )
{
nLineSpace = nPixelSpace * buf_xsize;
}
else if ( bSpacingShouldBeMultipleOfPixelSize && (nLineSpace % nPixelSize) != 0 )
{
CPLError(CE_Failure, CPLE_IllegalArg, "nLineSpace should be a multiple of nPixelSize");
return 0;
}
if( nBandSpace == 0 )
{
nBandSpace = nLineSpace * buf_ysize;
}
else if ( bSpacingShouldBeMultipleOfPixelSize && (nBandSpace % nPixelSize) != 0 )
{
CPLError(CE_Failure, CPLE_IllegalArg, "nLineSpace should be a multiple of nPixelSize");
return 0;
}
if (nBands <= 0 || (bandMap != NULL && nBands > nBandMapArrayLength))
{
CPLError(CE_Failure, CPLE_IllegalArg, "Invalid band count");
return 0;
}
GIntBig nRet = (GIntBig)(buf_ysize - 1) * nLineSpace + (GIntBig)(buf_xsize - 1) * nPixelSpace + (GIntBig)(nBands - 1) * nBandSpace + nPixelSize;
#if SIZEOF_VOIDP == 4
if (nRet > INT_MAX)
{
CPLError(CE_Failure, CPLE_IllegalArg, "Integer overflow");
return 0;
}
#endif
return nRet;
}
typedef struct
{
GDALAsyncReaderH hAsyncReader;
void *pyObject;
} GDALAsyncReaderWrapper;
typedef void* GDALAsyncReaderWrapperH;
static GDALAsyncReaderH AsyncReaderWrapperGetReader(GDALAsyncReaderWrapperH hWrapper)
{
GDALAsyncReaderWrapper* psWrapper = (GDALAsyncReaderWrapper*)hWrapper;
if (psWrapper->hAsyncReader == NULL)
{
CPLError(CE_Failure, CPLE_AppDefined, "AsyncReader object is defunct");
}
return psWrapper->hAsyncReader;
}
#if defined(SWIGPYTHON)
static void* AsyncReaderWrapperGetPyObject(GDALAsyncReaderWrapperH hWrapper)
{
GDALAsyncReaderWrapper* psWrapper = (GDALAsyncReaderWrapper*)hWrapper;
return psWrapper->pyObject;
}
#endif
static void DeleteAsyncReaderWrapper(GDALAsyncReaderWrapperH hWrapper)
{
GDALAsyncReaderWrapper* psWrapper = (GDALAsyncReaderWrapper*)hWrapper;
if (psWrapper->hAsyncReader != NULL)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Native AsyncReader object will leak. EndAsyncReader() should have been called before");
}
CPLFree(psWrapper);
}
SWIGINTERN void delete_GDALAsyncReaderShadow(GDALAsyncReaderShadow *self){
DeleteAsyncReaderWrapper(self);
}
SWIGINTERN GDALAsyncStatusType GDALAsyncReaderShadow_GetNextUpdatedRegion(GDALAsyncReaderShadow *self,double timeout,int *xoff,int *yoff,int *buf_xsize,int *buf_ysize){
GDALAsyncReaderH hReader = AsyncReaderWrapperGetReader(self);
if (hReader == NULL)
{
*xoff = 0;
*yoff = 0;
*buf_xsize = 0;
*buf_ysize = 0;
return GARIO_ERROR;
}
return GDALARGetNextUpdatedRegion(hReader, timeout, xoff, yoff, buf_xsize, buf_ysize );
}
SWIGINTERN int GDALAsyncReaderShadow_LockBuffer(GDALAsyncReaderShadow *self,double timeout){
GDALAsyncReaderH hReader = AsyncReaderWrapperGetReader(self);
if (hReader == NULL)
{
return 0;
}
return GDALARLockBuffer(hReader,timeout);
}
SWIGINTERN void GDALAsyncReaderShadow_UnlockBuffer(GDALAsyncReaderShadow *self){
GDALAsyncReaderH hReader = AsyncReaderWrapperGetReader(self);
if (hReader == NULL)
{
return;
}
GDALARUnlockBuffer(hReader);
}
SWIGINTERN void delete_GDALDatasetShadow(GDALDatasetShadow *self){
if ( GDALDereferenceDataset( self ) <= 0 ) {
GDALClose(self);
}
}
SWIGINTERN GDALDriverShadow *GDALDatasetShadow_GetDriver(GDALDatasetShadow *self){
return (GDALDriverShadow*) GDALGetDatasetDriver( self );
}
SWIGINTERN GDALRasterBandShadow *GDALDatasetShadow_GetRasterBand(GDALDatasetShadow *self,int nBand){
return (GDALRasterBandShadow*) GDALGetRasterBand( self, nBand );
}
SWIGINTERN char const *GDALDatasetShadow_GetProjection(GDALDatasetShadow *self){
return GDALGetProjectionRef( self );
}
SWIGINTERN char const *GDALDatasetShadow_GetProjectionRef(GDALDatasetShadow *self){
return GDALGetProjectionRef( self );
}
SWIGINTERN CPLErr GDALDatasetShadow_SetProjection(GDALDatasetShadow *self,char const *prj){
return GDALSetProjection( self, prj );
}
SWIGINTERN void GDALDatasetShadow_GetGeoTransform(GDALDatasetShadow *self,double argout[6]){
if ( GDALGetGeoTransform( self, argout ) != CE_None ) {
argout[0] = 0.0;
argout[1] = 1.0;
argout[2] = 0.0;
argout[3] = 0.0;
argout[4] = 0.0;
argout[5] = 1.0;
}
}
SWIGINTERN CPLErr GDALDatasetShadow_SetGeoTransform(GDALDatasetShadow *self,double argin[6]){
return GDALSetGeoTransform( self, argin );
}
SWIGINTERN int GDALDatasetShadow_BuildOverviews(GDALDatasetShadow *self,char const *resampling="NEAREST",int overviewlist=0,int *pOverviews=0,GDALProgressFunc callback=NULL,void *callback_data=NULL){
return GDALBuildOverviews( self,
resampling ? resampling : "NEAREST",
overviewlist,
pOverviews,
0,
0,
callback,
callback_data);
}
SWIGINTERN int GDALDatasetShadow_GetGCPCount(GDALDatasetShadow *self){
return GDALGetGCPCount( self );
}
SWIGINTERN char const *GDALDatasetShadow_GetGCPProjection(GDALDatasetShadow *self){
return GDALGetGCPProjection( self );
}
SWIGINTERN void GDALDatasetShadow_FlushCache(GDALDatasetShadow *self){
GDALFlushCache( self );
}
SWIGINTERN CPLErr GDALDatasetShadow_AddBand(GDALDatasetShadow *self,GDALDataType datatype=GDT_Byte,char **options=0){
return GDALAddBand( self, datatype, options );
}
SWIGINTERN CPLErr GDALDatasetShadow_CreateMaskBand(GDALDatasetShadow *self,int nFlags){
return GDALCreateDatasetMaskBand( self, nFlags );
}
SWIGINTERN char **GDALDatasetShadow_GetFileList(GDALDatasetShadow *self){
return GDALGetFileList( self );
}
SWIGINTERN OGRErr GDALDatasetShadow_StartTransaction(GDALDatasetShadow *self,int force=FALSE){
return GDALDatasetStartTransaction(self, force);
}
static char const *
OGRErrMessages( int rc ) {
switch( rc ) {
case 0:
return "OGR Error %d: None";
case 1:
return "OGR Error %d: Not enough data";
case 2:
return "OGR Error %d: Unsupported geometry type";
case 3:
return "OGR Error %d: Unsupported operation";
case 4:
return "OGR Error %d: Corrupt data";
case 5:
return "OGR Error %d: General Error";
case 6:
return "OGR Error %d: Unsupported SRS";
default:
return "OGR Error %d: Unknown";
}
}
SWIGINTERN OGRErr GDALDatasetShadow_CommitTransaction(GDALDatasetShadow *self){
return GDALDatasetCommitTransaction(self);
}
SWIGINTERN OGRErr GDALDatasetShadow_RollbackTransaction(GDALDatasetShadow *self){
return GDALDatasetRollbackTransaction(self);
}
SWIGINTERN CPLErr GDALDatasetShadow_ReadRaster(GDALDatasetShadow *self,int xOff,int yOff,int xSize,int ySize,void *buffer,int buf_xSize,int buf_ySize,GDALDataType buf_type,int bandCount,int *bandMap,int pixelSpace,int lineSpace,int bandSpace){
return GDALDatasetRasterIO( self, GF_Read, xOff, yOff, xSize, ySize,
buffer, buf_xSize, buf_ySize, buf_type, bandCount,
bandMap, pixelSpace, lineSpace, bandSpace);
}
SWIGINTERN CPLErr GDALDatasetShadow_WriteRaster(GDALDatasetShadow *self,int xOff,int yOff,int xSize,int ySize,void *buffer,int buf_xSize,int buf_ySize,GDALDataType buf_type,int bandCount,int *bandMap,int pixelSpace,int lineSpace,int bandSpace){
return GDALDatasetRasterIO( self, GF_Write, xOff, yOff, xSize, ySize,
buffer, buf_xSize, buf_ySize, buf_type, bandCount,
bandMap, pixelSpace, lineSpace, bandSpace);
}
SWIGINTERN GDAL_GCP const *GDALDatasetShadow___GetGCPs(GDALDatasetShadow *self){
return GDALGetGCPs( self );
}
SWIGINTERN CPLErr GDALDatasetShadow___SetGCPs(GDALDatasetShadow *self,int nGCPs,GDAL_GCP const *pGCPs,char const *pszGCPProjection){
return GDALSetGCPs( self, nGCPs, pGCPs, pszGCPProjection );
}
SWIGINTERN void GDALDatasetShadow___WriteCArrayItem_GDAL_GCP(GDALDatasetShadow *self,GDAL_GCP *carray,int index,GDAL_GCP *value){
carray[index] = *value;
}
SWIGINTERN GDAL_GCP *GDALDatasetShadow___ReadCArrayItem_GDAL_GCP(GDALDatasetShadow *self,GDAL_GCP *carray,int index){
return &carray[index];
}
SWIGINTERN GDAL_GCP *GDALDatasetShadow___AllocCArray_GDAL_GCP(GDALDatasetShadow *self,int size){
return (GDAL_GCP*)CPLMalloc(size * sizeof(GDAL_GCP));
}
SWIGINTERN void GDALDatasetShadow___FreeCArray_GDAL_GCP(GDALDatasetShadow *self,GDAL_GCP *carray){
if (carray)
CPLFree(carray);
}
int GDALDatasetShadow_RasterXSize_get( GDALDatasetShadow *h ) {
return GDALGetRasterXSize( h );
}
int GDALDatasetShadow_RasterYSize_get( GDALDatasetShadow *h ) {
return GDALGetRasterYSize( h );
}
int GDALDatasetShadow_RasterCount_get( GDALDatasetShadow *h ) {
return GDALGetRasterCount( h );
}
/* Returned size is in bytes or 0 if an error occurred. */
static
GIntBig ComputeBandRasterIOSize (int buf_xsize, int buf_ysize, int nPixelSize,
GIntBig nPixelSpace, GIntBig nLineSpace,
int bSpacingShouldBeMultipleOfPixelSize )
{
if (buf_xsize <= 0 || buf_ysize <= 0)
{
CPLError(CE_Failure, CPLE_IllegalArg, "Illegal values for buffer size");
return 0;
}
if (nPixelSpace < 0 || nLineSpace < 0)
{
CPLError(CE_Failure, CPLE_IllegalArg, "Illegal values for space arguments");
return 0;
}
if (nPixelSize == 0)
{
CPLError(CE_Failure, CPLE_IllegalArg, "Illegal value for data type");
return 0;
}
if( nPixelSpace == 0 )
nPixelSpace = nPixelSize;
else if ( bSpacingShouldBeMultipleOfPixelSize && (nPixelSpace % nPixelSize) != 0 )
{
CPLError(CE_Failure, CPLE_IllegalArg, "nPixelSpace should be a multiple of nPixelSize");
return 0;
}
if( nLineSpace == 0 )
{
nLineSpace = nPixelSpace * buf_xsize;
}
else if ( bSpacingShouldBeMultipleOfPixelSize && (nLineSpace % nPixelSize) != 0 )
{
CPLError(CE_Failure, CPLE_IllegalArg, "nLineSpace should be a multiple of nPixelSize");
return 0;
}
GIntBig nRet = (GIntBig)(buf_ysize - 1) * nLineSpace + (GIntBig)(buf_xsize - 1) * nPixelSpace + nPixelSize;
#if SIZEOF_VOIDP == 4
if (nRet > INT_MAX)
{
CPLError(CE_Failure, CPLE_IllegalArg, "Integer overflow");
return 0;
}
#endif
return nRet;
}
SWIGINTERN GDALDatasetShadow *GDALRasterBandShadow_GetDataset(GDALRasterBandShadow *self){
return (GDALDatasetShadow*) GDALGetBandDataset(self);
}
SWIGINTERN int GDALRasterBandShadow_GetBand(GDALRasterBandShadow *self){
return GDALGetBandNumber(self);
}
SWIGINTERN void GDALRasterBandShadow_GetBlockSize(GDALRasterBandShadow *self,int *pnBlockXSize,int *pnBlockYSize){
GDALGetBlockSize(self, pnBlockXSize, pnBlockYSize);
}
SWIGINTERN GDALColorInterp GDALRasterBandShadow_GetColorInterpretation(GDALRasterBandShadow *self){
return GDALGetRasterColorInterpretation( self );
}
SWIGINTERN GDALColorInterp GDALRasterBandShadow_GetRasterColorInterpretation(GDALRasterBandShadow *self){
return GDALGetRasterColorInterpretation( self );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetColorInterpretation(GDALRasterBandShadow *self,GDALColorInterp val){
return GDALSetRasterColorInterpretation( self, val );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetRasterColorInterpretation(GDALRasterBandShadow *self,GDALColorInterp val){
return GDALSetRasterColorInterpretation( self, val );
}
SWIGINTERN void GDALRasterBandShadow_GetNoDataValue(GDALRasterBandShadow *self,double *val,int *hasval){
*val = GDALGetRasterNoDataValue( self, hasval );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetNoDataValue(GDALRasterBandShadow *self,double d){
return GDALSetRasterNoDataValue( self, d );
}
SWIGINTERN CPLErr GDALRasterBandShadow_DeleteNoDataValue(GDALRasterBandShadow *self){
return GDALDeleteRasterNoDataValue( self );
}
SWIGINTERN char const *GDALRasterBandShadow_GetUnitType(GDALRasterBandShadow *self){
return GDALGetRasterUnitType( self );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetUnitType(GDALRasterBandShadow *self,char const *val){
return GDALSetRasterUnitType( self, val );
}
SWIGINTERN char **GDALRasterBandShadow_GetRasterCategoryNames(GDALRasterBandShadow *self){
return GDALGetRasterCategoryNames( self );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetRasterCategoryNames(GDALRasterBandShadow *self,char **names){
return GDALSetRasterCategoryNames( self, names );
}
SWIGINTERN void GDALRasterBandShadow_GetMinimum(GDALRasterBandShadow *self,double *val,int *hasval){
*val = GDALGetRasterMinimum( self, hasval );
}
SWIGINTERN void GDALRasterBandShadow_GetMaximum(GDALRasterBandShadow *self,double *val,int *hasval){
*val = GDALGetRasterMaximum( self, hasval );
}
SWIGINTERN void GDALRasterBandShadow_GetOffset(GDALRasterBandShadow *self,double *val,int *hasval){
*val = GDALGetRasterOffset( self, hasval );
}
SWIGINTERN void GDALRasterBandShadow_GetScale(GDALRasterBandShadow *self,double *val,int *hasval){
*val = GDALGetRasterScale( self, hasval );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetOffset(GDALRasterBandShadow *self,double val){
return GDALSetRasterOffset( self, val );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetScale(GDALRasterBandShadow *self,double val){
return GDALSetRasterScale( self, val );
}
SWIGINTERN CPLErr GDALRasterBandShadow_GetStatistics(GDALRasterBandShadow *self,int approx_ok,int force,double *min,double *max,double *mean,double *stddev){
if (min) *min = 0;
if (max) *max = 0;
if (mean) *mean = 0;
if (stddev) *stddev = -1; /* This is the only way to recognize from Python if GetRasterStatistics() has updated the values */
return GDALGetRasterStatistics( self, approx_ok, force,
min, max, mean, stddev );
}
SWIGINTERN CPLErr GDALRasterBandShadow_ComputeStatistics(GDALRasterBandShadow *self,bool approx_ok,double *min=NULL,double *max=NULL,double *mean=NULL,double *stddev=NULL,GDALProgressFunc callback=NULL,void *callback_data=NULL){
return GDALComputeRasterStatistics( self, approx_ok, min, max, mean, stddev, callback, callback_data );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetStatistics(GDALRasterBandShadow *self,double min,double max,double mean,double stddev){
return GDALSetRasterStatistics( self, min, max, mean, stddev );
}
SWIGINTERN int GDALRasterBandShadow_GetOverviewCount(GDALRasterBandShadow *self){
return GDALGetOverviewCount( self );
}
SWIGINTERN GDALRasterBandShadow *GDALRasterBandShadow_GetOverview(GDALRasterBandShadow *self,int i){
return (GDALRasterBandShadow*) GDALGetOverview( self, i );
}
SWIGINTERN int GDALRasterBandShadow_Checksum(GDALRasterBandShadow *self,int xoff=0,int yoff=0,int *xsize=0,int *ysize=0){
int nxsize = (xsize!=0) ? *xsize : GDALGetRasterBandXSize( self );
int nysize = (ysize!=0) ? *ysize : GDALGetRasterBandYSize( self );
return GDALChecksumImage( self, xoff, yoff, nxsize, nysize );
}
SWIGINTERN void GDALRasterBandShadow_ComputeRasterMinMax(GDALRasterBandShadow *self,double argout[2],int approx_ok=0){
GDALComputeRasterMinMax( self, approx_ok, argout );
}
SWIGINTERN void GDALRasterBandShadow_ComputeBandStats(GDALRasterBandShadow *self,double argout[2],int samplestep=1){
GDALComputeBandStats( self, samplestep, argout+0, argout+1,
NULL, NULL );
}
SWIGINTERN CPLErr GDALRasterBandShadow_Fill(GDALRasterBandShadow *self,double real_fill,double imag_fill=0.0){
return GDALFillRaster( self, real_fill, imag_fill );
}
SWIGINTERN void GDALRasterBandShadow_FlushCache(GDALRasterBandShadow *self){
GDALFlushRasterCache( self );
}
SWIGINTERN GDALColorTableShadow *GDALRasterBandShadow_GetRasterColorTable(GDALRasterBandShadow *self){
return (GDALColorTableShadow*) GDALGetRasterColorTable( self );
}
SWIGINTERN GDALColorTableShadow *GDALRasterBandShadow_GetColorTable(GDALRasterBandShadow *self){
return (GDALColorTableShadow*) GDALGetRasterColorTable( self );
}
SWIGINTERN int GDALRasterBandShadow_SetRasterColorTable(GDALRasterBandShadow *self,GDALColorTableShadow *arg){
return GDALSetRasterColorTable( self, arg );
}
SWIGINTERN int GDALRasterBandShadow_SetColorTable(GDALRasterBandShadow *self,GDALColorTableShadow *arg){
return GDALSetRasterColorTable( self, arg );
}
SWIGINTERN GDALRasterAttributeTableShadow *GDALRasterBandShadow_GetDefaultRAT(GDALRasterBandShadow *self){
return (GDALRasterAttributeTableShadow*) GDALGetDefaultRAT(self);
}
SWIGINTERN int GDALRasterBandShadow_SetDefaultRAT(GDALRasterBandShadow *self,GDALRasterAttributeTableShadow *table){
return GDALSetDefaultRAT(self, table);
}
SWIGINTERN GDALRasterBandShadow *GDALRasterBandShadow_GetMaskBand(GDALRasterBandShadow *self){
return (GDALRasterBandShadow *) GDALGetMaskBand( self );
}
SWIGINTERN int GDALRasterBandShadow_GetMaskFlags(GDALRasterBandShadow *self){
return GDALGetMaskFlags( self );
}
SWIGINTERN CPLErr GDALRasterBandShadow_CreateMaskBand(GDALRasterBandShadow *self,int nFlags){
return GDALCreateMaskBand( self, nFlags );
}
SWIGINTERN CPLErr GDALRasterBandShadow_GetHistogram(GDALRasterBandShadow *self,double min=-0.5,double max=255.5,int buckets=256,int *panHistogram=NULL,int include_out_of_range=0,int approx_ok=1,GDALProgressFunc callback=NULL,void *callback_data=NULL){
CPLErrorReset();
CPLErr err = GDALGetRasterHistogram( self, min, max, buckets, panHistogram,
include_out_of_range, approx_ok,
callback, callback_data );
return err;
}
SWIGINTERN CPLErr GDALRasterBandShadow_GetDefaultHistogram(GDALRasterBandShadow *self,double *min_ret=NULL,double *max_ret=NULL,int *buckets_ret=NULL,int **ppanHistogram=NULL,int force=1,GDALProgressFunc callback=NULL,void *callback_data=NULL){
return GDALGetDefaultHistogram( self, min_ret, max_ret, buckets_ret,
ppanHistogram, force,
callback, callback_data );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetDefaultHistogram(GDALRasterBandShadow *self,double min,double max,int buckets_in,int *panHistogram_in){
return GDALSetDefaultHistogram( self, min, max,
buckets_in, panHistogram_in );
}
SWIGINTERN bool GDALRasterBandShadow_HasArbitraryOverviews(GDALRasterBandShadow *self){
return (GDALHasArbitraryOverviews( self ) != 0) ? true : false;
}
SWIGINTERN char **GDALRasterBandShadow_GetCategoryNames(GDALRasterBandShadow *self){
return GDALGetRasterCategoryNames( self );
}
SWIGINTERN CPLErr GDALRasterBandShadow_SetCategoryNames(GDALRasterBandShadow *self,char **papszCategoryNames){
return GDALSetRasterCategoryNames( self, papszCategoryNames );
}
SWIGINTERN CPLErr GDALRasterBandShadow_ReadRaster(GDALRasterBandShadow *self,int xOff,int yOff,int xSize,int ySize,void *buffer,int buf_xSize,int buf_ySize,GDALDataType buf_type,int pixelSpace,int lineSpace){
return GDALRasterIO( self, GF_Read, xOff, yOff, xSize, ySize,
buffer, buf_xSize, buf_ySize, buf_type, pixelSpace, lineSpace );
}
SWIGINTERN CPLErr GDALRasterBandShadow_WriteRaster(GDALRasterBandShadow *self,int xOff,int yOff,int xSize,int ySize,void *buffer,int buf_xSize,int buf_ySize,GDALDataType buf_type,int pixelSpace,int lineSpace){
return GDALRasterIO( self, GF_Write, xOff, yOff, xSize, ySize,
buffer, buf_xSize, buf_ySize, buf_type, pixelSpace, lineSpace );
}
GDALDataType GDALRasterBandShadow_DataType_get( GDALRasterBandShadow *h ) {
return GDALGetRasterDataType( h );
}
int GDALRasterBandShadow_XSize_get( GDALRasterBandShadow *h ) {
return GDALGetRasterBandXSize( h );
}
int GDALRasterBandShadow_YSize_get( GDALRasterBandShadow *h ) {
return GDALGetRasterBandYSize( h );
}
SWIGINTERN GDALColorTableShadow *new_GDALColorTableShadow(GDALPaletteInterp palette=GPI_RGB){
return (GDALColorTableShadow*) GDALCreateColorTable(palette);
}
SWIGINTERN void delete_GDALColorTableShadow(GDALColorTableShadow *self){
GDALDestroyColorTable(self);
}
SWIGINTERN GDALColorTableShadow *GDALColorTableShadow_Clone(GDALColorTableShadow *self){
return (GDALColorTableShadow*) GDALCloneColorTable (self);
}
SWIGINTERN GDALPaletteInterp GDALColorTableShadow_GetPaletteInterpretation(GDALColorTableShadow *self){
return GDALGetPaletteInterpretation(self);
}
SWIGINTERN int GDALColorTableShadow_GetColorEntryCount(GDALColorTableShadow *self){
return GDALGetColorEntryCount(self);
}
SWIGINTERN GDALColorEntry *GDALColorTableShadow_GetColorEntry(GDALColorTableShadow *self,int entry){
return (GDALColorEntry*) GDALGetColorEntry(self, entry);
}
SWIGINTERN int GDALColorTableShadow_GetColorEntryAsRGB(GDALColorTableShadow *self,int entry,GDALColorEntry *centry){
return GDALGetColorEntryAsRGB(self, entry, centry);
}
SWIGINTERN void GDALColorTableShadow_SetColorEntry(GDALColorTableShadow *self,int entry,GDALColorEntry const *centry){
GDALSetColorEntry(self, entry, centry);
}
SWIGINTERN void GDALColorTableShadow_CreateColorRamp(GDALColorTableShadow *self,int nStartIndex,GDALColorEntry const *startcolor,int nEndIndex,GDALColorEntry const *endcolor){
GDALCreateColorRamp(self, nStartIndex, startcolor, nEndIndex, endcolor);
}
SWIGINTERN GDALRasterAttributeTableShadow *new_GDALRasterAttributeTableShadow(){
return (GDALRasterAttributeTableShadow*)
GDALCreateRasterAttributeTable();
}
SWIGINTERN void delete_GDALRasterAttributeTableShadow(GDALRasterAttributeTableShadow *self){
GDALDestroyRasterAttributeTable(self);
}
SWIGINTERN GDALRasterAttributeTableShadow *GDALRasterAttributeTableShadow_Clone(GDALRasterAttributeTableShadow *self){
return (GDALRasterAttributeTableShadow*) GDALRATClone(self);
}
SWIGINTERN int GDALRasterAttributeTableShadow_GetColumnCount(GDALRasterAttributeTableShadow *self){
return GDALRATGetColumnCount( self );
}
SWIGINTERN char const *GDALRasterAttributeTableShadow_GetNameOfCol(GDALRasterAttributeTableShadow *self,int iCol){
return GDALRATGetNameOfCol( self, iCol );
}
SWIGINTERN GDALRATFieldUsage GDALRasterAttributeTableShadow_GetUsageOfCol(GDALRasterAttributeTableShadow *self,int iCol){
return GDALRATGetUsageOfCol( self, iCol );
}
SWIGINTERN GDALRATFieldType GDALRasterAttributeTableShadow_GetTypeOfCol(GDALRasterAttributeTableShadow *self,int iCol){
return GDALRATGetTypeOfCol( self, iCol );
}
SWIGINTERN int GDALRasterAttributeTableShadow_GetColOfUsage(GDALRasterAttributeTableShadow *self,GDALRATFieldUsage eUsage){
return GDALRATGetColOfUsage( self, eUsage );
}
SWIGINTERN int GDALRasterAttributeTableShadow_GetRowCount(GDALRasterAttributeTableShadow *self){
return GDALRATGetRowCount( self );
}
SWIGINTERN char const *GDALRasterAttributeTableShadow_GetValueAsString(GDALRasterAttributeTableShadow *self,int iRow,int iCol){
return GDALRATGetValueAsString( self, iRow, iCol );
}
SWIGINTERN int GDALRasterAttributeTableShadow_GetValueAsInt(GDALRasterAttributeTableShadow *self,int iRow,int iCol){
return GDALRATGetValueAsInt( self, iRow, iCol );
}
SWIGINTERN double GDALRasterAttributeTableShadow_GetValueAsDouble(GDALRasterAttributeTableShadow *self,int iRow,int iCol){
return GDALRATGetValueAsDouble( self, iRow, iCol );
}
SWIGINTERN void GDALRasterAttributeTableShadow_SetValueAsString(GDALRasterAttributeTableShadow *self,int iRow,int iCol,char const *pszValue){
GDALRATSetValueAsString( self, iRow, iCol, pszValue );
}
SWIGINTERN void GDALRasterAttributeTableShadow_SetValueAsInt(GDALRasterAttributeTableShadow *self,int iRow,int iCol,int nValue){
GDALRATSetValueAsInt( self, iRow, iCol, nValue );
}
SWIGINTERN void GDALRasterAttributeTableShadow_SetValueAsDouble(GDALRasterAttributeTableShadow *self,int iRow,int iCol,double dfValue){
GDALRATSetValueAsDouble( self, iRow, iCol, dfValue );
}
SWIGINTERN void GDALRasterAttributeTableShadow_SetRowCount(GDALRasterAttributeTableShadow *self,int nCount){
GDALRATSetRowCount( self, nCount );
}
SWIGINTERN int GDALRasterAttributeTableShadow_CreateColumn(GDALRasterAttributeTableShadow *self,char const *pszName,GDALRATFieldType eType,GDALRATFieldUsage eUsage){
return GDALRATCreateColumn( self, pszName, eType, eUsage );
}
SWIGINTERN bool GDALRasterAttributeTableShadow_GetLinearBinning(GDALRasterAttributeTableShadow *self,double *pdfRow0Min,double *pdfBinSize){
return (GDALRATGetLinearBinning(self, pdfRow0Min, pdfBinSize) != 0) ? true : false;
}
SWIGINTERN int GDALRasterAttributeTableShadow_SetLinearBinning(GDALRasterAttributeTableShadow *self,double dfRow0Min,double dfBinSize){
return GDALRATSetLinearBinning(self, dfRow0Min, dfBinSize);
}
SWIGINTERN int GDALRasterAttributeTableShadow_GetRowOfValue(GDALRasterAttributeTableShadow *self,double dfValue){
return GDALRATGetRowOfValue( self, dfValue );
}
SWIGINTERN int GDALRasterAttributeTableShadow_ChangesAreWrittenToFile(GDALRasterAttributeTableShadow *self){
return GDALRATChangesAreWrittenToFile( self );
}
SWIGINTERN void GDALRasterAttributeTableShadow_DumpReadable(GDALRasterAttributeTableShadow *self){
GDALRATDumpReadable( self, NULL );
}
#include "gdalgrid.h"
#ifdef DEBUG
typedef struct OGRLayerHS OGRLayerShadow;
typedef struct OGRGeometryHS OGRGeometryShadow;
#else
typedef void OGRLayerShadow;
typedef void OGRGeometryShadow;
#endif
int ComputeMedianCutPCT ( GDALRasterBandShadow *red,
GDALRasterBandShadow *green,
GDALRasterBandShadow *blue,
int num_colors,
GDALColorTableShadow* colors,
GDALProgressFunc callback = NULL,
void* callback_data=NULL) {
CPLErrorReset();
int err = GDALComputeMedianCutPCT( red,
green,
blue,
NULL,
num_colors,
colors,
callback,
callback_data);
return err;
}
int DitherRGB2PCT ( GDALRasterBandShadow *red,
GDALRasterBandShadow *green,
GDALRasterBandShadow *blue,
GDALRasterBandShadow *target,
GDALColorTableShadow *colors,
GDALProgressFunc callback = NULL,
void* callback_data=NULL) {
CPLErrorReset();
int err;
err = GDALDitherRGB2PCT( red,
green,
blue,
target,
colors,
callback,
callback_data);
return err;
}
CPLErr ReprojectImage ( GDALDatasetShadow *src_ds,
GDALDatasetShadow *dst_ds,
const char *src_wkt=NULL,
const char *dst_wkt=NULL,
GDALResampleAlg eResampleAlg=GRA_NearestNeighbour,
double WarpMemoryLimit=0.0,
double maxerror = 0.0,
GDALProgressFunc callback = NULL,
void* callback_data=NULL,
char** options = NULL ) {
CPLErrorReset();
GDALWarpOptions* psOptions = NULL;
if( options != NULL )
{
psOptions = GDALCreateWarpOptions();
psOptions->papszWarpOptions = CSLDuplicate(options);
}
CPLErr err = GDALReprojectImage( src_ds,
src_wkt,
dst_ds,
dst_wkt,
eResampleAlg,
WarpMemoryLimit,
maxerror,
callback,
callback_data,
psOptions);
if( psOptions != NULL )
GDALDestroyWarpOptions(psOptions);
return err;
}
int ComputeProximity( GDALRasterBandShadow *srcBand,
GDALRasterBandShadow *proximityBand,
char **options = NULL,
GDALProgressFunc callback=NULL,
void* callback_data=NULL) {
CPLErrorReset();
return GDALComputeProximity( srcBand, proximityBand, options,
callback, callback_data );
}
int RasterizeLayer( GDALDatasetShadow *dataset,
int bands, int *band_list,
OGRLayerShadow *layer,
void *pfnTransformer = NULL,
void *pTransformArg = NULL,
int burn_values = 0, double *burn_values_list = NULL,
char **options = NULL,
GDALProgressFunc callback=NULL,
void* callback_data=NULL) {
CPLErr eErr;
CPLErrorReset();
if( burn_values == 0 )
{
burn_values_list = (double *) CPLMalloc(sizeof(double)*bands);
for( int i = 0; i < bands; i++ )
burn_values_list[i] = 255.0;
}
else if( burn_values != bands )
{
CPLError( CE_Failure, CPLE_AppDefined,
"Did not get the expected number of burn values in RasterizeLayer()" );
return CE_Failure;
}
eErr = GDALRasterizeLayers( dataset, bands, band_list,
1, &layer,
(GDALTransformerFunc) pfnTransformer,
pTransformArg,
burn_values_list, options,
callback, callback_data );
if( burn_values == 0 )
CPLFree( burn_values_list );
return eErr;
}
int Polygonize( GDALRasterBandShadow *srcBand,
GDALRasterBandShadow *maskBand,
OGRLayerShadow *outLayer,
int iPixValField,
char **options = NULL,
GDALProgressFunc callback=NULL,
void* callback_data=NULL) {
CPLErrorReset();
return GDALPolygonize( srcBand, maskBand, outLayer, iPixValField,
options, callback, callback_data );
}
int FPolygonize( GDALRasterBandShadow *srcBand,
GDALRasterBandShadow *maskBand,
OGRLayerShadow *outLayer,
int iPixValField,
char **options = NULL,
GDALProgressFunc callback=NULL,
void* callback_data=NULL) {
CPLErrorReset();
return GDALFPolygonize( srcBand, maskBand, outLayer, iPixValField,
options, callback, callback_data );
}
int FillNodata( GDALRasterBandShadow *targetBand,
GDALRasterBandShadow *maskBand,
double maxSearchDist,
int smoothingIterations,
char **options = NULL,
GDALProgressFunc callback=NULL,
void* callback_data=NULL) {
CPLErrorReset();
return GDALFillNodata( targetBand, maskBand, maxSearchDist,
0, smoothingIterations, options,
callback, callback_data );
}
int SieveFilter( GDALRasterBandShadow *srcBand,
GDALRasterBandShadow *maskBand,
GDALRasterBandShadow *dstBand,
int threshold, int connectedness=4,
char **options = NULL,
GDALProgressFunc callback=NULL,
void* callback_data=NULL) {
CPLErrorReset();
return GDALSieveFilter( srcBand, maskBand, dstBand,
threshold, connectedness,
options, callback, callback_data );
}
int RegenerateOverviews( GDALRasterBandShadow *srcBand,
int overviewBandCount,
GDALRasterBandShadow **overviewBands,
const char *resampling = "average",
GDALProgressFunc callback=NULL,
void* callback_data=NULL) {
CPLErrorReset();
return GDALRegenerateOverviews( srcBand, overviewBandCount, overviewBands,
resampling ? resampling : "average", callback, callback_data );
}
int RegenerateOverview( GDALRasterBandShadow *srcBand,
GDALRasterBandShadow *overviewBand,
const char *resampling = "average",
GDALProgressFunc callback=NULL,
void* callback_data=NULL) {
CPLErrorReset();
return GDALRegenerateOverviews( srcBand, 1, &overviewBand,
resampling ? resampling : "average", callback, callback_data );
}
int ContourGenerate( GDALRasterBandShadow *srcBand,
double contourInterval,
double contourBase,
int fixedLevelCount,
double *fixedLevels,
int useNoData,
double noDataValue,
OGRLayerShadow* dstLayer,
int idField,
int elevField,
GDALProgressFunc callback = NULL,
void* callback_data = NULL)
{
CPLErr eErr;
CPLErrorReset();
eErr = GDALContourGenerate( srcBand,
contourInterval,
contourBase,
fixedLevelCount,
fixedLevels,
useNoData,
noDataValue,
dstLayer,
idField,
elevField,
callback,
callback_data);
return eErr;
}
GDALDatasetShadow *AutoCreateWarpedVRT( GDALDatasetShadow *src_ds,
const char *src_wkt = 0,
const char *dst_wkt = 0,
GDALResampleAlg eResampleAlg = GRA_NearestNeighbour,
double maxerror = 0.0 ) {
GDALDatasetShadow *ds = GDALAutoCreateWarpedVRT( src_ds, src_wkt,
dst_wkt,
eResampleAlg,
maxerror,
0 );
if (ds == 0) {
/*throw CPLGetLastErrorMsg(); causes a SWIG_exception later*/
}
return ds;
}
GDALDatasetShadow* CreatePansharpenedVRT( const char* pszXML,
GDALRasterBandShadow* panchroBand,
int nInputSpectralBands,
GDALRasterBandShadow** ahInputSpectralBands )
{
CPLErrorReset();
return (GDALDatasetShadow*)GDALCreatePansharpenedVRT( pszXML, panchroBand,
nInputSpectralBands, ahInputSpectralBands );
}
SWIGINTERN GDALTransformerInfoShadow *new_GDALTransformerInfoShadow(GDALDatasetShadow *src,GDALDatasetShadow *dst,char **options){
GDALTransformerInfoShadow *obj = (GDALTransformerInfoShadow*)
GDALCreateGenImgProjTransformer2( (GDALDatasetH)src, (GDALDatasetH)dst,
options );
return obj;
}
SWIGINTERN void delete_GDALTransformerInfoShadow(GDALTransformerInfoShadow *self){
GDALDestroyTransformer( self );
}
SWIGINTERN int GDALTransformerInfoShadow_TransformPoint__SWIG_0(GDALTransformerInfoShadow *self,int bDstToSrc,double inout[3]){
int nRet, nSuccess = TRUE;
nRet = GDALUseTransformer( self, bDstToSrc,
1, &inout[0], &inout[1], &inout[2],
&nSuccess );
return nRet && nSuccess;
}
SWIGINTERN int GDALTransformerInfoShadow_TransformPoint__SWIG_1(GDALTransformerInfoShadow *self,double argout[3],int bDstToSrc,double x,double y,double z=0.0){
int nRet, nSuccess = TRUE;
argout[0] = x;
argout[1] = y;
argout[2] = z;
nRet = GDALUseTransformer( self, bDstToSrc,
1, &argout[0], &argout[1], &argout[2],
&nSuccess );
return nRet && nSuccess;
}
SWIGINTERN int GDALTransformerInfoShadow_TransformPoints(GDALTransformerInfoShadow *self,int bDstToSrc,int nCount,double *x,double *y,double *z,int *panSuccess){
int nRet;
nRet = GDALUseTransformer( self, bDstToSrc, nCount, x, y, z, panSuccess );
return nRet;
}
SWIGINTERN int GDALTransformerInfoShadow_TransformGeolocations(GDALTransformerInfoShadow *self,GDALRasterBandShadow *xBand,GDALRasterBandShadow *yBand,GDALRasterBandShadow *zBand,GDALProgressFunc callback=NULL,void *callback_data=NULL,char **options=NULL){
CPLErrorReset();
return GDALTransformGeolocations( xBand, yBand, zBand,
GDALUseTransformer, self,
callback, callback_data, options );
}
GDALDatasetShadow* ApplyVerticalShiftGrid( GDALDatasetShadow *src_ds,
GDALDatasetShadow *grid_ds,
bool inverse = false,
double srcUnitToMeter = 1.0,
double dstUnitToMeter = 1.0,
char** options = NULL ) {
GDALDatasetShadow *ds = GDALApplyVerticalShiftGrid( src_ds, grid_ds,
inverse,
srcUnitToMeter,
dstUnitToMeter,
options );
return ds;
}
int wrapper_GDALGetCacheMax()
{
return GDALGetCacheMax();
}
int wrapper_GDALGetCacheUsed()
{
return GDALGetCacheUsed();
}
void wrapper_GDALSetCacheMax(int nBytes)
{
return GDALSetCacheMax(nBytes);
}
retStringAndCPLFree *GetJPEG2000StructureAsString( const char* pszFilename, char** options = NULL )
{
CPLXMLNode* psNode = GDALGetJPEG2000Structure(pszFilename, options);
if( psNode == NULL )
return NULL;
char* pszXML = CPLSerializeXMLTree(psNode);
CPLDestroyXMLNode(psNode);
return pszXML;
}
int GetDriverCount() {
return GDALGetDriverCount();
}
static
GDALDriverShadow* GetDriverByName( char const *name ) {
return (GDALDriverShadow*) GDALGetDriverByName( name );
}
GDALDriverShadow* GetDriver( int i ) {
return (GDALDriverShadow*) GDALGetDriver( i );
}
GDALDatasetShadow* Open( char const* utf8_path, GDALAccess eAccess = GA_ReadOnly ) {
CPLErrorReset();
GDALDatasetShadow *ds = GDALOpen( utf8_path, eAccess );
if( ds != NULL && CPLGetLastErrorType() == CE_Failure )
{
if ( GDALDereferenceDataset( ds ) <= 0 )
GDALClose(ds);
ds = NULL;
}
return (GDALDatasetShadow*) ds;
}
GDALDatasetShadow* OpenEx( char const* utf8_path, unsigned int nOpenFlags = 0,
char** allowed_drivers = NULL, char** open_options = NULL,
char** sibling_files = NULL ) {
CPLErrorReset();
#ifdef SWIGPYTHON
if( GetUseExceptions() )
nOpenFlags |= GDAL_OF_VERBOSE_ERROR;
#endif
GDALDatasetShadow *ds = GDALOpenEx( utf8_path, nOpenFlags, allowed_drivers,
open_options, sibling_files );
if( ds != NULL && CPLGetLastErrorType() == CE_Failure )
{
if ( GDALDereferenceDataset( ds ) <= 0 )
GDALClose(ds);
ds = NULL;
}
return (GDALDatasetShadow*) ds;
}
GDALDatasetShadow* OpenShared( char const* utf8_path, GDALAccess eAccess = GA_ReadOnly ) {
CPLErrorReset();
GDALDatasetShadow *ds = GDALOpenShared( utf8_path, eAccess );
if( ds != NULL && CPLGetLastErrorType() == CE_Failure )
{
if ( GDALDereferenceDataset( ds ) <= 0 )
GDALClose(ds);
ds = NULL;
}
return (GDALDatasetShadow*) ds;
}
GDALDriverShadow *IdentifyDriver( const char *utf8_path,
char **papszSiblings = NULL ) {
return (GDALDriverShadow *) GDALIdentifyDriver( utf8_path,
papszSiblings );
}
GDALDriverShadow *IdentifyDriverEx( const char* utf8_path,
unsigned int nIdentifyFlags = 0,
char** allowed_drivers = NULL,
char** sibling_files = NULL )
{
return (GDALDriverShadow *) GDALIdentifyDriverEx( utf8_path,
nIdentifyFlags,
allowed_drivers,
sibling_files );
}
char **GeneralCmdLineProcessor( char **papszArgv, int nOptions = 0 ) {
int nResArgCount;
if( papszArgv == NULL )
return NULL;
nResArgCount =
GDALGeneralCmdLineProcessor( CSLCount(papszArgv), &papszArgv, nOptions );
if( nResArgCount <= 0 )
return NULL;
else
return papszArgv;
}
void __WriteCArrayItem_GDAL_GCP(GDAL_GCP* carray, int index, GDAL_GCP* value) {
carray[index] = *value;
}
GDAL_GCP* __ReadCArrayItem_GDAL_GCP(GDAL_GCP* carray, int index) {
return &carray[index];
}
GDAL_GCP* __AllocCArray_GDAL_GCP(int size) {
return (GDAL_GCP*)CPLMalloc(size * sizeof(GDAL_GCP));
}
void __FreeCArray_GDAL_GCP(GDAL_GCP* carray) {
if (carray)
CPLFree(carray);
}
#include "gdal_utils.h"
SWIGINTERN GDALInfoOptions *new_GDALInfoOptions(char **options){
return GDALInfoOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALInfoOptions(GDALInfoOptions *self){
GDALInfoOptionsFree( self );
}
SWIGINTERN GDALTranslateOptions *new_GDALTranslateOptions(char **options){
return GDALTranslateOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALTranslateOptions(GDALTranslateOptions *self){
GDALTranslateOptionsFree( self );
}
GDALDatasetShadow* wrapper_GDALTranslate( const char* dest,
GDALDatasetShadow* dataset,
GDALTranslateOptions* translateOptions,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( translateOptions == NULL )
{
bFreeOptions = true;
translateOptions = GDALTranslateOptionsNew(NULL, NULL);
}
GDALTranslateOptionsSetProgress(translateOptions, callback, callback_data);
}
GDALDatasetH hDSRet = GDALTranslate(dest, dataset, translateOptions, &usageError);
if( bFreeOptions )
GDALTranslateOptionsFree(translateOptions);
return hDSRet;
}
SWIGINTERN GDALWarpAppOptions *new_GDALWarpAppOptions(char **options){
return GDALWarpAppOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALWarpAppOptions(GDALWarpAppOptions *self){
GDALWarpAppOptionsFree( self );
}
int wrapper_GDALWarpDestDS( GDALDatasetShadow* dstDS,
int object_list_count, GDALDatasetShadow** poObjects,
GDALWarpAppOptions* warpAppOptions,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( warpAppOptions == NULL )
{
bFreeOptions = true;
warpAppOptions = GDALWarpAppOptionsNew(NULL, NULL);
}
GDALWarpAppOptionsSetProgress(warpAppOptions, callback, callback_data);
}
int bRet = (GDALWarp(NULL, dstDS, object_list_count, poObjects, warpAppOptions, &usageError) != NULL);
if( bFreeOptions )
GDALWarpAppOptionsFree(warpAppOptions);
return bRet;
}
GDALDatasetShadow* wrapper_GDALWarpDestName( const char* dest,
int object_list_count, GDALDatasetShadow** poObjects,
GDALWarpAppOptions* warpAppOptions,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( warpAppOptions == NULL )
{
bFreeOptions = true;
warpAppOptions = GDALWarpAppOptionsNew(NULL, NULL);
}
GDALWarpAppOptionsSetProgress(warpAppOptions, callback, callback_data);
}
GDALDatasetH hDSRet = GDALWarp(dest, NULL, object_list_count, poObjects, warpAppOptions, &usageError);
if( bFreeOptions )
GDALWarpAppOptionsFree(warpAppOptions);
return hDSRet;
}
SWIGINTERN GDALVectorTranslateOptions *new_GDALVectorTranslateOptions(char **options){
return GDALVectorTranslateOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALVectorTranslateOptions(GDALVectorTranslateOptions *self){
GDALVectorTranslateOptionsFree( self );
}
int wrapper_GDALVectorTranslateDestDS( GDALDatasetShadow* dstDS,
GDALDatasetShadow* srcDS,
GDALVectorTranslateOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALVectorTranslateOptionsNew(NULL, NULL);
}
GDALVectorTranslateOptionsSetProgress(options, callback, callback_data);
}
int bRet = (GDALVectorTranslate(NULL, dstDS, 1, &srcDS, options, &usageError) != NULL);
if( bFreeOptions )
GDALVectorTranslateOptionsFree(options);
return bRet;
}
GDALDatasetShadow* wrapper_GDALVectorTranslateDestName( const char* dest,
GDALDatasetShadow* srcDS,
GDALVectorTranslateOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALVectorTranslateOptionsNew(NULL, NULL);
}
GDALVectorTranslateOptionsSetProgress(options, callback, callback_data);
}
GDALDatasetH hDSRet = GDALVectorTranslate(dest, NULL, 1, &srcDS, options, &usageError);
if( bFreeOptions )
GDALVectorTranslateOptionsFree(options);
return hDSRet;
}
SWIGINTERN GDALDEMProcessingOptions *new_GDALDEMProcessingOptions(char **options){
return GDALDEMProcessingOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALDEMProcessingOptions(GDALDEMProcessingOptions *self){
GDALDEMProcessingOptionsFree( self );
}
GDALDatasetShadow* wrapper_GDALDEMProcessing( const char* dest,
GDALDatasetShadow* dataset,
const char* pszProcessing,
const char* pszColorFilename,
GDALDEMProcessingOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALDEMProcessingOptionsNew(NULL, NULL);
}
GDALDEMProcessingOptionsSetProgress(options, callback, callback_data);
}
GDALDatasetH hDSRet = GDALDEMProcessing(dest, dataset, pszProcessing, pszColorFilename, options, &usageError);
if( bFreeOptions )
GDALDEMProcessingOptionsFree(options);
return hDSRet;
}
SWIGINTERN GDALNearblackOptions *new_GDALNearblackOptions(char **options){
return GDALNearblackOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALNearblackOptions(GDALNearblackOptions *self){
GDALNearblackOptionsFree( self );
}
int wrapper_GDALNearblackDestDS( GDALDatasetShadow* dstDS,
GDALDatasetShadow* srcDS,
GDALNearblackOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALNearblackOptionsNew(NULL, NULL);
}
GDALNearblackOptionsSetProgress(options, callback, callback_data);
}
int bRet = (GDALNearblack(NULL, dstDS, srcDS, options, &usageError) != NULL);
if( bFreeOptions )
GDALNearblackOptionsFree(options);
return bRet;
}
GDALDatasetShadow* wrapper_GDALNearblackDestName( const char* dest,
GDALDatasetShadow* srcDS,
GDALNearblackOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALNearblackOptionsNew(NULL, NULL);
}
GDALNearblackOptionsSetProgress(options, callback, callback_data);
}
GDALDatasetH hDSRet = GDALNearblack(dest, NULL, srcDS, options, &usageError);
if( bFreeOptions )
GDALNearblackOptionsFree(options);
return hDSRet;
}
SWIGINTERN GDALGridOptions *new_GDALGridOptions(char **options){
return GDALGridOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALGridOptions(GDALGridOptions *self){
GDALGridOptionsFree( self );
}
GDALDatasetShadow* wrapper_GDALGrid( const char* dest,
GDALDatasetShadow* dataset,
GDALGridOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALGridOptionsNew(NULL, NULL);
}
GDALGridOptionsSetProgress(options, callback, callback_data);
}
GDALDatasetH hDSRet = GDALGrid(dest, dataset, options, &usageError);
if( bFreeOptions )
GDALGridOptionsFree(options);
return hDSRet;
}
SWIGINTERN GDALRasterizeOptions *new_GDALRasterizeOptions(char **options){
return GDALRasterizeOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALRasterizeOptions(GDALRasterizeOptions *self){
GDALRasterizeOptionsFree( self );
}
int wrapper_GDALRasterizeDestDS( GDALDatasetShadow* dstDS,
GDALDatasetShadow* srcDS,
GDALRasterizeOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALRasterizeOptionsNew(NULL, NULL);
}
GDALRasterizeOptionsSetProgress(options, callback, callback_data);
}
int bRet = (GDALRasterize(NULL, dstDS, srcDS, options, &usageError) != NULL);
if( bFreeOptions )
GDALRasterizeOptionsFree(options);
return bRet;
}
GDALDatasetShadow* wrapper_GDALRasterizeDestName( const char* dest,
GDALDatasetShadow* srcDS,
GDALRasterizeOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALRasterizeOptionsNew(NULL, NULL);
}
GDALRasterizeOptionsSetProgress(options, callback, callback_data);
}
GDALDatasetH hDSRet = GDALRasterize(dest, NULL, srcDS, options, &usageError);
if( bFreeOptions )
GDALRasterizeOptionsFree(options);
return hDSRet;
}
SWIGINTERN GDALBuildVRTOptions *new_GDALBuildVRTOptions(char **options){
return GDALBuildVRTOptionsNew(options, NULL);
}
SWIGINTERN void delete_GDALBuildVRTOptions(GDALBuildVRTOptions *self){
GDALBuildVRTOptionsFree( self );
}
GDALDatasetShadow* wrapper_GDALBuildVRT_objects( const char* dest,
int object_list_count, GDALDatasetShadow** poObjects,
GDALBuildVRTOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALBuildVRTOptionsNew(NULL, NULL);
}
GDALBuildVRTOptionsSetProgress(options, callback, callback_data);
}
GDALDatasetH hDSRet = GDALBuildVRT(dest, object_list_count, poObjects, NULL, options, &usageError);
if( bFreeOptions )
GDALBuildVRTOptionsFree(options);
return hDSRet;
}
GDALDatasetShadow* wrapper_GDALBuildVRT_names( const char* dest,
char ** source_filenames,
GDALBuildVRTOptions* options,
GDALProgressFunc callback=NULL,
void* callback_data=NULL)
{
int usageError; /* ignored */
bool bFreeOptions = false;
if( callback )
{
if( options == NULL )
{
bFreeOptions = true;
options = GDALBuildVRTOptionsNew(NULL, NULL);
}
GDALBuildVRTOptionsSetProgress(options, callback, callback_data);
}
GDALDatasetH hDSRet = GDALBuildVRT(dest, CSLCount(source_filenames), NULL, source_filenames, options, &usageError);
if( bFreeOptions )
GDALBuildVRTOptionsFree(options);
return hDSRet;
}
#ifdef __cplusplus
extern "C" {
#endif
SWIGEXPORT void SWIGSTDCALL CSharp_UseExceptions() {
UseExceptions();
}
SWIGEXPORT void SWIGSTDCALL CSharp_DontUseExceptions() {
DontUseExceptions();
}
SWIGEXPORT void SWIGSTDCALL CSharp_StringListDestroy(void * jarg1) {
void *arg1 = (void *) 0 ;
arg1 = (void *)jarg1;
{
CPLErrorReset();
StringListDestroy(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_Debug(char * jarg1, char * jarg2) {
char *arg1 = (char *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
Debug((char const *)arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_SetErrorHandler(char * jarg1) {
int jresult ;
char *arg1 = (char *) NULL ;
CPLErr result;
arg1 = (char *)jarg1;
{
CPLErrorReset();
result = (CPLErr)SetErrorHandler((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_PushErrorHandler__SWIG_0(char * jarg1) {
int jresult ;
char *arg1 = (char *) NULL ;
CPLErr result;
arg1 = (char *)jarg1;
{
CPLErrorReset();
result = (CPLErr)PushErrorHandler((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Error(int jarg1, int jarg2, char * jarg3) {
CPLErr arg1 = (CPLErr) CE_Failure ;
int arg2 = (int) 0 ;
char *arg3 = (char *) "error" ;
arg1 = (CPLErr)jarg1;
arg2 = (int)jarg2;
arg3 = (char *)jarg3;
{
CPLErrorReset();
Error(arg1,arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GOA2GetAuthorizationURL(char * jarg1) {
char * jresult ;
char *arg1 = (char *) 0 ;
retStringAndCPLFree *result = 0 ;
arg1 = (char *)jarg1;
{
CPLErrorReset();
result = (retStringAndCPLFree *)GOA2GetAuthorizationURL((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GOA2GetRefreshToken(char * jarg1, char * jarg2) {
char * jresult ;
char *arg1 = (char *) 0 ;
char *arg2 = (char *) 0 ;
retStringAndCPLFree *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
result = (retStringAndCPLFree *)GOA2GetRefreshToken((char const *)arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GOA2GetAccessToken(char * jarg1, char * jarg2) {
char * jresult ;
char *arg1 = (char *) 0 ;
char *arg2 = (char *) 0 ;
retStringAndCPLFree *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
result = (retStringAndCPLFree *)GOA2GetAccessToken((char const *)arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_PushErrorHandler__SWIG_1(void * jarg1) {
CPLErrorHandler arg1 ;
arg1 = (CPLErrorHandler)jarg1;
{
CPLErrorReset();
CPLPushErrorHandler(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_PopErrorHandler() {
{
CPLErrorReset();
CPLPopErrorHandler();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_ErrorReset() {
{
CPLErrorReset();
CPLErrorReset();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_EscapeString(int jarg1, char * jarg2, int jarg3) {
char * jresult ;
int arg1 ;
char *arg2 = (char *) 0 ;
int arg3 ;
retStringAndCPLFree *result = 0 ;
arg1 = (int)jarg1;
arg2 = (char *)jarg2;
arg3 = (int)jarg3;
{
CPLErrorReset();
result = (retStringAndCPLFree *)EscapeString(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_GetLastErrorNo() {
int jresult ;
int result;
{
result = CPLGetLastErrorNo();
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_GetLastErrorType() {
int jresult ;
int result;
{
result = CPLGetLastErrorType();
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GetLastErrorMsg() {
char * jresult ;
char *result = 0 ;
{
result = (char*)CPLGetLastErrorMsg();
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_VSIGetLastErrorNo() {
int jresult ;
int result;
{
CPLErrorReset();
result = (int)VSIGetLastErrorNo();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_VSIGetLastErrorMsg() {
char * jresult ;
char *result = 0 ;
{
CPLErrorReset();
result = (char *)VSIGetLastErrorMsg();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_PushFinderLocation(char * jarg1) {
char *arg1 = (char *) 0 ;
arg1 = (char *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
CPLPushFinderLocation((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_PopFinderLocation() {
{
CPLErrorReset();
CPLPopFinderLocation();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_FinderClean() {
{
CPLErrorReset();
CPLFinderClean();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_FindFile(char * jarg1, char * jarg2) {
char * jresult ;
char *arg1 = (char *) 0 ;
char *arg2 = (char *) 0 ;
char *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char *)CPLFindFile((char const *)arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_ReadDir(char * jarg1, int jarg2) {
void * jresult ;
char *arg1 = (char *) 0 ;
int arg2 = (int) 0 ;
char **result = 0 ;
arg1 = (char *)jarg1;
arg2 = (int)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char **)wrapper_VSIReadDirEx((char const *)arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_ReadDirRecursive(char * jarg1) {
void * jresult ;
char *arg1 = (char *) 0 ;
char **result = 0 ;
arg1 = (char *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char **)VSIReadDirRecursive((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_SetConfigOption(char * jarg1, char * jarg2) {
char *arg1 = (char *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
CPLSetConfigOption((char const *)arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GetConfigOption(char * jarg1, char * jarg2) {
char * jresult ;
char *arg1 = (char *) 0 ;
char *arg2 = (char *) NULL ;
char *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char *)wrapper_CPLGetConfigOption((char const *)arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_CPLBinaryToHex(int jarg1, void * jarg2) {
char * jresult ;
int arg1 ;
GByte *arg2 = (GByte *) 0 ;
retStringAndCPLFree *result = 0 ;
arg1 = (int)jarg1;
arg2 = (GByte *)jarg2;
{
CPLErrorReset();
result = (retStringAndCPLFree *)CPLBinaryToHex(arg1,(GByte const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_CPLHexToBinary(char * jarg1, void * jarg2) {
void * jresult ;
char *arg1 = (char *) 0 ;
int *arg2 = (int *) 0 ;
GByte *result = 0 ;
arg1 = (char *)jarg1;
{
/* %typemap(in) (int *hasval) */
arg2 = (int *)jarg2;
}
{
CPLErrorReset();
result = (GByte *)CPLHexToBinary((char const *)arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_FileFromMemBuffer(char * jarg1, int jarg2, void * jarg3) {
char *arg1 = (char *) 0 ;
int arg2 ;
GByte *arg3 = (GByte *) 0 ;
arg1 = (char *)jarg1;
arg2 = (int)jarg2;
arg3 = (GByte *)jarg3;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
wrapper_VSIFileFromMemBuffer((char const *)arg1,arg2,(GByte const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Unlink(char * jarg1) {
int jresult ;
char *arg1 = (char *) 0 ;
VSI_RETVAL result;
arg1 = (char *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = VSIUnlink((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_HasThreadSupport() {
int jresult ;
int result;
{
CPLErrorReset();
result = (int)wrapper_HasThreadSupport();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Mkdir(char * jarg1, int jarg2) {
int jresult ;
char *arg1 = (char *) 0 ;
int arg2 ;
VSI_RETVAL result;
arg1 = (char *)jarg1;
arg2 = (int)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = VSIMkdir((char const *)arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Rmdir(char * jarg1) {
int jresult ;
char *arg1 = (char *) 0 ;
VSI_RETVAL result;
arg1 = (char *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = VSIRmdir((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Rename(char * jarg1, char * jarg2) {
int jresult ;
char *arg1 = (char *) 0 ;
char *arg2 = (char *) 0 ;
VSI_RETVAL result;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = VSIRename((char const *)arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_VSIFOpenL(char * jarg1, char * jarg2) {
void * jresult ;
char *arg1 = (char *) 0 ;
char *arg2 = (char *) 0 ;
VSILFILE *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (VSILFILE *)wrapper_VSIFOpenL((char const *)arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_VSIFOpenExL(char * jarg1, char * jarg2, int jarg3) {
void * jresult ;
char *arg1 = (char *) 0 ;
char *arg2 = (char *) 0 ;
int arg3 ;
VSILFILE *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char *)jarg2;
arg3 = (int)jarg3;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (VSILFILE *)wrapper_VSIFOpenExL((char const *)arg1,(char const *)arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_VSIFCloseL(void * jarg1) {
int jresult ;
VSILFILE *arg1 = (VSILFILE *) 0 ;
VSI_RETVAL result;
arg1 = (VSILFILE *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = VSIFCloseL(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_VSIFSeekL(void * jarg1, long jarg2, int jarg3) {
int jresult ;
VSILFILE *arg1 = (VSILFILE *) 0 ;
long arg2 ;
int arg3 ;
VSI_RETVAL result;
arg1 = (VSILFILE *)jarg1;
arg2 = (long)jarg2;
arg3 = (int)jarg3;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = VSIFSeekL(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT long SWIGSTDCALL CSharp_VSIFTellL(void * jarg1) {
long jresult ;
VSILFILE *arg1 = (VSILFILE *) 0 ;
long result;
arg1 = (VSILFILE *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (long)VSIFTellL(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_VSIFTruncateL(void * jarg1, long jarg2) {
int jresult ;
VSILFILE *arg1 = (VSILFILE *) 0 ;
long arg2 ;
VSI_RETVAL result;
arg1 = (VSILFILE *)jarg1;
arg2 = (long)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = VSIFTruncateL(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_VSIFWriteL(char * jarg1, int jarg2, int jarg3, void * jarg4) {
int jresult ;
char *arg1 = (char *) 0 ;
int arg2 ;
int arg3 ;
VSILFILE *arg4 = (VSILFILE *) 0 ;
int result;
arg1 = (char *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
arg4 = (VSILFILE *)jarg4;
{
if (!arg4) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)VSIFWriteL((char const *)arg1,arg2,arg3,arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_VSICurlClearCache() {
{
CPLErrorReset();
VSICurlClearCache();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_ParseCommandLine(char * jarg1) {
void * jresult ;
char *arg1 = (char *) 0 ;
char **result = 0 ;
arg1 = (char *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char **)CSLParseCommandLine((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_XMLNode_Type_get(void * jarg1) {
int jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
CPLXMLNodeType result;
arg1 = (CPLXMLNode *)jarg1;
result = (CPLXMLNodeType) ((arg1)->eType);
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_XMLNode_Value_get(void * jarg1) {
char * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
char *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
result = (char *) ((arg1)->pszValue);
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_XMLNode_Next_get(void * jarg1) {
void * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
result = (CPLXMLNode *) ((arg1)->psNext);
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_XMLNode_Child_get(void * jarg1) {
void * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
result = (CPLXMLNode *) ((arg1)->psChild);
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_XMLNode__SWIG_0(char * jarg1) {
void * jresult ;
char *arg1 = (char *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (char *)jarg1;
{
CPLErrorReset();
result = (CPLXMLNode *)new_CPLXMLNode__SWIG_0((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_XMLNode__SWIG_1(int jarg1, char * jarg2) {
void * jresult ;
CPLXMLNodeType arg1 ;
char *arg2 = (char *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (CPLXMLNodeType)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
result = (CPLXMLNode *)new_CPLXMLNode__SWIG_1(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_XMLNode(void * jarg1) {
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
arg1 = (CPLXMLNode *)jarg1;
{
CPLErrorReset();
delete_CPLXMLNode(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_XMLNode_SerializeXMLTree(void * jarg1) {
char * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
retStringAndCPLFree *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
{
CPLErrorReset();
result = (retStringAndCPLFree *)CPLXMLNode_SerializeXMLTree(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_XMLNode_toString(void * jarg1) {
char * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
retStringAndCPLFree *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
{
CPLErrorReset();
result = (retStringAndCPLFree *)CPLXMLNode_toString(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_XMLNode_SearchXMLNode(void * jarg1, char * jarg2) {
void * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
char *arg2 = (char *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
result = (CPLXMLNode *)CPLXMLNode_SearchXMLNode(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_XMLNode_GetXMLNode(void * jarg1, char * jarg2) {
void * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
char *arg2 = (char *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
result = (CPLXMLNode *)CPLXMLNode_GetXMLNode(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_XMLNode_GetXMLValue(void * jarg1, char * jarg2, char * jarg3) {
char * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) 0 ;
char *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
{
CPLErrorReset();
result = (char *)CPLXMLNode_GetXMLValue(arg1,(char const *)arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_XMLNode_AddXMLChild(void * jarg1, void * jarg2) {
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
CPLXMLNode *arg2 = (CPLXMLNode *) 0 ;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (CPLXMLNode *)jarg2;
{
CPLErrorReset();
CPLXMLNode_AddXMLChild(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_XMLNode_RemoveXMLChild(void * jarg1, void * jarg2) {
int jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
CPLXMLNode *arg2 = (CPLXMLNode *) 0 ;
int result;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (CPLXMLNode *)jarg2;
{
CPLErrorReset();
result = (int)CPLXMLNode_RemoveXMLChild(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_XMLNode_AddXMLSibling(void * jarg1, void * jarg2) {
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
CPLXMLNode *arg2 = (CPLXMLNode *) 0 ;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (CPLXMLNode *)jarg2;
{
CPLErrorReset();
CPLXMLNode_AddXMLSibling(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_XMLNode_CreateXMLElementAndValue(void * jarg1, char * jarg2, char * jarg3) {
void * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
{
CPLErrorReset();
result = (CPLXMLNode *)CPLXMLNode_CreateXMLElementAndValue(arg1,(char const *)arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_XMLNode_CloneXMLTree(void * jarg1, void * jarg2) {
void * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
CPLXMLNode *arg2 = (CPLXMLNode *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (CPLXMLNode *)jarg2;
{
CPLErrorReset();
result = (CPLXMLNode *)CPLXMLNode_CloneXMLTree(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_XMLNode_Clone(void * jarg1) {
void * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
{
CPLErrorReset();
result = (CPLXMLNode *)CPLXMLNode_Clone(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_XMLNode_SetXMLValue(void * jarg1, char * jarg2, char * jarg3) {
int jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) 0 ;
int result;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
{
CPLErrorReset();
result = (int)CPLXMLNode_SetXMLValue(arg1,(char const *)arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_XMLNode_StripXMLNamespace(void * jarg1, char * jarg2, int jarg3) {
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
char *arg2 = (char *) 0 ;
int arg3 ;
arg1 = (CPLXMLNode *)jarg1;
arg2 = (char *)jarg2;
arg3 = (int)jarg3;
{
CPLErrorReset();
CPLXMLNode_StripXMLNamespace(arg1,(char const *)arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_MajorObject_GetDescription(void * jarg1) {
char * jresult ;
GDALMajorObjectShadow *arg1 = (GDALMajorObjectShadow *) 0 ;
char *result = 0 ;
arg1 = (GDALMajorObjectShadow *)jarg1;
{
CPLErrorReset();
result = (char *)GDALMajorObjectShadow_GetDescription(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_MajorObject_SetDescription(void * jarg1, char * jarg2) {
GDALMajorObjectShadow *arg1 = (GDALMajorObjectShadow *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (GDALMajorObjectShadow *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDALMajorObjectShadow_SetDescription(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_MajorObject_GetMetadataDomainList(void * jarg1) {
void * jresult ;
GDALMajorObjectShadow *arg1 = (GDALMajorObjectShadow *) 0 ;
char **result = 0 ;
arg1 = (GDALMajorObjectShadow *)jarg1;
{
CPLErrorReset();
result = (char **)GDALMajorObjectShadow_GetMetadataDomainList(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_MajorObject_GetMetadata(void * jarg1, char * jarg2) {
void * jresult ;
GDALMajorObjectShadow *arg1 = (GDALMajorObjectShadow *) 0 ;
char *arg2 = (char *) "" ;
char **result = 0 ;
arg1 = (GDALMajorObjectShadow *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
result = (char **)GDALMajorObjectShadow_GetMetadata_List(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_MajorObject_SetMetadata__SWIG_0(void * jarg1, void * jarg2, char * jarg3) {
int jresult ;
GDALMajorObjectShadow *arg1 = (GDALMajorObjectShadow *) 0 ;
char **arg2 = (char **) 0 ;
char *arg3 = (char *) "" ;
CPLErr result;
arg1 = (GDALMajorObjectShadow *)jarg1;
arg2 = (char **)jarg2;
arg3 = (char *)jarg3;
{
CPLErrorReset();
result = (CPLErr)GDALMajorObjectShadow_SetMetadata__SWIG_0(arg1,arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_MajorObject_SetMetadata__SWIG_1(void * jarg1, char * jarg2, char * jarg3) {
int jresult ;
GDALMajorObjectShadow *arg1 = (GDALMajorObjectShadow *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) "" ;
CPLErr result;
arg1 = (GDALMajorObjectShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
{
CPLErrorReset();
result = (CPLErr)GDALMajorObjectShadow_SetMetadata__SWIG_1(arg1,arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_MajorObject_GetMetadataItem(void * jarg1, char * jarg2, char * jarg3) {
char * jresult ;
GDALMajorObjectShadow *arg1 = (GDALMajorObjectShadow *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) "" ;
char *result = 0 ;
arg1 = (GDALMajorObjectShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char *)GDALMajorObjectShadow_GetMetadataItem(arg1,(char const *)arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_MajorObject_SetMetadataItem(void * jarg1, char * jarg2, char * jarg3, char * jarg4) {
int jresult ;
GDALMajorObjectShadow *arg1 = (GDALMajorObjectShadow *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) 0 ;
char *arg4 = (char *) "" ;
CPLErr result;
arg1 = (GDALMajorObjectShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
arg4 = (char *)jarg4;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (CPLErr)GDALMajorObjectShadow_SetMetadataItem(arg1,(char const *)arg2,(char const *)arg3,(char const *)arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_Driver_ShortName_get(void * jarg1) {
char * jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
char *result = 0 ;
arg1 = (GDALDriverShadow *)jarg1;
{
CPLErrorReset();
result = (char *)GDALDriverShadow_ShortName_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_Driver_LongName_get(void * jarg1) {
char * jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
char *result = 0 ;
arg1 = (GDALDriverShadow *)jarg1;
{
CPLErrorReset();
result = (char *)GDALDriverShadow_LongName_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_Driver_HelpTopic_get(void * jarg1) {
char * jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
char *result = 0 ;
arg1 = (GDALDriverShadow *)jarg1;
{
CPLErrorReset();
result = (char *)GDALDriverShadow_HelpTopic_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Driver_Create(void * jarg1, char * jarg2, int jarg3, int jarg4, int jarg5, int jarg6, void * jarg7) {
void * jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
char *arg2 = (char *) 0 ;
int arg3 ;
int arg4 ;
int arg5 = (int) 1 ;
GDALDataType arg6 = (GDALDataType) GDT_Byte ;
char **arg7 = (char **) 0 ;
GDALDatasetShadow *result = 0 ;
arg1 = (GDALDriverShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (int)jarg3;
arg4 = (int)jarg4;
arg5 = (int)jarg5;
arg6 = (GDALDataType)jarg6;
arg7 = (char **)jarg7;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)GDALDriverShadow_Create(arg1,(char const *)arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Driver_CreateCopy(void * jarg1, char * jarg2, void * jarg3, int jarg4, void * jarg5, void * jarg6, void * jarg7) {
void * jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
char *arg2 = (char *) 0 ;
GDALDatasetShadow *arg3 = (GDALDatasetShadow *) 0 ;
int arg4 = (int) 1 ;
char **arg5 = (char **) 0 ;
GDALProgressFunc arg6 = (GDALProgressFunc) NULL ;
void *arg7 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (GDALDriverShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (GDALDatasetShadow *)jarg3;
arg4 = (int)jarg4;
arg5 = (char **)jarg5;
arg6 = (GDALProgressFunc)jarg6;
arg7 = (void *)jarg7;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)GDALDriverShadow_CreateCopy(arg1,(char const *)arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Driver_Delete(void * jarg1, char * jarg2) {
int jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
char *arg2 = (char *) 0 ;
CPLErr result;
arg1 = (GDALDriverShadow *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (CPLErr)GDALDriverShadow_Delete(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Driver_Rename(void * jarg1, char * jarg2, char * jarg3) {
int jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) 0 ;
CPLErr result;
arg1 = (GDALDriverShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (CPLErr)GDALDriverShadow_Rename(arg1,(char const *)arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Driver_CopyFiles(void * jarg1, char * jarg2, char * jarg3) {
int jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) 0 ;
CPLErr result;
arg1 = (GDALDriverShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (CPLErr)GDALDriverShadow_CopyFiles(arg1,(char const *)arg2,(char const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Driver_Register(void * jarg1) {
int jresult ;
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
int result;
arg1 = (GDALDriverShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALDriverShadow_Register(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Driver_Deregister(void * jarg1) {
GDALDriverShadow *arg1 = (GDALDriverShadow *) 0 ;
arg1 = (GDALDriverShadow *)jarg1;
{
CPLErrorReset();
GDALDriverShadow_Deregister(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_ColorEntry_c1_set(void * jarg1, short jarg2) {
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
short arg2 ;
arg1 = (GDALColorEntry *)jarg1;
arg2 = (short)jarg2;
if (arg1) (arg1)->c1 = arg2;
}
SWIGEXPORT short SWIGSTDCALL CSharp_ColorEntry_c1_get(void * jarg1) {
short jresult ;
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
short result;
arg1 = (GDALColorEntry *)jarg1;
result = (short) ((arg1)->c1);
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_ColorEntry_c2_set(void * jarg1, short jarg2) {
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
short arg2 ;
arg1 = (GDALColorEntry *)jarg1;
arg2 = (short)jarg2;
if (arg1) (arg1)->c2 = arg2;
}
SWIGEXPORT short SWIGSTDCALL CSharp_ColorEntry_c2_get(void * jarg1) {
short jresult ;
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
short result;
arg1 = (GDALColorEntry *)jarg1;
result = (short) ((arg1)->c2);
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_ColorEntry_c3_set(void * jarg1, short jarg2) {
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
short arg2 ;
arg1 = (GDALColorEntry *)jarg1;
arg2 = (short)jarg2;
if (arg1) (arg1)->c3 = arg2;
}
SWIGEXPORT short SWIGSTDCALL CSharp_ColorEntry_c3_get(void * jarg1) {
short jresult ;
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
short result;
arg1 = (GDALColorEntry *)jarg1;
result = (short) ((arg1)->c3);
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_ColorEntry_c4_set(void * jarg1, short jarg2) {
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
short arg2 ;
arg1 = (GDALColorEntry *)jarg1;
arg2 = (short)jarg2;
if (arg1) (arg1)->c4 = arg2;
}
SWIGEXPORT short SWIGSTDCALL CSharp_ColorEntry_c4_get(void * jarg1) {
short jresult ;
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
short result;
arg1 = (GDALColorEntry *)jarg1;
result = (short) ((arg1)->c4);
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_ColorEntry() {
void * jresult ;
GDALColorEntry *result = 0 ;
{
CPLErrorReset();
result = (GDALColorEntry *)new GDALColorEntry();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_ColorEntry(void * jarg1) {
GDALColorEntry *arg1 = (GDALColorEntry *) 0 ;
arg1 = (GDALColorEntry *)jarg1;
{
CPLErrorReset();
delete arg1;
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_GCP_GCPX_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
GDAL_GCP_GCPX_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GCP_GCPX_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPX_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GCP_GCPY_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
GDAL_GCP_GCPY_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GCP_GCPY_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPY_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GCP_GCPZ_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
GDAL_GCP_GCPZ_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GCP_GCPZ_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPZ_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GCP_GCPPixel_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
GDAL_GCP_GCPPixel_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GCP_GCPPixel_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPPixel_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GCP_GCPLine_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
GDAL_GCP_GCPLine_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GCP_GCPLine_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPLine_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GCP_Info_set(void * jarg1, char * jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
/* char* Info memberin typemap */
GDAL_GCP_Info_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GCP_Info_get(void * jarg1) {
char * jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *result = 0 ;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
result = (char *)GDAL_GCP_Info_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GCP_Id_set(void * jarg1, char * jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
/* char* Info memberin typemap */
GDAL_GCP_Id_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GCP_Id_get(void * jarg1) {
char * jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *result = 0 ;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
result = (char *)GDAL_GCP_Id_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GCP(double jarg1, double jarg2, double jarg3, double jarg4, double jarg5, char * jarg6, char * jarg7) {
void * jresult ;
double arg1 = (double) 0.0 ;
double arg2 = (double) 0.0 ;
double arg3 = (double) 0.0 ;
double arg4 = (double) 0.0 ;
double arg5 = (double) 0.0 ;
char *arg6 = (char *) "" ;
char *arg7 = (char *) "" ;
GDAL_GCP *result = 0 ;
arg1 = (double)jarg1;
arg2 = (double)jarg2;
arg3 = (double)jarg3;
arg4 = (double)jarg4;
arg5 = (double)jarg5;
arg6 = (char *)jarg6;
arg7 = (char *)jarg7;
{
CPLErrorReset();
result = (GDAL_GCP *)new_GDAL_GCP(arg1,arg2,arg3,arg4,arg5,(char const *)arg6,(char const *)arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GCP(void * jarg1) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
delete_GDAL_GCP(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_GCPX_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPX_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_GCPX_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_GCPX_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_GCPY_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPY_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_GCPY_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_GCPY_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_GCPZ_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPZ_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_GCPZ_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_GCPZ_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_GCPPixel_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPPixel_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_GCPPixel_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_GCPPixel_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_GCPLine_get(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_GCPLine_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_GCPLine_set(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_GCPLine_set(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GDAL_GCP_Info_get(void * jarg1) {
char * jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *result = 0 ;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char *)GDAL_GCP_Info_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_Info_set(void * jarg1, char * jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_Info_set(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GDAL_GCP_Id_get(void * jarg1) {
char * jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *result = 0 ;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char *)GDAL_GCP_Id_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_Id_set(void * jarg1, char * jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_Id_set(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_get_GCPX(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_get_GCPX(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_set_GCPX(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_set_GCPX(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_get_GCPY(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_get_GCPY(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_set_GCPY(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_set_GCPY(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_get_GCPZ(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_get_GCPZ(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_set_GCPZ(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_set_GCPZ(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_get_GCPPixel(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_get_GCPPixel(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_set_GCPPixel(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_set_GCPPixel(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT double SWIGSTDCALL CSharp_GDAL_GCP_get_GCPLine(void * jarg1) {
double jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double result;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (double)GDAL_GCP_get_GCPLine(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_set_GCPLine(void * jarg1, double jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
double arg2 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (double)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_set_GCPLine(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GDAL_GCP_get_Info(void * jarg1) {
char * jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *result = 0 ;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char *)GDAL_GCP_get_Info(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_set_Info(void * jarg1, char * jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_set_Info(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GDAL_GCP_get_Id(void * jarg1) {
char * jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *result = 0 ;
arg1 = (GDAL_GCP *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (char *)GDAL_GCP_get_Id(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDAL_GCP_set_Id(void * jarg1, char * jarg2) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
char *arg2 = (char *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return ;
};
}
}
{
CPLErrorReset();
GDAL_GCP_set_Id(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_GCPsToGeoTransform(int jarg1, void * jarg2, void * jarg3, int jarg4) {
int jresult ;
int arg1 ;
GDAL_GCP *arg2 = (GDAL_GCP *) 0 ;
double *arg3 ;
int arg4 = (int) 1 ;
RETURN_NONE result;
arg1 = (int)jarg1;
arg2 = (GDAL_GCP *)jarg2;
{
/* %typemap(in) (double argout[ANY]) */
arg3 = (double *)jarg3;
}
arg4 = (int)jarg4;
{
CPLErrorReset();
result = (RETURN_NONE)GDALGCPsToGeoTransform(arg1,(GDAL_GCP const *)arg2,arg3,arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_AsyncReader(void * jarg1) {
GDALAsyncReaderShadow *arg1 = (GDALAsyncReaderShadow *) 0 ;
arg1 = (GDALAsyncReaderShadow *)jarg1;
{
CPLErrorReset();
delete_GDALAsyncReaderShadow(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_AsyncReader_GetNextUpdatedRegion(void * jarg1, double jarg2, int * jarg3, int * jarg4, int * jarg5, int * jarg6) {
int jresult ;
GDALAsyncReaderShadow *arg1 = (GDALAsyncReaderShadow *) 0 ;
double arg2 ;
int *arg3 = (int *) 0 ;
int *arg4 = (int *) 0 ;
int *arg5 = (int *) 0 ;
int *arg6 = (int *) 0 ;
GDALAsyncStatusType result;
arg1 = (GDALAsyncReaderShadow *)jarg1;
arg2 = (double)jarg2;
arg3 = (int *)jarg3;
arg4 = (int *)jarg4;
arg5 = (int *)jarg5;
arg6 = (int *)jarg6;
{
CPLErrorReset();
result = (GDALAsyncStatusType)GDALAsyncReaderShadow_GetNextUpdatedRegion(arg1,arg2,arg3,arg4,arg5,arg6);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_AsyncReader_LockBuffer(void * jarg1, double jarg2) {
int jresult ;
GDALAsyncReaderShadow *arg1 = (GDALAsyncReaderShadow *) 0 ;
double arg2 ;
int result;
arg1 = (GDALAsyncReaderShadow *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
result = (int)GDALAsyncReaderShadow_LockBuffer(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_AsyncReader_UnlockBuffer(void * jarg1) {
GDALAsyncReaderShadow *arg1 = (GDALAsyncReaderShadow *) 0 ;
arg1 = (GDALAsyncReaderShadow *)jarg1;
{
CPLErrorReset();
GDALAsyncReaderShadow_UnlockBuffer(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_RasterXSize_get(void * jarg1) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALDatasetShadow_RasterXSize_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_RasterYSize_get(void * jarg1) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALDatasetShadow_RasterYSize_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_RasterCount_get(void * jarg1) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALDatasetShadow_RasterCount_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_Dataset(void * jarg1) {
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
delete_GDALDatasetShadow(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Dataset_GetDriver(void * jarg1) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALDriverShadow *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (GDALDriverShadow *)GDALDatasetShadow_GetDriver(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Dataset_GetRasterBand(void * jarg1, int jarg2) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 ;
GDALRasterBandShadow *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (GDALRasterBandShadow *)GDALDatasetShadow_GetRasterBand(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_Dataset_GetProjection(void * jarg1) {
char * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
char *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (char *)GDALDatasetShadow_GetProjection(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_Dataset_GetProjectionRef(void * jarg1) {
char * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
char *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (char *)GDALDatasetShadow_GetProjectionRef(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_SetProjection(void * jarg1, char * jarg2) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
char *arg2 = (char *) 0 ;
CPLErr result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (char *)jarg2;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (CPLErr)GDALDatasetShadow_SetProjection(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Dataset_GetGeoTransform(void * jarg1, void * jarg2) {
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
double *arg2 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
/* %typemap(in) (double argout[ANY]) */
arg2 = (double *)jarg2;
}
{
CPLErrorReset();
GDALDatasetShadow_GetGeoTransform(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_SetGeoTransform(void * jarg1, void * jarg2) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
double *arg2 ;
CPLErr result;
arg1 = (GDALDatasetShadow *)jarg1;
{
/* %typemap(in) (double argin[ANY]) */
arg2 = (double *)jarg2;
}
{
CPLErrorReset();
result = (CPLErr)GDALDatasetShadow_SetGeoTransform(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_BuildOverviews(void * jarg1, char * jarg2, int jarg3, void * jarg4, void * jarg5, void * jarg6) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
char *arg2 = (char *) "NEAREST" ;
int arg3 = (int) 0 ;
int *arg4 = (int *) 0 ;
GDALProgressFunc arg5 = (GDALProgressFunc) NULL ;
void *arg6 = (void *) NULL ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (int)jarg3;
arg4 = (int *)jarg4;
arg5 = (GDALProgressFunc)jarg5;
arg6 = (void *)jarg6;
{
CPLErrorReset();
result = (int)GDALDatasetShadow_BuildOverviews(arg1,(char const *)arg2,arg3,arg4,arg5,arg6);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_GetGCPCount(void * jarg1) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALDatasetShadow_GetGCPCount(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_Dataset_GetGCPProjection(void * jarg1) {
char * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
char *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (char *)GDALDatasetShadow_GetGCPProjection(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Dataset_FlushCache(void * jarg1) {
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
GDALDatasetShadow_FlushCache(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_AddBand(void * jarg1, int jarg2, void * jarg3) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALDataType arg2 = (GDALDataType) GDT_Byte ;
char **arg3 = (char **) 0 ;
CPLErr result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDALDataType)jarg2;
arg3 = (char **)jarg3;
{
CPLErrorReset();
result = (CPLErr)GDALDatasetShadow_AddBand(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_CreateMaskBand(void * jarg1, int jarg2) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 ;
CPLErr result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALDatasetShadow_CreateMaskBand(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Dataset_GetFileList(void * jarg1) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
char **result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (char **)GDALDatasetShadow_GetFileList(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_StartTransaction(void * jarg1, int jarg2) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 = (int) FALSE ;
OGRErr result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (OGRErr)GDALDatasetShadow_StartTransaction(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
{
/* %typemap(out,fragment="OGRErrMessages",canthrow=1) OGRErr */
jresult = result;
}
{
/* %typemap(ret) OGRErr */
}
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_CommitTransaction(void * jarg1) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
OGRErr result;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (OGRErr)GDALDatasetShadow_CommitTransaction(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
{
/* %typemap(out,fragment="OGRErrMessages",canthrow=1) OGRErr */
jresult = result;
}
{
/* %typemap(ret) OGRErr */
}
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_RollbackTransaction(void * jarg1) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
OGRErr result;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (OGRErr)GDALDatasetShadow_RollbackTransaction(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
{
/* %typemap(out,fragment="OGRErrMessages",canthrow=1) OGRErr */
jresult = result;
}
{
/* %typemap(ret) OGRErr */
}
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_ReadRaster(void * jarg1, int jarg2, int jarg3, int jarg4, int jarg5, void * jarg6, int jarg7, int jarg8, int jarg9, int jarg10, void * jarg11, int jarg12, int jarg13, int jarg14) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 ;
int arg3 ;
int arg4 ;
int arg5 ;
void *arg6 = (void *) 0 ;
int arg7 ;
int arg8 ;
GDALDataType arg9 ;
int arg10 ;
int *arg11 = (int *) 0 ;
int arg12 ;
int arg13 ;
int arg14 ;
CPLErr result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
arg4 = (int)jarg4;
arg5 = (int)jarg5;
arg6 = (void *)jarg6;
arg7 = (int)jarg7;
arg8 = (int)jarg8;
arg9 = (GDALDataType)jarg9;
arg10 = (int)jarg10;
{
/* %typemap(in) (int argin[ANY]) */
arg11 = (int *)jarg11;
}
arg12 = (int)jarg12;
arg13 = (int)jarg13;
arg14 = (int)jarg14;
{
CPLErrorReset();
result = (CPLErr)GDALDatasetShadow_ReadRaster(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12,arg13,arg14);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset_WriteRaster(void * jarg1, int jarg2, int jarg3, int jarg4, int jarg5, void * jarg6, int jarg7, int jarg8, int jarg9, int jarg10, void * jarg11, int jarg12, int jarg13, int jarg14) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 ;
int arg3 ;
int arg4 ;
int arg5 ;
void *arg6 = (void *) 0 ;
int arg7 ;
int arg8 ;
GDALDataType arg9 ;
int arg10 ;
int *arg11 = (int *) 0 ;
int arg12 ;
int arg13 ;
int arg14 ;
CPLErr result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
arg4 = (int)jarg4;
arg5 = (int)jarg5;
arg6 = (void *)jarg6;
arg7 = (int)jarg7;
arg8 = (int)jarg8;
arg9 = (GDALDataType)jarg9;
arg10 = (int)jarg10;
{
/* %typemap(in) (int argin[ANY]) */
arg11 = (int *)jarg11;
}
arg12 = (int)jarg12;
arg13 = (int)jarg13;
arg14 = (int)jarg14;
{
CPLErrorReset();
result = (CPLErr)GDALDatasetShadow_WriteRaster(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12,arg13,arg14);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Dataset___GetGCPs(void * jarg1) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDAL_GCP *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
{
CPLErrorReset();
result = (GDAL_GCP *)GDALDatasetShadow___GetGCPs(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Dataset___SetGCPs(void * jarg1, int jarg2, void * jarg3, char * jarg4) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 ;
GDAL_GCP *arg3 = (GDAL_GCP *) 0 ;
char *arg4 = (char *) 0 ;
CPLErr result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDAL_GCP *)jarg3;
arg4 = (char *)jarg4;
{
CPLErrorReset();
result = (CPLErr)GDALDatasetShadow___SetGCPs(arg1,arg2,(GDAL_GCP const *)arg3,(char const *)arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Dataset___WriteCArrayItem_GDAL_GCP(void * jarg1, void * jarg2, int jarg3, void * jarg4) {
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDAL_GCP *arg2 = (GDAL_GCP *) 0 ;
int arg3 ;
GDAL_GCP *arg4 = (GDAL_GCP *) 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDAL_GCP *)jarg2;
arg3 = (int)jarg3;
arg4 = (GDAL_GCP *)jarg4;
{
CPLErrorReset();
GDALDatasetShadow___WriteCArrayItem_GDAL_GCP(arg1,arg2,arg3,arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Dataset___ReadCArrayItem_GDAL_GCP(void * jarg1, void * jarg2, int jarg3) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDAL_GCP *arg2 = (GDAL_GCP *) 0 ;
int arg3 ;
GDAL_GCP *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDAL_GCP *)jarg2;
arg3 = (int)jarg3;
{
CPLErrorReset();
result = (GDAL_GCP *)GDALDatasetShadow___ReadCArrayItem_GDAL_GCP(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Dataset___AllocCArray_GDAL_GCP(void * jarg1, int jarg2) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 ;
GDAL_GCP *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (GDAL_GCP *)GDALDatasetShadow___AllocCArray_GDAL_GCP(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Dataset___FreeCArray_GDAL_GCP(void * jarg1, void * jarg2) {
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDAL_GCP *arg2 = (GDAL_GCP *) 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDAL_GCP *)jarg2;
{
CPLErrorReset();
GDALDatasetShadow___FreeCArray_GDAL_GCP(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_XSize_get(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_XSize_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_YSize_get(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_YSize_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_DataType_get(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALDataType result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (GDALDataType)GDALRasterBandShadow_DataType_get(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Band_GetDataset(void * jarg1) {
void * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALDatasetShadow *result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (GDALDatasetShadow *)GDALRasterBandShadow_GetDataset(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_GetBand(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_GetBand(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_GetBlockSize(void * jarg1, int * jarg2, int * jarg3) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int *arg2 = (int *) 0 ;
int *arg3 = (int *) 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (int *)jarg2;
arg3 = (int *)jarg3;
{
CPLErrorReset();
GDALRasterBandShadow_GetBlockSize(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_GetColorInterpretation(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALColorInterp result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (GDALColorInterp)GDALRasterBandShadow_GetColorInterpretation(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_GetRasterColorInterpretation(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALColorInterp result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (GDALColorInterp)GDALRasterBandShadow_GetRasterColorInterpretation(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetColorInterpretation(void * jarg1, int jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALColorInterp arg2 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALColorInterp)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetColorInterpretation(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetRasterColorInterpretation(void * jarg1, int jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALColorInterp arg2 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALColorInterp)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetRasterColorInterpretation(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_GetNoDataValue(void * jarg1, void * jarg2, void * jarg3) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double *arg2 = (double *) 0 ;
int *arg3 = (int *) 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
/* %typemap(in) (double *val) */
arg2 = (double *)jarg2;
}
{
/* %typemap(in) (int *hasval) */
arg3 = (int *)jarg3;
}
{
CPLErrorReset();
GDALRasterBandShadow_GetNoDataValue(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetNoDataValue(void * jarg1, double jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double arg2 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetNoDataValue(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_DeleteNoDataValue(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_DeleteNoDataValue(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_Band_GetUnitType(void * jarg1) {
char * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
char *result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (char *)GDALRasterBandShadow_GetUnitType(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetUnitType(void * jarg1, char * jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
char *arg2 = (char *) 0 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (char *)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetUnitType(arg1,(char const *)arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Band_GetRasterCategoryNames(void * jarg1) {
void * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
char **result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (char **)GDALRasterBandShadow_GetRasterCategoryNames(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetRasterCategoryNames(void * jarg1, void * jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
char **arg2 = (char **) 0 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (char **)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetRasterCategoryNames(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_GetMinimum(void * jarg1, void * jarg2, void * jarg3) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double *arg2 = (double *) 0 ;
int *arg3 = (int *) 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
/* %typemap(in) (double *val) */
arg2 = (double *)jarg2;
}
{
/* %typemap(in) (int *hasval) */
arg3 = (int *)jarg3;
}
{
CPLErrorReset();
GDALRasterBandShadow_GetMinimum(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_GetMaximum(void * jarg1, void * jarg2, void * jarg3) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double *arg2 = (double *) 0 ;
int *arg3 = (int *) 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
/* %typemap(in) (double *val) */
arg2 = (double *)jarg2;
}
{
/* %typemap(in) (int *hasval) */
arg3 = (int *)jarg3;
}
{
CPLErrorReset();
GDALRasterBandShadow_GetMaximum(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_GetOffset(void * jarg1, void * jarg2, void * jarg3) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double *arg2 = (double *) 0 ;
int *arg3 = (int *) 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
/* %typemap(in) (double *val) */
arg2 = (double *)jarg2;
}
{
/* %typemap(in) (int *hasval) */
arg3 = (int *)jarg3;
}
{
CPLErrorReset();
GDALRasterBandShadow_GetOffset(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_GetScale(void * jarg1, void * jarg2, void * jarg3) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double *arg2 = (double *) 0 ;
int *arg3 = (int *) 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
/* %typemap(in) (double *val) */
arg2 = (double *)jarg2;
}
{
/* %typemap(in) (int *hasval) */
arg3 = (int *)jarg3;
}
{
CPLErrorReset();
GDALRasterBandShadow_GetScale(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetOffset(void * jarg1, double jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double arg2 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetOffset(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetScale(void * jarg1, double jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double arg2 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetScale(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_GetStatistics(void * jarg1, int jarg2, int jarg3, double * jarg4, double * jarg5, double * jarg6, double * jarg7) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int arg2 ;
int arg3 ;
double *arg4 = (double *) 0 ;
double *arg5 = (double *) 0 ;
double *arg6 = (double *) 0 ;
double *arg7 = (double *) 0 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
{
/* %typemap(in) (double *val) */
arg4 = (double *)jarg4;
}
{
/* %typemap(in) (double *val) */
arg5 = (double *)jarg5;
}
{
/* %typemap(in) (double *val) */
arg6 = (double *)jarg6;
}
{
/* %typemap(in) (double *val) */
arg7 = (double *)jarg7;
}
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_GetStatistics(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_ComputeStatistics(void * jarg1, unsigned int jarg2, double * jarg3, double * jarg4, double * jarg5, double * jarg6, void * jarg7, void * jarg8) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
bool arg2 ;
double *arg3 = (double *) NULL ;
double *arg4 = (double *) NULL ;
double *arg5 = (double *) NULL ;
double *arg6 = (double *) NULL ;
GDALProgressFunc arg7 = (GDALProgressFunc) NULL ;
void *arg8 = (void *) NULL ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = jarg2 ? true : false;
{
/* %typemap(in) (double *val) */
arg3 = (double *)jarg3;
}
{
/* %typemap(in) (double *val) */
arg4 = (double *)jarg4;
}
{
/* %typemap(in) (double *val) */
arg5 = (double *)jarg5;
}
{
/* %typemap(in) (double *val) */
arg6 = (double *)jarg6;
}
arg7 = (GDALProgressFunc)jarg7;
arg8 = (void *)jarg8;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_ComputeStatistics(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetStatistics(void * jarg1, double jarg2, double jarg3, double jarg4, double jarg5) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double arg2 ;
double arg3 ;
double arg4 ;
double arg5 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (double)jarg2;
arg3 = (double)jarg3;
arg4 = (double)jarg4;
arg5 = (double)jarg5;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetStatistics(arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_GetOverviewCount(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_GetOverviewCount(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Band_GetOverview(void * jarg1, int jarg2) {
void * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int arg2 ;
GDALRasterBandShadow *result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (GDALRasterBandShadow *)GDALRasterBandShadow_GetOverview(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_Checksum(void * jarg1, int jarg2, int jarg3, void * jarg4, void * jarg5) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int arg2 = (int) 0 ;
int arg3 = (int) 0 ;
int *arg4 = (int *) 0 ;
int *arg5 = (int *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
{
/* %typemap(in) (type *optional_##int) */
arg4 = (int *)jarg4;
}
{
/* %typemap(in) (type *optional_##int) */
arg5 = (int *)jarg5;
}
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_Checksum(arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_ComputeRasterMinMax(void * jarg1, void * jarg2, int jarg3) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double *arg2 ;
int arg3 = (int) 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
/* %typemap(in) (double argout[ANY]) */
arg2 = (double *)jarg2;
}
arg3 = (int)jarg3;
{
CPLErrorReset();
GDALRasterBandShadow_ComputeRasterMinMax(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_ComputeBandStats(void * jarg1, void * jarg2, int jarg3) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double *arg2 ;
int arg3 = (int) 1 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
/* %typemap(in) (double argout[ANY]) */
arg2 = (double *)jarg2;
}
arg3 = (int)jarg3;
{
CPLErrorReset();
GDALRasterBandShadow_ComputeBandStats(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_Fill(void * jarg1, double jarg2, double jarg3) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double arg2 ;
double arg3 = (double) 0.0 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (double)jarg2;
arg3 = (double)jarg3;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_Fill(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_Band_FlushCache(void * jarg1) {
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
GDALRasterBandShadow_FlushCache(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Band_GetRasterColorTable(void * jarg1) {
void * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALColorTableShadow *result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (GDALColorTableShadow *)GDALRasterBandShadow_GetRasterColorTable(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Band_GetColorTable(void * jarg1) {
void * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALColorTableShadow *result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (GDALColorTableShadow *)GDALRasterBandShadow_GetColorTable(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetRasterColorTable(void * jarg1, void * jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALColorTableShadow *arg2 = (GDALColorTableShadow *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALColorTableShadow *)jarg2;
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_SetRasterColorTable(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetColorTable(void * jarg1, void * jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALColorTableShadow *arg2 = (GDALColorTableShadow *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALColorTableShadow *)jarg2;
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_SetColorTable(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Band_GetDefaultRAT(void * jarg1) {
void * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterAttributeTableShadow *result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (GDALRasterAttributeTableShadow *)GDALRasterBandShadow_GetDefaultRAT(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetDefaultRAT(void * jarg1, void * jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterAttributeTableShadow *arg2 = (GDALRasterAttributeTableShadow *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterAttributeTableShadow *)jarg2;
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_SetDefaultRAT(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Band_GetMaskBand(void * jarg1) {
void * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (GDALRasterBandShadow *)GDALRasterBandShadow_GetMaskBand(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_GetMaskFlags(void * jarg1) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALRasterBandShadow_GetMaskFlags(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_CreateMaskBand(void * jarg1, int jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int arg2 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_CreateMaskBand(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_GetHistogram(void * jarg1, double jarg2, double jarg3, int jarg4, void * jarg5, int jarg6, int jarg7, void * jarg8, void * jarg9) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double arg2 = (double) -0.5 ;
double arg3 = (double) 255.5 ;
int arg4 = (int) 256 ;
int *arg5 = (int *) NULL ;
int arg6 = (int) 0 ;
int arg7 = (int) 1 ;
GDALProgressFunc arg8 = (GDALProgressFunc) NULL ;
void *arg9 = (void *) NULL ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (double)jarg2;
arg3 = (double)jarg3;
arg4 = (int)jarg4;
{
/* %typemap(in) (int inout[ANY]) */
arg5 = (int *)jarg5;
}
arg6 = (int)jarg6;
arg7 = (int)jarg7;
arg8 = (GDALProgressFunc)jarg8;
arg9 = (void *)jarg9;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_GetHistogram(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_GetDefaultHistogram(void * jarg1, double * jarg2, double * jarg3, void * jarg4, void * jarg5, int jarg6, void * jarg7, void * jarg8) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double *arg2 = (double *) NULL ;
double *arg3 = (double *) NULL ;
int *arg4 = (int *) NULL ;
int **arg5 = (int **) NULL ;
int arg6 = (int) 1 ;
GDALProgressFunc arg7 = (GDALProgressFunc) NULL ;
void *arg8 = (void *) NULL ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
/* %typemap(in) (double *val) */
arg2 = (double *)jarg2;
}
{
/* %typemap(in) (double *val) */
arg3 = (double *)jarg3;
}
{
/* %typemap(in) (int *hasval) */
arg4 = (int *)jarg4;
}
{
/* %typemap(in) (int **array_argout) */
arg5 = (int **)jarg5;
}
arg6 = (int)jarg6;
arg7 = (GDALProgressFunc)jarg7;
arg8 = (void *)jarg8;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_GetDefaultHistogram(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetDefaultHistogram(void * jarg1, double jarg2, double jarg3, int jarg4, void * jarg5) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double arg2 ;
double arg3 ;
int arg4 ;
int *arg5 = (int *) 0 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (double)jarg2;
arg3 = (double)jarg3;
arg4 = (int)jarg4;
{
/* %typemap(in) (int inout[ANY]) */
arg5 = (int *)jarg5;
}
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetDefaultHistogram(arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT unsigned int SWIGSTDCALL CSharp_Band_HasArbitraryOverviews(void * jarg1) {
unsigned int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
bool result;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (bool)GDALRasterBandShadow_HasArbitraryOverviews(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Band_GetCategoryNames(void * jarg1) {
void * jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
char **result = 0 ;
arg1 = (GDALRasterBandShadow *)jarg1;
{
CPLErrorReset();
result = (char **)GDALRasterBandShadow_GetCategoryNames(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_SetCategoryNames(void * jarg1, void * jarg2) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
char **arg2 = (char **) 0 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (char **)jarg2;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_SetCategoryNames(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_ReadRaster(void * jarg1, int jarg2, int jarg3, int jarg4, int jarg5, void * jarg6, int jarg7, int jarg8, int jarg9, int jarg10, int jarg11) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int arg2 ;
int arg3 ;
int arg4 ;
int arg5 ;
void *arg6 = (void *) 0 ;
int arg7 ;
int arg8 ;
GDALDataType arg9 ;
int arg10 ;
int arg11 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
arg4 = (int)jarg4;
arg5 = (int)jarg5;
arg6 = (void *)jarg6;
arg7 = (int)jarg7;
arg8 = (int)jarg8;
arg9 = (GDALDataType)jarg9;
arg10 = (int)jarg10;
arg11 = (int)jarg11;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_ReadRaster(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Band_WriteRaster(void * jarg1, int jarg2, int jarg3, int jarg4, int jarg5, void * jarg6, int jarg7, int jarg8, int jarg9, int jarg10, int jarg11) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int arg2 ;
int arg3 ;
int arg4 ;
int arg5 ;
void *arg6 = (void *) 0 ;
int arg7 ;
int arg8 ;
GDALDataType arg9 ;
int arg10 ;
int arg11 ;
CPLErr result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
arg4 = (int)jarg4;
arg5 = (int)jarg5;
arg6 = (void *)jarg6;
arg7 = (int)jarg7;
arg8 = (int)jarg8;
arg9 = (GDALDataType)jarg9;
arg10 = (int)jarg10;
arg11 = (int)jarg11;
{
CPLErrorReset();
result = (CPLErr)GDALRasterBandShadow_WriteRaster(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_ColorTable(int jarg1) {
void * jresult ;
GDALPaletteInterp arg1 = (GDALPaletteInterp) GPI_RGB ;
GDALColorTableShadow *result = 0 ;
arg1 = (GDALPaletteInterp)jarg1;
{
CPLErrorReset();
result = (GDALColorTableShadow *)new_GDALColorTableShadow(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_ColorTable(void * jarg1) {
GDALColorTableShadow *arg1 = (GDALColorTableShadow *) 0 ;
arg1 = (GDALColorTableShadow *)jarg1;
{
CPLErrorReset();
delete_GDALColorTableShadow(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_ColorTable_Clone(void * jarg1) {
void * jresult ;
GDALColorTableShadow *arg1 = (GDALColorTableShadow *) 0 ;
GDALColorTableShadow *result = 0 ;
arg1 = (GDALColorTableShadow *)jarg1;
{
CPLErrorReset();
result = (GDALColorTableShadow *)GDALColorTableShadow_Clone(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_ColorTable_GetPaletteInterpretation(void * jarg1) {
int jresult ;
GDALColorTableShadow *arg1 = (GDALColorTableShadow *) 0 ;
GDALPaletteInterp result;
arg1 = (GDALColorTableShadow *)jarg1;
{
CPLErrorReset();
result = (GDALPaletteInterp)GDALColorTableShadow_GetPaletteInterpretation(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_ColorTable_GetCount(void * jarg1) {
int jresult ;
GDALColorTableShadow *arg1 = (GDALColorTableShadow *) 0 ;
int result;
arg1 = (GDALColorTableShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALColorTableShadow_GetColorEntryCount(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_ColorTable_GetColorEntry(void * jarg1, int jarg2) {
void * jresult ;
GDALColorTableShadow *arg1 = (GDALColorTableShadow *) 0 ;
int arg2 ;
GDALColorEntry *result = 0 ;
arg1 = (GDALColorTableShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (GDALColorEntry *)GDALColorTableShadow_GetColorEntry(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_ColorTable_GetColorEntryAsRGB(void * jarg1, int jarg2, void * jarg3) {
int jresult ;
GDALColorTableShadow *arg1 = (GDALColorTableShadow *) 0 ;
int arg2 ;
GDALColorEntry *arg3 = (GDALColorEntry *) 0 ;
int result;
arg1 = (GDALColorTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDALColorEntry *)jarg3;
{
CPLErrorReset();
result = (int)GDALColorTableShadow_GetColorEntryAsRGB(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_ColorTable_SetColorEntry(void * jarg1, int jarg2, void * jarg3) {
GDALColorTableShadow *arg1 = (GDALColorTableShadow *) 0 ;
int arg2 ;
GDALColorEntry *arg3 = (GDALColorEntry *) 0 ;
arg1 = (GDALColorTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDALColorEntry *)jarg3;
{
CPLErrorReset();
GDALColorTableShadow_SetColorEntry(arg1,arg2,(GDALColorEntry const *)arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_ColorTable_CreateColorRamp(void * jarg1, int jarg2, void * jarg3, int jarg4, void * jarg5) {
GDALColorTableShadow *arg1 = (GDALColorTableShadow *) 0 ;
int arg2 ;
GDALColorEntry *arg3 = (GDALColorEntry *) 0 ;
int arg4 ;
GDALColorEntry *arg5 = (GDALColorEntry *) 0 ;
arg1 = (GDALColorTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDALColorEntry *)jarg3;
arg4 = (int)jarg4;
arg5 = (GDALColorEntry *)jarg5;
{
CPLErrorReset();
GDALColorTableShadow_CreateColorRamp(arg1,arg2,(GDALColorEntry const *)arg3,arg4,(GDALColorEntry const *)arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_RasterAttributeTable() {
void * jresult ;
GDALRasterAttributeTableShadow *result = 0 ;
{
CPLErrorReset();
result = (GDALRasterAttributeTableShadow *)new_GDALRasterAttributeTableShadow();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_RasterAttributeTable(void * jarg1) {
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
{
CPLErrorReset();
delete_GDALRasterAttributeTableShadow(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_RasterAttributeTable_Clone(void * jarg1) {
void * jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
GDALRasterAttributeTableShadow *result = 0 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
{
CPLErrorReset();
result = (GDALRasterAttributeTableShadow *)GDALRasterAttributeTableShadow_Clone(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_GetColumnCount(void * jarg1) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALRasterAttributeTableShadow_GetColumnCount(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_RasterAttributeTable_GetNameOfCol(void * jarg1, int jarg2) {
char * jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
char *result = 0 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (char *)GDALRasterAttributeTableShadow_GetNameOfCol(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_GetUsageOfCol(void * jarg1, int jarg2) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
GDALRATFieldUsage result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (GDALRATFieldUsage)GDALRasterAttributeTableShadow_GetUsageOfCol(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_GetTypeOfCol(void * jarg1, int jarg2) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
GDALRATFieldType result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (GDALRATFieldType)GDALRasterAttributeTableShadow_GetTypeOfCol(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_GetColOfUsage(void * jarg1, int jarg2) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
GDALRATFieldUsage arg2 ;
int result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (GDALRATFieldUsage)jarg2;
{
CPLErrorReset();
result = (int)GDALRasterAttributeTableShadow_GetColOfUsage(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_GetRowCount(void * jarg1) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALRasterAttributeTableShadow_GetRowCount(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_RasterAttributeTable_GetValueAsString(void * jarg1, int jarg2, int jarg3) {
char * jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
int arg3 ;
char *result = 0 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
{
CPLErrorReset();
result = (char *)GDALRasterAttributeTableShadow_GetValueAsString(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_GetValueAsInt(void * jarg1, int jarg2, int jarg3) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
int arg3 ;
int result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
{
CPLErrorReset();
result = (int)GDALRasterAttributeTableShadow_GetValueAsInt(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT double SWIGSTDCALL CSharp_RasterAttributeTable_GetValueAsDouble(void * jarg1, int jarg2, int jarg3) {
double jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
int arg3 ;
double result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
{
CPLErrorReset();
result = (double)GDALRasterAttributeTableShadow_GetValueAsDouble(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_RasterAttributeTable_SetValueAsString(void * jarg1, int jarg2, int jarg3, char * jarg4) {
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
int arg3 ;
char *arg4 = (char *) 0 ;
string str4 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
{
/* %typemap(in) (tostring argin) */
arg4 = (char *)jarg4;
}
{
CPLErrorReset();
GDALRasterAttributeTableShadow_SetValueAsString(arg1,arg2,arg3,(char const *)arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_RasterAttributeTable_SetValueAsInt(void * jarg1, int jarg2, int jarg3, int jarg4) {
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
int arg3 ;
int arg4 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
arg4 = (int)jarg4;
{
CPLErrorReset();
GDALRasterAttributeTableShadow_SetValueAsInt(arg1,arg2,arg3,arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_RasterAttributeTable_SetValueAsDouble(void * jarg1, int jarg2, int jarg3, double jarg4) {
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
int arg3 ;
double arg4 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
arg4 = (double)jarg4;
{
CPLErrorReset();
GDALRasterAttributeTableShadow_SetValueAsDouble(arg1,arg2,arg3,arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_RasterAttributeTable_SetRowCount(void * jarg1, int jarg2) {
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int arg2 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
GDALRasterAttributeTableShadow_SetRowCount(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_CreateColumn(void * jarg1, char * jarg2, int jarg3, int jarg4) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
char *arg2 = (char *) 0 ;
GDALRATFieldType arg3 ;
GDALRATFieldUsage arg4 ;
int result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (GDALRATFieldType)jarg3;
arg4 = (GDALRATFieldUsage)jarg4;
{
CPLErrorReset();
result = (int)GDALRasterAttributeTableShadow_CreateColumn(arg1,(char const *)arg2,arg3,arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT unsigned int SWIGSTDCALL CSharp_RasterAttributeTable_GetLinearBinning(void * jarg1, double * jarg2, double * jarg3) {
unsigned int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
double *arg2 = (double *) 0 ;
double *arg3 = (double *) 0 ;
bool result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
{
/* %typemap(in) (double *val) */
arg2 = (double *)jarg2;
}
{
/* %typemap(in) (double *val) */
arg3 = (double *)jarg3;
}
{
CPLErrorReset();
result = (bool)GDALRasterAttributeTableShadow_GetLinearBinning(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_SetLinearBinning(void * jarg1, double jarg2, double jarg3) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
double arg2 ;
double arg3 ;
int result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (double)jarg2;
arg3 = (double)jarg3;
{
CPLErrorReset();
result = (int)GDALRasterAttributeTableShadow_SetLinearBinning(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_GetRowOfValue(void * jarg1, double jarg2) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
double arg2 ;
int result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
arg2 = (double)jarg2;
{
CPLErrorReset();
result = (int)GDALRasterAttributeTableShadow_GetRowOfValue(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterAttributeTable_ChangesAreWrittenToFile(void * jarg1) {
int jresult ;
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
int result;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
{
CPLErrorReset();
result = (int)GDALRasterAttributeTableShadow_ChangesAreWrittenToFile(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_RasterAttributeTable_DumpReadable(void * jarg1) {
GDALRasterAttributeTableShadow *arg1 = (GDALRasterAttributeTableShadow *) 0 ;
arg1 = (GDALRasterAttributeTableShadow *)jarg1;
{
CPLErrorReset();
GDALRasterAttributeTableShadow_DumpReadable(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_ComputeMedianCutPCT(void * jarg1, void * jarg2, void * jarg3, int jarg4, void * jarg5, void * jarg6, void * jarg7) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg3 = (GDALRasterBandShadow *) 0 ;
int arg4 ;
GDALColorTableShadow *arg5 = (GDALColorTableShadow *) 0 ;
GDALProgressFunc arg6 = (GDALProgressFunc) NULL ;
void *arg7 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (GDALRasterBandShadow *)jarg3;
arg4 = (int)jarg4;
arg5 = (GDALColorTableShadow *)jarg5;
arg6 = (GDALProgressFunc)jarg6;
arg7 = (void *)jarg7;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg5) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)ComputeMedianCutPCT(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_DitherRGB2PCT(void * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5, void * jarg6, void * jarg7) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg3 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg4 = (GDALRasterBandShadow *) 0 ;
GDALColorTableShadow *arg5 = (GDALColorTableShadow *) 0 ;
GDALProgressFunc arg6 = (GDALProgressFunc) NULL ;
void *arg7 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (GDALRasterBandShadow *)jarg3;
arg4 = (GDALRasterBandShadow *)jarg4;
arg5 = (GDALColorTableShadow *)jarg5;
arg6 = (GDALProgressFunc)jarg6;
arg7 = (void *)jarg7;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg4) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg5) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)DitherRGB2PCT(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_ReprojectImage(void * jarg1, void * jarg2, char * jarg3, char * jarg4, int jarg5, double jarg6, double jarg7, void * jarg8, void * jarg9, void * jarg10) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
char *arg3 = (char *) NULL ;
char *arg4 = (char *) NULL ;
GDALResampleAlg arg5 = (GDALResampleAlg) GRA_NearestNeighbour ;
double arg6 = (double) 0.0 ;
double arg7 = (double) 0.0 ;
GDALProgressFunc arg8 = (GDALProgressFunc) NULL ;
void *arg9 = (void *) NULL ;
char **arg10 = (char **) NULL ;
CPLErr result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (char *)jarg3;
arg4 = (char *)jarg4;
arg5 = (GDALResampleAlg)jarg5;
arg6 = (double)jarg6;
arg7 = (double)jarg7;
arg8 = (GDALProgressFunc)jarg8;
arg9 = (void *)jarg9;
arg10 = (char **)jarg10;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (CPLErr)ReprojectImage(arg1,arg2,(char const *)arg3,(char const *)arg4,arg5,arg6,arg7,arg8,arg9,arg10);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_ComputeProximity(void * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
char **arg3 = (char **) NULL ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (char **)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)ComputeProximity(arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RasterizeLayer(void * jarg1, int jarg2, void * jarg3, void * jarg4, void * jarg5, void * jarg6, int jarg7, void * jarg8, void * jarg9, void * jarg10, void * jarg11) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 ;
int *arg3 = (int *) 0 ;
OGRLayerShadow *arg4 = (OGRLayerShadow *) 0 ;
void *arg5 = (void *) NULL ;
void *arg6 = (void *) NULL ;
int arg7 = (int) 0 ;
double *arg8 = (double *) NULL ;
char **arg9 = (char **) NULL ;
GDALProgressFunc arg10 = (GDALProgressFunc) NULL ;
void *arg11 = (void *) NULL ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
{
/* %typemap(in) (int inout[ANY]) */
arg3 = (int *)jarg3;
}
arg4 = (OGRLayerShadow *)jarg4;
arg5 = (void *)jarg5;
arg6 = (void *)jarg6;
arg7 = (int)jarg7;
{
/* %typemap(in) (double inout[ANY]) */
arg8 = (double *)jarg8;
}
arg9 = (char **)jarg9;
arg10 = (GDALProgressFunc)jarg10;
arg11 = (void *)jarg11;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg4) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)RasterizeLayer(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Polygonize(void * jarg1, void * jarg2, void * jarg3, int jarg4, void * jarg5, void * jarg6, void * jarg7) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
OGRLayerShadow *arg3 = (OGRLayerShadow *) 0 ;
int arg4 ;
char **arg5 = (char **) NULL ;
GDALProgressFunc arg6 = (GDALProgressFunc) NULL ;
void *arg7 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (OGRLayerShadow *)jarg3;
arg4 = (int)jarg4;
arg5 = (char **)jarg5;
arg6 = (GDALProgressFunc)jarg6;
arg7 = (void *)jarg7;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)Polygonize(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_FPolygonize(void * jarg1, void * jarg2, void * jarg3, int jarg4, void * jarg5, void * jarg6, void * jarg7) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
OGRLayerShadow *arg3 = (OGRLayerShadow *) 0 ;
int arg4 ;
char **arg5 = (char **) NULL ;
GDALProgressFunc arg6 = (GDALProgressFunc) NULL ;
void *arg7 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (OGRLayerShadow *)jarg3;
arg4 = (int)jarg4;
arg5 = (char **)jarg5;
arg6 = (GDALProgressFunc)jarg6;
arg7 = (void *)jarg7;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)FPolygonize(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_FillNodata(void * jarg1, void * jarg2, double jarg3, int jarg4, void * jarg5, void * jarg6, void * jarg7) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
double arg3 ;
int arg4 ;
char **arg5 = (char **) NULL ;
GDALProgressFunc arg6 = (GDALProgressFunc) NULL ;
void *arg7 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (double)jarg3;
arg4 = (int)jarg4;
arg5 = (char **)jarg5;
arg6 = (GDALProgressFunc)jarg6;
arg7 = (void *)jarg7;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)FillNodata(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_SieveFilter(void * jarg1, void * jarg2, void * jarg3, int jarg4, int jarg5, void * jarg6, void * jarg7, void * jarg8) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg3 = (GDALRasterBandShadow *) 0 ;
int arg4 ;
int arg5 = (int) 4 ;
char **arg6 = (char **) NULL ;
GDALProgressFunc arg7 = (GDALProgressFunc) NULL ;
void *arg8 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (GDALRasterBandShadow *)jarg3;
arg4 = (int)jarg4;
arg5 = (int)jarg5;
arg6 = (char **)jarg6;
arg7 = (GDALProgressFunc)jarg7;
arg8 = (void *)jarg8;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)SieveFilter(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RegenerateOverviews(void * jarg1, int jarg2, void * jarg3, char * jarg4, void * jarg5, void * jarg6) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
int arg2 ;
GDALRasterBandShadow **arg3 = (GDALRasterBandShadow **) 0 ;
char *arg4 = (char *) "average" ;
GDALProgressFunc arg5 = (GDALProgressFunc) NULL ;
void *arg6 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDALRasterBandShadow **)jarg3;
arg4 = (char *)jarg4;
arg5 = (GDALProgressFunc)jarg5;
arg6 = (void *)jarg6;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)RegenerateOverviews(arg1,arg2,arg3,(char const *)arg4,arg5,arg6);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_RegenerateOverview(void * jarg1, void * jarg2, char * jarg3, void * jarg4, void * jarg5) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
char *arg3 = (char *) "average" ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (char *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)RegenerateOverview(arg1,arg2,(char const *)arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_ContourGenerate(void * jarg1, double jarg2, double jarg3, int jarg4, void * jarg5, int jarg6, double jarg7, void * jarg8, int jarg9, int jarg10, void * jarg11, void * jarg12) {
int jresult ;
GDALRasterBandShadow *arg1 = (GDALRasterBandShadow *) 0 ;
double arg2 ;
double arg3 ;
int arg4 ;
double *arg5 = (double *) 0 ;
int arg6 ;
double arg7 ;
OGRLayerShadow *arg8 = (OGRLayerShadow *) 0 ;
int arg9 ;
int arg10 ;
GDALProgressFunc arg11 = (GDALProgressFunc) NULL ;
void *arg12 = (void *) NULL ;
int result;
arg1 = (GDALRasterBandShadow *)jarg1;
arg2 = (double)jarg2;
arg3 = (double)jarg3;
arg4 = (int)jarg4;
{
/* %typemap(in) (double inout[ANY]) */
arg5 = (double *)jarg5;
}
arg6 = (int)jarg6;
arg7 = (double)jarg7;
arg8 = (OGRLayerShadow *)jarg8;
arg9 = (int)jarg9;
arg10 = (int)jarg10;
arg11 = (GDALProgressFunc)jarg11;
arg12 = (void *)jarg12;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg8) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)ContourGenerate(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10,arg11,arg12);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_AutoCreateWarpedVRT(void * jarg1, char * jarg2, char * jarg3, int jarg4, double jarg5) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) 0 ;
GDALResampleAlg arg4 = (GDALResampleAlg) GRA_NearestNeighbour ;
double arg5 = (double) 0.0 ;
GDALDatasetShadow *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (char *)jarg2;
arg3 = (char *)jarg3;
arg4 = (GDALResampleAlg)jarg4;
arg5 = (double)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)AutoCreateWarpedVRT(arg1,(char const *)arg2,(char const *)arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_CreatePansharpenedVRT(char * jarg1, void * jarg2, int jarg3, void * jarg4) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
int arg3 ;
GDALRasterBandShadow **arg4 = (GDALRasterBandShadow **) 0 ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (int)jarg3;
arg4 = (GDALRasterBandShadow **)jarg4;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)CreatePansharpenedVRT((char const *)arg1,arg2,arg3,arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_Transformer(void * jarg1, void * jarg2, void * jarg3) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
char **arg3 = (char **) 0 ;
GDALTransformerInfoShadow *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (char **)jarg3;
{
CPLErrorReset();
result = (GDALTransformerInfoShadow *)new_GDALTransformerInfoShadow(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_Transformer(void * jarg1) {
GDALTransformerInfoShadow *arg1 = (GDALTransformerInfoShadow *) 0 ;
arg1 = (GDALTransformerInfoShadow *)jarg1;
{
CPLErrorReset();
delete_GDALTransformerInfoShadow(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_Transformer_TransformPoint__SWIG_0(void * jarg1, int jarg2, void * jarg3) {
int jresult ;
GDALTransformerInfoShadow *arg1 = (GDALTransformerInfoShadow *) 0 ;
int arg2 ;
double *arg3 ;
int result;
arg1 = (GDALTransformerInfoShadow *)jarg1;
arg2 = (int)jarg2;
{
/* %typemap(in) (double argin[ANY]) */
arg3 = (double *)jarg3;
}
{
CPLErrorReset();
result = (int)GDALTransformerInfoShadow_TransformPoint__SWIG_0(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Transformer_TransformPoint__SWIG_1(void * jarg1, void * jarg2, int jarg3, double jarg4, double jarg5, double jarg6) {
int jresult ;
GDALTransformerInfoShadow *arg1 = (GDALTransformerInfoShadow *) 0 ;
double *arg2 ;
int arg3 ;
double arg4 ;
double arg5 ;
double arg6 = (double) 0.0 ;
int result;
arg1 = (GDALTransformerInfoShadow *)jarg1;
{
/* %typemap(in) (double argout[ANY]) */
arg2 = (double *)jarg2;
}
arg3 = (int)jarg3;
arg4 = (double)jarg4;
arg5 = (double)jarg5;
arg6 = (double)jarg6;
{
CPLErrorReset();
result = (int)GDALTransformerInfoShadow_TransformPoint__SWIG_1(arg1,arg2,arg3,arg4,arg5,arg6);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Transformer_TransformPoints(void * jarg1, int jarg2, int jarg3, void * jarg4, void * jarg5, void * jarg6, void * jarg7) {
int jresult ;
GDALTransformerInfoShadow *arg1 = (GDALTransformerInfoShadow *) 0 ;
int arg2 ;
int arg3 ;
double *arg4 = (double *) 0 ;
double *arg5 = (double *) 0 ;
double *arg6 = (double *) 0 ;
int *arg7 = (int *) 0 ;
int result;
arg1 = (GDALTransformerInfoShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (int)jarg3;
{
/* %typemap(in) (double argout[ANY]) */
arg4 = (double *)jarg4;
}
{
/* %typemap(in) (double argout[ANY]) */
arg5 = (double *)jarg5;
}
{
/* %typemap(in) (double argout[ANY]) */
arg6 = (double *)jarg6;
}
{
/* %typemap(in) (double argout[ANY]) */
arg7 = (int *)jarg7;
}
{
CPLErrorReset();
result = (int)GDALTransformerInfoShadow_TransformPoints(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_Transformer_TransformGeolocations(void * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5, void * jarg6, void * jarg7) {
int jresult ;
GDALTransformerInfoShadow *arg1 = (GDALTransformerInfoShadow *) 0 ;
GDALRasterBandShadow *arg2 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg3 = (GDALRasterBandShadow *) 0 ;
GDALRasterBandShadow *arg4 = (GDALRasterBandShadow *) 0 ;
GDALProgressFunc arg5 = (GDALProgressFunc) NULL ;
void *arg6 = (void *) NULL ;
char **arg7 = (char **) NULL ;
int result;
arg1 = (GDALTransformerInfoShadow *)jarg1;
arg2 = (GDALRasterBandShadow *)jarg2;
arg3 = (GDALRasterBandShadow *)jarg3;
arg4 = (GDALRasterBandShadow *)jarg4;
arg5 = (GDALProgressFunc)jarg5;
arg6 = (void *)jarg6;
arg7 = (char **)jarg7;
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg4) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (int)GDALTransformerInfoShadow_TransformGeolocations(arg1,arg2,arg3,arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_ApplyVerticalShiftGrid(void * jarg1, void * jarg2, unsigned int jarg3, double jarg4, double jarg5, void * jarg6) {
void * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
bool arg3 = (bool) false ;
double arg4 = (double) 1.0 ;
double arg5 = (double) 1.0 ;
char **arg6 = (char **) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = jarg3 ? true : false;
arg4 = (double)jarg4;
arg5 = (double)jarg5;
arg6 = (char **)jarg6;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)ApplyVerticalShiftGrid(arg1,arg2,arg3,arg4,arg5,arg6);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_ApplyGeoTransform(void * jarg1, double jarg2, double jarg3, double * jarg4, double * jarg5) {
double *arg1 ;
double arg2 ;
double arg3 ;
double *arg4 = (double *) 0 ;
double *arg5 = (double *) 0 ;
{
/* %typemap(in) (double argin[ANY]) */
arg1 = (double *)jarg1;
}
arg2 = (double)jarg2;
arg3 = (double)jarg3;
{
/* %typemap(in) (double *val) */
arg4 = (double *)jarg4;
}
{
/* %typemap(in) (double *val) */
arg5 = (double *)jarg5;
}
{
CPLErrorReset();
GDALApplyGeoTransform(arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_InvGeoTransform(void * jarg1, void * jarg2) {
int jresult ;
double *arg1 ;
double *arg2 ;
RETURN_NONE result;
{
/* %typemap(in) (double argin[ANY]) */
arg1 = (double *)jarg1;
}
{
/* %typemap(in) (double argout[ANY]) */
arg2 = (double *)jarg2;
}
{
CPLErrorReset();
result = (RETURN_NONE)GDALInvGeoTransform(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_VersionInfo(char * jarg1) {
char * jresult ;
char *arg1 = (char *) "VERSION_NUM" ;
char *result = 0 ;
arg1 = (char *)jarg1;
{
CPLErrorReset();
result = (char *)GDALVersionInfo((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_AllRegister() {
{
CPLErrorReset();
GDALAllRegister();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void SWIGSTDCALL CSharp_GDALDestroyDriverManager() {
{
CPLErrorReset();
GDALDestroyDriverManager();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_GetCacheMax() {
int jresult ;
int result;
{
CPLErrorReset();
result = (int)wrapper_GDALGetCacheMax();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_GetCacheUsed() {
int jresult ;
int result;
{
CPLErrorReset();
result = (int)wrapper_GDALGetCacheUsed();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_SetCacheMax(int jarg1) {
int arg1 ;
arg1 = (int)jarg1;
{
CPLErrorReset();
wrapper_GDALSetCacheMax(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_GetDataTypeSize(int jarg1) {
int jresult ;
GDALDataType arg1 ;
int result;
arg1 = (GDALDataType)jarg1;
{
CPLErrorReset();
result = (int)GDALGetDataTypeSize(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_DataTypeIsComplex(int jarg1) {
int jresult ;
GDALDataType arg1 ;
int result;
arg1 = (GDALDataType)jarg1;
{
CPLErrorReset();
result = (int)GDALDataTypeIsComplex(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GetDataTypeName(int jarg1) {
char * jresult ;
GDALDataType arg1 ;
char *result = 0 ;
arg1 = (GDALDataType)jarg1;
{
CPLErrorReset();
result = (char *)GDALGetDataTypeName(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_GetDataTypeByName(char * jarg1) {
int jresult ;
char *arg1 = (char *) 0 ;
GDALDataType result;
arg1 = (char *)jarg1;
{
CPLErrorReset();
result = (GDALDataType)GDALGetDataTypeByName((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GetColorInterpretationName(int jarg1) {
char * jresult ;
GDALColorInterp arg1 ;
char *result = 0 ;
arg1 = (GDALColorInterp)jarg1;
{
CPLErrorReset();
result = (char *)GDALGetColorInterpretationName(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GetPaletteInterpretationName(int jarg1) {
char * jresult ;
GDALPaletteInterp arg1 ;
char *result = 0 ;
arg1 = (GDALPaletteInterp)jarg1;
{
CPLErrorReset();
result = (char *)GDALGetPaletteInterpretationName(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_DecToDMS(double jarg1, char * jarg2, int jarg3) {
char * jresult ;
double arg1 ;
char *arg2 = (char *) 0 ;
int arg3 = (int) 2 ;
char *result = 0 ;
arg1 = (double)jarg1;
arg2 = (char *)jarg2;
arg3 = (int)jarg3;
{
CPLErrorReset();
result = (char *)GDALDecToDMS(arg1,(char const *)arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = SWIG_csharp_string_callback((const char *)result);
return jresult;
}
SWIGEXPORT double SWIGSTDCALL CSharp_PackedDMSToDec(double jarg1) {
double jresult ;
double arg1 ;
double result;
arg1 = (double)jarg1;
{
CPLErrorReset();
result = (double)GDALPackedDMSToDec(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT double SWIGSTDCALL CSharp_DecToPackedDMS(double jarg1) {
double jresult ;
double arg1 ;
double result;
arg1 = (double)jarg1;
{
CPLErrorReset();
result = (double)GDALDecToPackedDMS(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_ParseXMLString(char * jarg1) {
void * jresult ;
char *arg1 = (char *) 0 ;
CPLXMLNode *result = 0 ;
arg1 = (char *)jarg1;
{
CPLErrorReset();
result = (CPLXMLNode *)CPLParseXMLString(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_SerializeXMLTree(void * jarg1) {
char * jresult ;
CPLXMLNode *arg1 = (CPLXMLNode *) 0 ;
retStringAndCPLFree *result = 0 ;
arg1 = (CPLXMLNode *)jarg1;
{
CPLErrorReset();
result = (retStringAndCPLFree *)CPLSerializeXMLTree(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GetJPEG2000StructureAsString(char * jarg1, void * jarg2) {
char * jresult ;
char *arg1 = (char *) 0 ;
char **arg2 = (char **) NULL ;
retStringAndCPLFree *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char **)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (retStringAndCPLFree *)GetJPEG2000StructureAsString((char const *)arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT int SWIGSTDCALL CSharp_GetDriverCount() {
int jresult ;
int result;
{
CPLErrorReset();
result = (int)GetDriverCount();
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_GetDriverByName(char * jarg1) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALDriverShadow *result = 0 ;
arg1 = (char *)jarg1;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDriverShadow *)GetDriverByName((char const *)arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_GetDriver(int jarg1) {
void * jresult ;
int arg1 ;
GDALDriverShadow *result = 0 ;
arg1 = (int)jarg1;
{
CPLErrorReset();
result = (GDALDriverShadow *)GetDriver(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_Open(char * jarg1, int jarg2) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALAccess arg2 = (GDALAccess) GA_ReadOnly ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALAccess)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)Open((char const *)arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_OpenEx(char * jarg1, unsigned int jarg2, void * jarg3, void * jarg4, void * jarg5) {
void * jresult ;
char *arg1 = (char *) 0 ;
unsigned int arg2 = (unsigned int) 0 ;
char **arg3 = (char **) NULL ;
char **arg4 = (char **) NULL ;
char **arg5 = (char **) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (unsigned int)jarg2;
arg3 = (char **)jarg3;
arg4 = (char **)jarg4;
arg5 = (char **)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)OpenEx((char const *)arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_OpenShared(char * jarg1, int jarg2) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALAccess arg2 = (GDALAccess) GA_ReadOnly ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALAccess)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)OpenShared((char const *)arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_IdentifyDriver(char * jarg1, void * jarg2) {
void * jresult ;
char *arg1 = (char *) 0 ;
char **arg2 = (char **) NULL ;
GDALDriverShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char **)jarg2;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDriverShadow *)IdentifyDriver((char const *)arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_IdentifyDriverEx(char * jarg1, unsigned int jarg2, void * jarg3, void * jarg4) {
void * jresult ;
char *arg1 = (char *) 0 ;
unsigned int arg2 = (unsigned int) 0 ;
char **arg3 = (char **) NULL ;
char **arg4 = (char **) NULL ;
GDALDriverShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (unsigned int)jarg2;
arg3 = (char **)jarg3;
arg4 = (char **)jarg4;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDriverShadow *)IdentifyDriverEx((char const *)arg1,arg2,arg3,arg4);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_GeneralCmdLineProcessor(void * jarg1, int jarg2) {
void * jresult ;
char **arg1 = (char **) 0 ;
int arg2 = (int) 0 ;
char **result = 0 ;
arg1 = (char **)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (char **)GeneralCmdLineProcessor(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp___WriteCArrayItem_GDAL_GCP(void * jarg1, int jarg2, void * jarg3) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
int arg2 ;
GDAL_GCP *arg3 = (GDAL_GCP *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDAL_GCP *)jarg3;
{
CPLErrorReset();
__WriteCArrayItem_GDAL_GCP(arg1,arg2,arg3);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp___ReadCArrayItem_GDAL_GCP(void * jarg1, int jarg2) {
void * jresult ;
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
int arg2 ;
GDAL_GCP *result = 0 ;
arg1 = (GDAL_GCP *)jarg1;
arg2 = (int)jarg2;
{
CPLErrorReset();
result = (GDAL_GCP *)__ReadCArrayItem_GDAL_GCP(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp___AllocCArray_GDAL_GCP(int jarg1) {
void * jresult ;
int arg1 ;
GDAL_GCP *result = 0 ;
arg1 = (int)jarg1;
{
CPLErrorReset();
result = (GDAL_GCP *)__AllocCArray_GDAL_GCP(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp___FreeCArray_GDAL_GCP(void * jarg1) {
GDAL_GCP *arg1 = (GDAL_GCP *) 0 ;
arg1 = (GDAL_GCP *)jarg1;
{
CPLErrorReset();
__FreeCArray_GDAL_GCP(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALInfoOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALInfoOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALInfoOptions *)new_GDALInfoOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALInfoOptions(void * jarg1) {
GDALInfoOptions *arg1 = (GDALInfoOptions *) 0 ;
arg1 = (GDALInfoOptions *)jarg1;
{
CPLErrorReset();
delete_GDALInfoOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT char * SWIGSTDCALL CSharp_GDALInfo(void * jarg1, void * jarg2) {
char * jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALInfoOptions *arg2 = (GDALInfoOptions *) 0 ;
retStringAndCPLFree *result = 0 ;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDALInfoOptions *)jarg2;
{
CPLErrorReset();
result = (retStringAndCPLFree *)GDALInfo(arg1,arg2);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
/* %typemap(out) (retStringAndCPLFree*) */
if(result)
{
jresult = SWIG_csharp_string_callback((const char *)result);
CPLFree(result);
}
else
{
jresult = NULL;
}
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALTranslateOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALTranslateOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALTranslateOptions *)new_GDALTranslateOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALTranslateOptions(void * jarg1) {
GDALTranslateOptions *arg1 = (GDALTranslateOptions *) 0 ;
arg1 = (GDALTranslateOptions *)jarg1;
{
CPLErrorReset();
delete_GDALTranslateOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALTranslate(char * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
GDALTranslateOptions *arg3 = (GDALTranslateOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (GDALTranslateOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALTranslate((char const *)arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALWarpAppOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALWarpAppOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALWarpAppOptions *)new_GDALWarpAppOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALWarpAppOptions(void * jarg1) {
GDALWarpAppOptions *arg1 = (GDALWarpAppOptions *) 0 ;
arg1 = (GDALWarpAppOptions *)jarg1;
{
CPLErrorReset();
delete_GDALWarpAppOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_wrapper_GDALWarpDestDS(void * jarg1, int jarg2, void * jarg3, void * jarg4, void * jarg5, void * jarg6) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
int arg2 ;
GDALDatasetShadow **arg3 = (GDALDatasetShadow **) 0 ;
GDALWarpAppOptions *arg4 = (GDALWarpAppOptions *) 0 ;
GDALProgressFunc arg5 = (GDALProgressFunc) NULL ;
void *arg6 = (void *) NULL ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDALDatasetShadow **)jarg3;
arg4 = (GDALWarpAppOptions *)jarg4;
arg5 = (GDALProgressFunc)jarg5;
arg6 = (void *)jarg6;
{
CPLErrorReset();
result = (int)wrapper_GDALWarpDestDS(arg1,arg2,arg3,arg4,arg5,arg6);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALWarpDestName(char * jarg1, int jarg2, void * jarg3, void * jarg4, void * jarg5, void * jarg6) {
void * jresult ;
char *arg1 = (char *) 0 ;
int arg2 ;
GDALDatasetShadow **arg3 = (GDALDatasetShadow **) 0 ;
GDALWarpAppOptions *arg4 = (GDALWarpAppOptions *) 0 ;
GDALProgressFunc arg5 = (GDALProgressFunc) NULL ;
void *arg6 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDALDatasetShadow **)jarg3;
arg4 = (GDALWarpAppOptions *)jarg4;
arg5 = (GDALProgressFunc)jarg5;
arg6 = (void *)jarg6;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALWarpDestName((char const *)arg1,arg2,arg3,arg4,arg5,arg6);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALVectorTranslateOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALVectorTranslateOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALVectorTranslateOptions *)new_GDALVectorTranslateOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALVectorTranslateOptions(void * jarg1) {
GDALVectorTranslateOptions *arg1 = (GDALVectorTranslateOptions *) 0 ;
arg1 = (GDALVectorTranslateOptions *)jarg1;
{
CPLErrorReset();
delete_GDALVectorTranslateOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_wrapper_GDALVectorTranslateDestDS(void * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
GDALVectorTranslateOptions *arg3 = (GDALVectorTranslateOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (GDALVectorTranslateOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
CPLErrorReset();
result = (int)wrapper_GDALVectorTranslateDestDS(arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALVectorTranslateDestName(char * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
GDALVectorTranslateOptions *arg3 = (GDALVectorTranslateOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (GDALVectorTranslateOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALVectorTranslateDestName((char const *)arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALDEMProcessingOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALDEMProcessingOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALDEMProcessingOptions *)new_GDALDEMProcessingOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALDEMProcessingOptions(void * jarg1) {
GDALDEMProcessingOptions *arg1 = (GDALDEMProcessingOptions *) 0 ;
arg1 = (GDALDEMProcessingOptions *)jarg1;
{
CPLErrorReset();
delete_GDALDEMProcessingOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALDEMProcessing(char * jarg1, void * jarg2, char * jarg3, char * jarg4, void * jarg5, void * jarg6, void * jarg7) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
char *arg3 = (char *) 0 ;
char *arg4 = (char *) 0 ;
GDALDEMProcessingOptions *arg5 = (GDALDEMProcessingOptions *) 0 ;
GDALProgressFunc arg6 = (GDALProgressFunc) NULL ;
void *arg7 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (char *)jarg3;
arg4 = (char *)jarg4;
arg5 = (GDALDEMProcessingOptions *)jarg5;
arg6 = (GDALProgressFunc)jarg6;
arg7 = (void *)jarg7;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg3) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALDEMProcessing((char const *)arg1,arg2,(char const *)arg3,(char const *)arg4,arg5,arg6,arg7);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALNearblackOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALNearblackOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALNearblackOptions *)new_GDALNearblackOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALNearblackOptions(void * jarg1) {
GDALNearblackOptions *arg1 = (GDALNearblackOptions *) 0 ;
arg1 = (GDALNearblackOptions *)jarg1;
{
CPLErrorReset();
delete_GDALNearblackOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_wrapper_GDALNearblackDestDS(void * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
GDALNearblackOptions *arg3 = (GDALNearblackOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (GDALNearblackOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
CPLErrorReset();
result = (int)wrapper_GDALNearblackDestDS(arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALNearblackDestName(char * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
GDALNearblackOptions *arg3 = (GDALNearblackOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (GDALNearblackOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALNearblackDestName((char const *)arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALGridOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALGridOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALGridOptions *)new_GDALGridOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALGridOptions(void * jarg1) {
GDALGridOptions *arg1 = (GDALGridOptions *) 0 ;
arg1 = (GDALGridOptions *)jarg1;
{
CPLErrorReset();
delete_GDALGridOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALGrid(char * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
GDALGridOptions *arg3 = (GDALGridOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (GDALGridOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
if (!arg2) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALGrid((char const *)arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALRasterizeOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALRasterizeOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALRasterizeOptions *)new_GDALRasterizeOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALRasterizeOptions(void * jarg1) {
GDALRasterizeOptions *arg1 = (GDALRasterizeOptions *) 0 ;
arg1 = (GDALRasterizeOptions *)jarg1;
{
CPLErrorReset();
delete_GDALRasterizeOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT int SWIGSTDCALL CSharp_wrapper_GDALRasterizeDestDS(void * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
int jresult ;
GDALDatasetShadow *arg1 = (GDALDatasetShadow *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
GDALRasterizeOptions *arg3 = (GDALRasterizeOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
int result;
arg1 = (GDALDatasetShadow *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (GDALRasterizeOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
CPLErrorReset();
result = (int)wrapper_GDALRasterizeDestDS(arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALRasterizeDestName(char * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
void * jresult ;
char *arg1 = (char *) 0 ;
GDALDatasetShadow *arg2 = (GDALDatasetShadow *) 0 ;
GDALRasterizeOptions *arg3 = (GDALRasterizeOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (GDALDatasetShadow *)jarg2;
arg3 = (GDALRasterizeOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALRasterizeDestName((char const *)arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_new_GDALBuildVRTOptions(void * jarg1) {
void * jresult ;
char **arg1 = (char **) 0 ;
GDALBuildVRTOptions *result = 0 ;
arg1 = (char **)jarg1;
{
CPLErrorReset();
result = (GDALBuildVRTOptions *)new_GDALBuildVRTOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void SWIGSTDCALL CSharp_delete_GDALBuildVRTOptions(void * jarg1) {
GDALBuildVRTOptions *arg1 = (GDALBuildVRTOptions *) 0 ;
arg1 = (GDALBuildVRTOptions *)jarg1;
{
CPLErrorReset();
delete_GDALBuildVRTOptions(arg1);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALBuildVRT_objects(char * jarg1, int jarg2, void * jarg3, void * jarg4, void * jarg5, void * jarg6) {
void * jresult ;
char *arg1 = (char *) 0 ;
int arg2 ;
GDALDatasetShadow **arg3 = (GDALDatasetShadow **) 0 ;
GDALBuildVRTOptions *arg4 = (GDALBuildVRTOptions *) 0 ;
GDALProgressFunc arg5 = (GDALProgressFunc) NULL ;
void *arg6 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (int)jarg2;
arg3 = (GDALDatasetShadow **)jarg3;
arg4 = (GDALBuildVRTOptions *)jarg4;
arg5 = (GDALProgressFunc)jarg5;
arg6 = (void *)jarg6;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALBuildVRT_objects((char const *)arg1,arg2,arg3,arg4,arg5,arg6);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_wrapper_GDALBuildVRT_names(char * jarg1, void * jarg2, void * jarg3, void * jarg4, void * jarg5) {
void * jresult ;
char *arg1 = (char *) 0 ;
char **arg2 = (char **) 0 ;
GDALBuildVRTOptions *arg3 = (GDALBuildVRTOptions *) 0 ;
GDALProgressFunc arg4 = (GDALProgressFunc) NULL ;
void *arg5 = (void *) NULL ;
GDALDatasetShadow *result = 0 ;
arg1 = (char *)jarg1;
arg2 = (char **)jarg2;
arg3 = (GDALBuildVRTOptions *)jarg3;
arg4 = (GDALProgressFunc)jarg4;
arg5 = (void *)jarg5;
{
if (!arg1) {
{
SWIG_CSharpException(SWIG_ValueError, "Received a NULL pointer."); return 0;
};
}
}
{
CPLErrorReset();
result = (GDALDatasetShadow *)wrapper_GDALBuildVRT_names((char const *)arg1,arg2,arg3,arg4,arg5);
CPLErr eclass = CPLGetLastErrorType();
if ( eclass == CE_Failure || eclass == CE_Fatal ) {
SWIG_CSharpException(SWIG_RuntimeError, CPLGetLastErrorMsg());
}
}
jresult = (void *)result;
return jresult;
}
SWIGEXPORT GDALMajorObjectShadow * SWIGSTDCALL CSharp_DriverUpcast(GDALDriverShadow *objectRef) {
return (GDALMajorObjectShadow *)objectRef;
}
SWIGEXPORT GDALMajorObjectShadow * SWIGSTDCALL CSharp_DatasetUpcast(GDALDatasetShadow *objectRef) {
return (GDALMajorObjectShadow *)objectRef;
}
SWIGEXPORT GDALMajorObjectShadow * SWIGSTDCALL CSharp_BandUpcast(GDALRasterBandShadow *objectRef) {
return (GDALMajorObjectShadow *)objectRef;
}
#ifdef __cplusplus
}
#endif
| 21.982251 | 256 | 0.611711 | VisualAwarenessTech |
d6ee72390b730292076a2f928e2b6f4074bbbc76 | 39,892 | cpp | C++ | webkit/WebCore/loader/appcache/ApplicationCacheStorage.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | 15 | 2016-01-05T12:43:41.000Z | 2022-03-15T10:34:47.000Z | webkit/WebCore/loader/appcache/ApplicationCacheStorage.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | null | null | null | webkit/WebCore/loader/appcache/ApplicationCacheStorage.cpp | s1rcheese/nintendo-3ds-internetbrowser-sourcecode | 3dd05f035e0a5fc9723300623e9b9b359be64e11 | [
"Unlicense"
] | 2 | 2020-11-30T18:36:01.000Z | 2021-02-05T23:20:24.000Z | /*
* Copyright (C) 2008, 2009 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ApplicationCacheStorage.h"
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
#include "ApplicationCache.h"
#include "ApplicationCacheHost.h"
#include "ApplicationCacheGroup.h"
#include "ApplicationCacheResource.h"
#include "CString.h"
#include "FileSystem.h"
#include "KURL.h"
#include "SQLiteStatement.h"
#include "SQLiteTransaction.h"
#include <wtf/StdLibExtras.h>
#include <wtf/StringExtras.h>
using namespace std;
namespace WebCore {
template <class T>
class StorageIDJournal {
public:
~StorageIDJournal()
{
size_t size = m_records.size();
for (size_t i = 0; i < size; ++i)
m_records[i].restore();
}
void add(T* resource, unsigned storageID)
{
m_records.append(Record(resource, storageID));
}
void commit()
{
m_records.clear();
}
private:
class Record {
public:
Record() : m_resource(0), m_storageID(0) { }
Record(T* resource, unsigned storageID) : m_resource(resource), m_storageID(storageID) { }
void restore()
{
m_resource->setStorageID(m_storageID);
}
private:
T* m_resource;
unsigned m_storageID;
};
Vector<Record> m_records;
};
static unsigned urlHostHash(const KURL& url)
{
unsigned hostStart = url.hostStart();
unsigned hostEnd = url.hostEnd();
return AlreadyHashed::avoidDeletedValue(StringImpl::computeHash(url.string().characters() + hostStart, hostEnd - hostStart));
}
ApplicationCacheGroup* ApplicationCacheStorage::loadCacheGroup(const KURL& manifestURL)
{
openDatabase(false);
if (!m_database.isOpen())
return 0;
SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL AND manifestURL=?");
if (statement.prepare() != SQLResultOk)
return 0;
statement.bindText(1, manifestURL);
int result = statement.step();
if (result == SQLResultDone)
return 0;
if (result != SQLResultRow) {
LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg());
return 0;
}
unsigned newestCacheStorageID = static_cast<unsigned>(statement.getColumnInt64(2));
RefPtr<ApplicationCache> cache = loadCache(newestCacheStorageID);
if (!cache)
return 0;
ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL);
group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
group->setNewestCache(cache.release());
return group;
}
ApplicationCacheGroup* ApplicationCacheStorage::findOrCreateCacheGroup(const KURL& manifestURL)
{
ASSERT(!manifestURL.hasFragmentIdentifier());
std::pair<CacheGroupMap::iterator, bool> result = m_cachesInMemory.add(manifestURL, 0);
if (!result.second) {
ASSERT(result.first->second);
return result.first->second;
}
// Look up the group in the database
ApplicationCacheGroup* group = loadCacheGroup(manifestURL);
// If the group was not found we need to create it
if (!group) {
group = new ApplicationCacheGroup(manifestURL);
m_cacheHostSet.add(urlHostHash(manifestURL));
}
result.first->second = group;
return group;
}
void ApplicationCacheStorage::loadManifestHostHashes()
{
static bool hasLoadedHashes = false;
if (hasLoadedHashes)
return;
// We set this flag to true before the database has been opened
// to avoid trying to open the database over and over if it doesn't exist.
hasLoadedHashes = true;
openDatabase(false);
if (!m_database.isOpen())
return;
// Fetch the host hashes.
SQLiteStatement statement(m_database, "SELECT manifestHostHash FROM CacheGroups");
if (statement.prepare() != SQLResultOk)
return;
int result;
while ((result = statement.step()) == SQLResultRow)
m_cacheHostSet.add(static_cast<unsigned>(statement.getColumnInt64(0)));
}
ApplicationCacheGroup* ApplicationCacheStorage::cacheGroupForURL(const KURL& url)
{
ASSERT(!url.hasFragmentIdentifier());
loadManifestHostHashes();
// Hash the host name and see if there's a manifest with the same host.
if (!m_cacheHostSet.contains(urlHostHash(url)))
return 0;
// Check if a cache already exists in memory.
CacheGroupMap::const_iterator end = m_cachesInMemory.end();
for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it) {
ApplicationCacheGroup* group = it->second;
ASSERT(!group->isObsolete());
if (!protocolHostAndPortAreEqual(url, group->manifestURL()))
continue;
if (ApplicationCache* cache = group->newestCache()) {
ApplicationCacheResource* resource = cache->resourceForURL(url);
if (!resource)
continue;
if (resource->type() & ApplicationCacheResource::Foreign)
continue;
return group;
}
}
if (!m_database.isOpen())
return 0;
// Check the database. Look for all cache groups with a newest cache.
SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL");
if (statement.prepare() != SQLResultOk)
return 0;
int result;
while ((result = statement.step()) == SQLResultRow) {
KURL manifestURL = KURL(ParsedURLString, statement.getColumnText(1));
if (m_cachesInMemory.contains(manifestURL))
continue;
if (!protocolHostAndPortAreEqual(url, manifestURL))
continue;
// We found a cache group that matches. Now check if the newest cache has a resource with
// a matching URL.
unsigned newestCacheID = static_cast<unsigned>(statement.getColumnInt64(2));
RefPtr<ApplicationCache> cache = loadCache(newestCacheID);
if (!cache)
continue;
ApplicationCacheResource* resource = cache->resourceForURL(url);
if (!resource)
continue;
if (resource->type() & ApplicationCacheResource::Foreign)
continue;
ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL);
group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
group->setNewestCache(cache.release());
m_cachesInMemory.set(group->manifestURL(), group);
return group;
}
if (result != SQLResultDone)
LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg());
return 0;
}
ApplicationCacheGroup* ApplicationCacheStorage::fallbackCacheGroupForURL(const KURL& url)
{
ASSERT(!url.hasFragmentIdentifier());
// Check if an appropriate cache already exists in memory.
CacheGroupMap::const_iterator end = m_cachesInMemory.end();
for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it) {
ApplicationCacheGroup* group = it->second;
ASSERT(!group->isObsolete());
if (ApplicationCache* cache = group->newestCache()) {
KURL fallbackURL;
if (!cache->urlMatchesFallbackNamespace(url, &fallbackURL))
continue;
if (cache->resourceForURL(fallbackURL)->type() & ApplicationCacheResource::Foreign)
continue;
return group;
}
}
if (!m_database.isOpen())
return 0;
// Check the database. Look for all cache groups with a newest cache.
SQLiteStatement statement(m_database, "SELECT id, manifestURL, newestCache FROM CacheGroups WHERE newestCache IS NOT NULL");
if (statement.prepare() != SQLResultOk)
return 0;
int result;
while ((result = statement.step()) == SQLResultRow) {
KURL manifestURL = KURL(ParsedURLString, statement.getColumnText(1));
if (m_cachesInMemory.contains(manifestURL))
continue;
// Fallback namespaces always have the same origin as manifest URL, so we can avoid loading caches that cannot match.
if (!protocolHostAndPortAreEqual(url, manifestURL))
continue;
// We found a cache group that matches. Now check if the newest cache has a resource with
// a matching fallback namespace.
unsigned newestCacheID = static_cast<unsigned>(statement.getColumnInt64(2));
RefPtr<ApplicationCache> cache = loadCache(newestCacheID);
KURL fallbackURL;
if (!cache->urlMatchesFallbackNamespace(url, &fallbackURL))
continue;
if (cache->resourceForURL(fallbackURL)->type() & ApplicationCacheResource::Foreign)
continue;
ApplicationCacheGroup* group = new ApplicationCacheGroup(manifestURL);
group->setStorageID(static_cast<unsigned>(statement.getColumnInt64(0)));
group->setNewestCache(cache.release());
m_cachesInMemory.set(group->manifestURL(), group);
return group;
}
if (result != SQLResultDone)
LOG_ERROR("Could not load cache group, error \"%s\"", m_database.lastErrorMsg());
return 0;
}
void ApplicationCacheStorage::cacheGroupDestroyed(ApplicationCacheGroup* group)
{
if (group->isObsolete()) {
ASSERT(!group->storageID());
ASSERT(m_cachesInMemory.get(group->manifestURL()) != group);
return;
}
ASSERT(m_cachesInMemory.get(group->manifestURL()) == group);
m_cachesInMemory.remove(group->manifestURL());
// If the cache group is half-created, we don't want it in the saved set (as it is not stored in database).
if (!group->storageID())
m_cacheHostSet.remove(urlHostHash(group->manifestURL()));
}
void ApplicationCacheStorage::cacheGroupMadeObsolete(ApplicationCacheGroup* group)
{
ASSERT(m_cachesInMemory.get(group->manifestURL()) == group);
ASSERT(m_cacheHostSet.contains(urlHostHash(group->manifestURL())));
if (ApplicationCache* newestCache = group->newestCache())
remove(newestCache);
m_cachesInMemory.remove(group->manifestURL());
m_cacheHostSet.remove(urlHostHash(group->manifestURL()));
}
void ApplicationCacheStorage::setCacheDirectory(const String& cacheDirectory)
{
ASSERT(m_cacheDirectory.isNull());
ASSERT(!cacheDirectory.isNull());
m_cacheDirectory = cacheDirectory;
}
const String& ApplicationCacheStorage::cacheDirectory() const
{
return m_cacheDirectory;
}
void ApplicationCacheStorage::setMaximumSize(int64_t size)
{
m_maximumSize = size;
}
int64_t ApplicationCacheStorage::maximumSize() const
{
return m_maximumSize;
}
bool ApplicationCacheStorage::isMaximumSizeReached() const
{
return m_isMaximumSizeReached;
}
int64_t ApplicationCacheStorage::spaceNeeded(int64_t cacheToSave)
{
int64_t spaceNeeded = 0;
long long fileSize = 0;
if (!getFileSize(m_cacheFile, fileSize))
return 0;
int64_t currentSize = fileSize;
// Determine the amount of free space we have available.
int64_t totalAvailableSize = 0;
if (m_maximumSize < currentSize) {
// The max size is smaller than the actual size of the app cache file.
// This can happen if the client previously imposed a larger max size
// value and the app cache file has already grown beyond the current
// max size value.
// The amount of free space is just the amount of free space inside
// the database file. Note that this is always 0 if SQLite is compiled
// with AUTO_VACUUM = 1.
totalAvailableSize = m_database.freeSpaceSize();
} else {
// The max size is the same or larger than the current size.
// The amount of free space available is the amount of free space
// inside the database file plus the amount we can grow until we hit
// the max size.
totalAvailableSize = (m_maximumSize - currentSize) + m_database.freeSpaceSize();
}
// The space needed to be freed in order to accomodate the failed cache is
// the size of the failed cache minus any already available free space.
spaceNeeded = cacheToSave - totalAvailableSize;
// The space needed value must be positive (or else the total already
// available free space would be larger than the size of the failed cache and
// saving of the cache should have never failed).
ASSERT(spaceNeeded);
return spaceNeeded;
}
bool ApplicationCacheStorage::executeSQLCommand(const String& sql)
{
ASSERT(m_database.isOpen());
bool result = m_database.executeCommand(sql);
if (!result)
LOG_ERROR("Application Cache Storage: failed to execute statement \"%s\" error \"%s\"",
sql.utf8().data(), m_database.lastErrorMsg());
return result;
}
static const int schemaVersion = 5;
void ApplicationCacheStorage::verifySchemaVersion()
{
int version = SQLiteStatement(m_database, "PRAGMA user_version").getColumnInt(0);
if (version == schemaVersion)
return;
m_database.clearAllTables();
// Update user version.
SQLiteTransaction setDatabaseVersion(m_database);
setDatabaseVersion.begin();
char userVersionSQL[32];
int unusedNumBytes = snprintf(userVersionSQL, sizeof(userVersionSQL), "PRAGMA user_version=%d", schemaVersion);
ASSERT_UNUSED(unusedNumBytes, static_cast<int>(sizeof(userVersionSQL)) >= unusedNumBytes);
SQLiteStatement statement(m_database, userVersionSQL);
if (statement.prepare() != SQLResultOk)
return;
executeStatement(statement);
setDatabaseVersion.commit();
}
void ApplicationCacheStorage::openDatabase(bool createIfDoesNotExist)
{
if (m_database.isOpen())
return;
// The cache directory should never be null, but if it for some weird reason is we bail out.
if (m_cacheDirectory.isNull())
return;
m_cacheFile = pathByAppendingComponent(m_cacheDirectory, "ApplicationCache.db");
if (!createIfDoesNotExist && !fileExists(m_cacheFile))
return;
makeAllDirectories(m_cacheDirectory);
m_database.open(m_cacheFile);
if (!m_database.isOpen())
return;
verifySchemaVersion();
// Create tables
executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheGroups (id INTEGER PRIMARY KEY AUTOINCREMENT, "
"manifestHostHash INTEGER NOT NULL ON CONFLICT FAIL, manifestURL TEXT UNIQUE ON CONFLICT FAIL, newestCache INTEGER)");
executeSQLCommand("CREATE TABLE IF NOT EXISTS Caches (id INTEGER PRIMARY KEY AUTOINCREMENT, cacheGroup INTEGER, size INTEGER)");
executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheWhitelistURLs (url TEXT NOT NULL ON CONFLICT FAIL, cache INTEGER NOT NULL ON CONFLICT FAIL)");
executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheAllowsAllNetworkRequests (wildcard INTEGER NOT NULL ON CONFLICT FAIL, cache INTEGER NOT NULL ON CONFLICT FAIL)");
executeSQLCommand("CREATE TABLE IF NOT EXISTS FallbackURLs (namespace TEXT NOT NULL ON CONFLICT FAIL, fallbackURL TEXT NOT NULL ON CONFLICT FAIL, "
"cache INTEGER NOT NULL ON CONFLICT FAIL)");
executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheEntries (cache INTEGER NOT NULL ON CONFLICT FAIL, type INTEGER, resource INTEGER NOT NULL)");
executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheResources (id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL ON CONFLICT FAIL, "
"statusCode INTEGER NOT NULL, responseURL TEXT NOT NULL, mimeType TEXT, textEncodingName TEXT, headers TEXT, data INTEGER NOT NULL ON CONFLICT FAIL)");
executeSQLCommand("CREATE TABLE IF NOT EXISTS CacheResourceData (id INTEGER PRIMARY KEY AUTOINCREMENT, data BLOB)");
// When a cache is deleted, all its entries and its whitelist should be deleted.
executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheDeleted AFTER DELETE ON Caches"
" FOR EACH ROW BEGIN"
" DELETE FROM CacheEntries WHERE cache = OLD.id;"
" DELETE FROM CacheWhitelistURLs WHERE cache = OLD.id;"
" DELETE FROM CacheAllowsAllNetworkRequests WHERE cache = OLD.id;"
" DELETE FROM FallbackURLs WHERE cache = OLD.id;"
" END");
// When a cache entry is deleted, its resource should also be deleted.
executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheEntryDeleted AFTER DELETE ON CacheEntries"
" FOR EACH ROW BEGIN"
" DELETE FROM CacheResources WHERE id = OLD.resource;"
" END");
// When a cache resource is deleted, its data blob should also be deleted.
executeSQLCommand("CREATE TRIGGER IF NOT EXISTS CacheResourceDeleted AFTER DELETE ON CacheResources"
" FOR EACH ROW BEGIN"
" DELETE FROM CacheResourceData WHERE id = OLD.data;"
" END");
}
bool ApplicationCacheStorage::executeStatement(SQLiteStatement& statement)
{
bool result = statement.executeCommand();
if (!result)
LOG_ERROR("Application Cache Storage: failed to execute statement \"%s\" error \"%s\"",
statement.query().utf8().data(), m_database.lastErrorMsg());
return result;
}
bool ApplicationCacheStorage::store(ApplicationCacheGroup* group, GroupStorageIDJournal* journal)
{
ASSERT(group->storageID() == 0);
ASSERT(journal);
SQLiteStatement statement(m_database, "INSERT INTO CacheGroups (manifestHostHash, manifestURL) VALUES (?, ?)");
if (statement.prepare() != SQLResultOk)
return false;
statement.bindInt64(1, urlHostHash(group->manifestURL()));
statement.bindText(2, group->manifestURL());
if (!executeStatement(statement))
return false;
group->setStorageID(static_cast<unsigned>(m_database.lastInsertRowID()));
journal->add(group, 0);
return true;
}
bool ApplicationCacheStorage::store(ApplicationCache* cache, ResourceStorageIDJournal* storageIDJournal)
{
ASSERT(cache->storageID() == 0);
ASSERT(cache->group()->storageID() != 0);
ASSERT(storageIDJournal);
SQLiteStatement statement(m_database, "INSERT INTO Caches (cacheGroup, size) VALUES (?, ?)");
if (statement.prepare() != SQLResultOk)
return false;
statement.bindInt64(1, cache->group()->storageID());
statement.bindInt64(2, cache->estimatedSizeInStorage());
if (!executeStatement(statement))
return false;
unsigned cacheStorageID = static_cast<unsigned>(m_database.lastInsertRowID());
// Store all resources
{
ApplicationCache::ResourceMap::const_iterator end = cache->end();
for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) {
unsigned oldStorageID = it->second->storageID();
if (!store(it->second.get(), cacheStorageID))
return false;
// Storing the resource succeeded. Log its old storageID in case
// it needs to be restored later.
storageIDJournal->add(it->second.get(), oldStorageID);
}
}
// Store the online whitelist
const Vector<KURL>& onlineWhitelist = cache->onlineWhitelist();
{
size_t whitelistSize = onlineWhitelist.size();
for (size_t i = 0; i < whitelistSize; ++i) {
SQLiteStatement statement(m_database, "INSERT INTO CacheWhitelistURLs (url, cache) VALUES (?, ?)");
statement.prepare();
statement.bindText(1, onlineWhitelist[i]);
statement.bindInt64(2, cacheStorageID);
if (!executeStatement(statement))
return false;
}
}
// Store online whitelist wildcard flag.
{
SQLiteStatement statement(m_database, "INSERT INTO CacheAllowsAllNetworkRequests (wildcard, cache) VALUES (?, ?)");
statement.prepare();
statement.bindInt64(1, cache->allowsAllNetworkRequests());
statement.bindInt64(2, cacheStorageID);
if (!executeStatement(statement))
return false;
}
// Store fallback URLs.
const FallbackURLVector& fallbackURLs = cache->fallbackURLs();
{
size_t fallbackCount = fallbackURLs.size();
for (size_t i = 0; i < fallbackCount; ++i) {
SQLiteStatement statement(m_database, "INSERT INTO FallbackURLs (namespace, fallbackURL, cache) VALUES (?, ?, ?)");
statement.prepare();
statement.bindText(1, fallbackURLs[i].first);
statement.bindText(2, fallbackURLs[i].second);
statement.bindInt64(3, cacheStorageID);
if (!executeStatement(statement))
return false;
}
}
cache->setStorageID(cacheStorageID);
return true;
}
bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, unsigned cacheStorageID)
{
ASSERT(cacheStorageID);
ASSERT(!resource->storageID());
openDatabase(true);
// First, insert the data
SQLiteStatement dataStatement(m_database, "INSERT INTO CacheResourceData (data) VALUES (?)");
if (dataStatement.prepare() != SQLResultOk)
return false;
if (resource->data()->size())
dataStatement.bindBlob(1, resource->data()->data(), resource->data()->size());
if (!dataStatement.executeCommand())
return false;
unsigned dataId = static_cast<unsigned>(m_database.lastInsertRowID());
// Then, insert the resource
// Serialize the headers
Vector<UChar> stringBuilder;
HTTPHeaderMap::const_iterator end = resource->response().httpHeaderFields().end();
for (HTTPHeaderMap::const_iterator it = resource->response().httpHeaderFields().begin(); it!= end; ++it) {
stringBuilder.append(it->first.characters(), it->first.length());
stringBuilder.append((UChar)':');
stringBuilder.append(it->second.characters(), it->second.length());
stringBuilder.append((UChar)'\n');
}
String headers = String::adopt(stringBuilder);
SQLiteStatement resourceStatement(m_database, "INSERT INTO CacheResources (url, statusCode, responseURL, headers, data, mimeType, textEncodingName) VALUES (?, ?, ?, ?, ?, ?, ?)");
if (resourceStatement.prepare() != SQLResultOk)
return false;
// The same ApplicationCacheResource are used in ApplicationCacheResource::size()
// to calculate the approximate size of an ApplicationCacheResource object. If
// you change the code below, please also change ApplicationCacheResource::size().
resourceStatement.bindText(1, resource->url());
resourceStatement.bindInt64(2, resource->response().httpStatusCode());
resourceStatement.bindText(3, resource->response().url());
resourceStatement.bindText(4, headers);
resourceStatement.bindInt64(5, dataId);
resourceStatement.bindText(6, resource->response().mimeType());
resourceStatement.bindText(7, resource->response().textEncodingName());
if (!executeStatement(resourceStatement))
return false;
unsigned resourceId = static_cast<unsigned>(m_database.lastInsertRowID());
// Finally, insert the cache entry
SQLiteStatement entryStatement(m_database, "INSERT INTO CacheEntries (cache, type, resource) VALUES (?, ?, ?)");
if (entryStatement.prepare() != SQLResultOk)
return false;
entryStatement.bindInt64(1, cacheStorageID);
entryStatement.bindInt64(2, resource->type());
entryStatement.bindInt64(3, resourceId);
if (!executeStatement(entryStatement))
return false;
resource->setStorageID(resourceId);
return true;
}
bool ApplicationCacheStorage::storeUpdatedType(ApplicationCacheResource* resource, ApplicationCache* cache)
{
ASSERT_UNUSED(cache, cache->storageID());
ASSERT(resource->storageID());
// First, insert the data
SQLiteStatement entryStatement(m_database, "UPDATE CacheEntries SET type=? WHERE resource=?");
if (entryStatement.prepare() != SQLResultOk)
return false;
entryStatement.bindInt64(1, resource->type());
entryStatement.bindInt64(2, resource->storageID());
return executeStatement(entryStatement);
}
bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, ApplicationCache* cache)
{
ASSERT(cache->storageID());
openDatabase(true);
m_isMaximumSizeReached = false;
m_database.setMaximumSize(m_maximumSize);
SQLiteTransaction storeResourceTransaction(m_database);
storeResourceTransaction.begin();
if (!store(resource, cache->storageID())) {
checkForMaxSizeReached();
return false;
}
// A resource was added to the cache. Update the total data size for the cache.
SQLiteStatement sizeUpdateStatement(m_database, "UPDATE Caches SET size=size+? WHERE id=?");
if (sizeUpdateStatement.prepare() != SQLResultOk)
return false;
sizeUpdateStatement.bindInt64(1, resource->estimatedSizeInStorage());
sizeUpdateStatement.bindInt64(2, cache->storageID());
if (!executeStatement(sizeUpdateStatement))
return false;
storeResourceTransaction.commit();
return true;
}
bool ApplicationCacheStorage::storeNewestCache(ApplicationCacheGroup* group)
{
openDatabase(true);
m_isMaximumSizeReached = false;
m_database.setMaximumSize(m_maximumSize);
SQLiteTransaction storeCacheTransaction(m_database);
storeCacheTransaction.begin();
GroupStorageIDJournal groupStorageIDJournal;
if (!group->storageID()) {
// Store the group
if (!store(group, &groupStorageIDJournal)) {
checkForMaxSizeReached();
return false;
}
}
ASSERT(group->newestCache());
ASSERT(!group->isObsolete());
ASSERT(!group->newestCache()->storageID());
// Log the storageID changes to the in-memory resource objects. The journal
// object will roll them back automatically in case a database operation
// fails and this method returns early.
ResourceStorageIDJournal resourceStorageIDJournal;
// Store the newest cache
if (!store(group->newestCache(), &resourceStorageIDJournal)) {
checkForMaxSizeReached();
return false;
}
// Update the newest cache in the group.
SQLiteStatement statement(m_database, "UPDATE CacheGroups SET newestCache=? WHERE id=?");
if (statement.prepare() != SQLResultOk)
return false;
statement.bindInt64(1, group->newestCache()->storageID());
statement.bindInt64(2, group->storageID());
if (!executeStatement(statement))
return false;
groupStorageIDJournal.commit();
resourceStorageIDJournal.commit();
storeCacheTransaction.commit();
return true;
}
static inline void parseHeader(const UChar* header, size_t headerLength, ResourceResponse& response)
{
int pos = find(header, headerLength, ':');
ASSERT(pos != -1);
AtomicString headerName = AtomicString(header, pos);
String headerValue = String(header + pos + 1, headerLength - pos - 1);
response.setHTTPHeaderField(headerName, headerValue);
}
static inline void parseHeaders(const String& headers, ResourceResponse& response)
{
int startPos = 0;
int endPos;
while ((endPos = headers.find('\n', startPos)) != -1) {
ASSERT(startPos != endPos);
parseHeader(headers.characters() + startPos, endPos - startPos, response);
startPos = endPos + 1;
}
if (startPos != static_cast<int>(headers.length()))
parseHeader(headers.characters(), headers.length(), response);
}
PassRefPtr<ApplicationCache> ApplicationCacheStorage::loadCache(unsigned storageID)
{
SQLiteStatement cacheStatement(m_database,
"SELECT url, type, mimeType, textEncodingName, headers, CacheResourceData.data FROM CacheEntries INNER JOIN CacheResources ON CacheEntries.resource=CacheResources.id "
"INNER JOIN CacheResourceData ON CacheResourceData.id=CacheResources.data WHERE CacheEntries.cache=?");
if (cacheStatement.prepare() != SQLResultOk) {
LOG_ERROR("Could not prepare cache statement, error \"%s\"", m_database.lastErrorMsg());
return 0;
}
cacheStatement.bindInt64(1, storageID);
RefPtr<ApplicationCache> cache = ApplicationCache::create();
int result;
while ((result = cacheStatement.step()) == SQLResultRow) {
KURL url(ParsedURLString, cacheStatement.getColumnText(0));
unsigned type = static_cast<unsigned>(cacheStatement.getColumnInt64(1));
Vector<char> blob;
cacheStatement.getColumnBlobAsVector(5, blob);
RefPtr<SharedBuffer> data = SharedBuffer::adoptVector(blob);
String mimeType = cacheStatement.getColumnText(2);
String textEncodingName = cacheStatement.getColumnText(3);
ResourceResponse response(url, mimeType, data->size(), textEncodingName, "");
String headers = cacheStatement.getColumnText(4);
parseHeaders(headers, response);
RefPtr<ApplicationCacheResource> resource = ApplicationCacheResource::create(url, response, type, data.release());
if (type & ApplicationCacheResource::Manifest)
cache->setManifestResource(resource.release());
else
cache->addResource(resource.release());
}
if (result != SQLResultDone)
LOG_ERROR("Could not load cache resources, error \"%s\"", m_database.lastErrorMsg());
// Load the online whitelist
SQLiteStatement whitelistStatement(m_database, "SELECT url FROM CacheWhitelistURLs WHERE cache=?");
if (whitelistStatement.prepare() != SQLResultOk)
return 0;
whitelistStatement.bindInt64(1, storageID);
Vector<KURL> whitelist;
while ((result = whitelistStatement.step()) == SQLResultRow)
whitelist.append(KURL(ParsedURLString, whitelistStatement.getColumnText(0)));
if (result != SQLResultDone)
LOG_ERROR("Could not load cache online whitelist, error \"%s\"", m_database.lastErrorMsg());
cache->setOnlineWhitelist(whitelist);
// Load online whitelist wildcard flag.
SQLiteStatement whitelistWildcardStatement(m_database, "SELECT wildcard FROM CacheAllowsAllNetworkRequests WHERE cache=?");
if (whitelistWildcardStatement.prepare() != SQLResultOk)
return 0;
whitelistWildcardStatement.bindInt64(1, storageID);
result = whitelistWildcardStatement.step();
if (result != SQLResultRow)
LOG_ERROR("Could not load cache online whitelist wildcard flag, error \"%s\"", m_database.lastErrorMsg());
cache->setAllowsAllNetworkRequests(whitelistWildcardStatement.getColumnInt64(0));
if (whitelistWildcardStatement.step() != SQLResultDone)
LOG_ERROR("Too many rows for online whitelist wildcard flag");
// Load fallback URLs.
SQLiteStatement fallbackStatement(m_database, "SELECT namespace, fallbackURL FROM FallbackURLs WHERE cache=?");
if (fallbackStatement.prepare() != SQLResultOk)
return 0;
fallbackStatement.bindInt64(1, storageID);
FallbackURLVector fallbackURLs;
while ((result = fallbackStatement.step()) == SQLResultRow)
fallbackURLs.append(make_pair(KURL(ParsedURLString, fallbackStatement.getColumnText(0)), KURL(ParsedURLString, fallbackStatement.getColumnText(1))));
if (result != SQLResultDone)
LOG_ERROR("Could not load fallback URLs, error \"%s\"", m_database.lastErrorMsg());
cache->setFallbackURLs(fallbackURLs);
cache->setStorageID(storageID);
return cache.release();
}
void ApplicationCacheStorage::remove(ApplicationCache* cache)
{
if (!cache->storageID())
return;
openDatabase(false);
if (!m_database.isOpen())
return;
ASSERT(cache->group());
ASSERT(cache->group()->storageID());
// All associated data will be deleted by database triggers.
SQLiteStatement statement(m_database, "DELETE FROM Caches WHERE id=?");
if (statement.prepare() != SQLResultOk)
return;
statement.bindInt64(1, cache->storageID());
executeStatement(statement);
cache->clearStorageID();
if (cache->group()->newestCache() == cache) {
// Currently, there are no triggers on the cache group, which is why the cache had to be removed separately above.
SQLiteStatement groupStatement(m_database, "DELETE FROM CacheGroups WHERE id=?");
if (groupStatement.prepare() != SQLResultOk)
return;
groupStatement.bindInt64(1, cache->group()->storageID());
executeStatement(groupStatement);
cache->group()->clearStorageID();
}
}
void ApplicationCacheStorage::empty()
{
openDatabase(false);
if (!m_database.isOpen())
return;
// Clear cache groups, caches and cache resources.
executeSQLCommand("DELETE FROM CacheGroups");
executeSQLCommand("DELETE FROM Caches");
// Clear the storage IDs for the caches in memory.
// The caches will still work, but cached resources will not be saved to disk
// until a cache update process has been initiated.
CacheGroupMap::const_iterator end = m_cachesInMemory.end();
for (CacheGroupMap::const_iterator it = m_cachesInMemory.begin(); it != end; ++it)
it->second->clearStorageID();
}
bool ApplicationCacheStorage::storeCopyOfCache(const String& cacheDirectory, ApplicationCacheHost* cacheHost)
{
ApplicationCache* cache = cacheHost->applicationCache();
if (!cache)
return true;
// Create a new cache.
RefPtr<ApplicationCache> cacheCopy = ApplicationCache::create();
cacheCopy->setOnlineWhitelist(cache->onlineWhitelist());
cacheCopy->setFallbackURLs(cache->fallbackURLs());
// Traverse the cache and add copies of all resources.
ApplicationCache::ResourceMap::const_iterator end = cache->end();
for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) {
ApplicationCacheResource* resource = it->second.get();
RefPtr<ApplicationCacheResource> resourceCopy = ApplicationCacheResource::create(resource->url(), resource->response(), resource->type(), resource->data());
cacheCopy->addResource(resourceCopy.release());
}
// Now create a new cache group.
OwnPtr<ApplicationCacheGroup> groupCopy(new ApplicationCacheGroup(cache->group()->manifestURL(), true));
groupCopy->setNewestCache(cacheCopy);
ApplicationCacheStorage copyStorage;
copyStorage.setCacheDirectory(cacheDirectory);
// Empty the cache in case something was there before.
copyStorage.empty();
return copyStorage.storeNewestCache(groupCopy.get());
}
bool ApplicationCacheStorage::manifestURLs(Vector<KURL>* urls)
{
ASSERT(urls);
openDatabase(false);
if (!m_database.isOpen())
return false;
SQLiteStatement selectURLs(m_database, "SELECT manifestURL FROM CacheGroups");
if (selectURLs.prepare() != SQLResultOk)
return false;
while (selectURLs.step() == SQLResultRow)
urls->append(KURL(ParsedURLString, selectURLs.getColumnText(0)));
return true;
}
bool ApplicationCacheStorage::cacheGroupSize(const String& manifestURL, int64_t* size)
{
ASSERT(size);
openDatabase(false);
if (!m_database.isOpen())
return false;
SQLiteStatement statement(m_database, "SELECT sum(Caches.size) FROM Caches INNER JOIN CacheGroups ON Caches.cacheGroup=CacheGroups.id WHERE CacheGroups.manifestURL=?");
if (statement.prepare() != SQLResultOk)
return false;
statement.bindText(1, manifestURL);
int result = statement.step();
if (result == SQLResultDone)
return false;
if (result != SQLResultRow) {
LOG_ERROR("Could not get the size of the cache group, error \"%s\"", m_database.lastErrorMsg());
return false;
}
*size = statement.getColumnInt64(0);
return true;
}
bool ApplicationCacheStorage::deleteCacheGroup(const String& manifestURL)
{
SQLiteTransaction deleteTransaction(m_database);
// Check to see if the group is in memory.
ApplicationCacheGroup* group = m_cachesInMemory.get(manifestURL);
if (group)
cacheGroupMadeObsolete(group);
else {
// The cache group is not in memory, so remove it from the disk.
openDatabase(false);
if (!m_database.isOpen())
return false;
SQLiteStatement idStatement(m_database, "SELECT id FROM CacheGroups WHERE manifestURL=?");
if (idStatement.prepare() != SQLResultOk)
return false;
idStatement.bindText(1, manifestURL);
int result = idStatement.step();
if (result == SQLResultDone)
return false;
if (result != SQLResultRow) {
LOG_ERROR("Could not load cache group id, error \"%s\"", m_database.lastErrorMsg());
return false;
}
int64_t groupId = idStatement.getColumnInt64(0);
SQLiteStatement cacheStatement(m_database, "DELETE FROM Caches WHERE cacheGroup=?");
if (cacheStatement.prepare() != SQLResultOk)
return false;
SQLiteStatement groupStatement(m_database, "DELETE FROM CacheGroups WHERE id=?");
if (groupStatement.prepare() != SQLResultOk)
return false;
cacheStatement.bindInt64(1, groupId);
executeStatement(cacheStatement);
groupStatement.bindInt64(1, groupId);
executeStatement(groupStatement);
}
deleteTransaction.commit();
return true;
}
void ApplicationCacheStorage::vacuumDatabaseFile()
{
openDatabase(false);
if (!m_database.isOpen())
return;
m_database.runVacuumCommand();
}
void ApplicationCacheStorage::checkForMaxSizeReached()
{
if (m_database.lastError() == SQLResultFull)
m_isMaximumSizeReached = true;
}
ApplicationCacheStorage::ApplicationCacheStorage()
: m_maximumSize(INT_MAX)
, m_isMaximumSizeReached(false)
{
}
ApplicationCacheStorage& cacheStorage()
{
DEFINE_STATIC_LOCAL(ApplicationCacheStorage, storage, ());
return storage;
}
} // namespace WebCore
#endif // ENABLE(OFFLINE_WEB_APPLICATIONS)
| 35.333924 | 202 | 0.678382 | s1rcheese |
d6f1e2628fa53a0efacbe63f0d9860ddb47dc44f | 36,248 | hpp | C++ | lisp/c++/tealang.hpp | Teaonly/tealang | a83e2feeb0331768a6c396930f4fcb10cccd6f85 | [
"MIT"
] | 2 | 2019-09-26T02:43:35.000Z | 2019-10-09T13:25:42.000Z | lisp/c++/tealang.hpp | Teaonly/tealang | a83e2feeb0331768a6c396930f4fcb10cccd6f85 | [
"MIT"
] | null | null | null | lisp/c++/tealang.hpp | Teaonly/tealang | a83e2feeb0331768a6c396930f4fcb10cccd6f85 | [
"MIT"
] | null | null | null | #pragma once
#include <assert.h>
#include <string>
#include <memory>
#include <list>
#include <vector>
#include <map>
#include <iterator>
#include <iostream>
#include <sstream>
namespace tea {
using namespace std;
struct _TeaExtern {};
typedef struct _TeaExtern TeaExtern;
struct TeaEnvironment;
struct TeaObject;
struct TeaResult;
typedef shared_ptr<TeaObject> tobject;
typedef shared_ptr<TeaEnvironment> tenv;
typedef TeaResult (*TeaFunc) (vector<tobject> &args, tenv &env);
struct TeaLambda {
vector<tobject> head;
tobject body;
shared_ptr<map<string, tobject>> closure;
TeaLambda() {
}
};
struct TeaObject {
enum TeaType {
T_NULL,
T_INT,
T_FLOAT,
T_BOOL,
T_PATTERN,
T_LIST,
T_MAP,
T_EXT,
T_SYMBOL,
T_LAMBDA,
T_FUNC,
};
const TeaType type;
// user values
int64_t v_int;
float v_float;
bool v_bool;
const string v_string;
const shared_ptr<vector<tobject>> v_list;
const shared_ptr<map<string, tobject>> v_map;
const shared_ptr<TeaExtern> v_ext;
// internal values
const shared_ptr<TeaLambda> v_lambda;
TeaFunc v_func;
TeaObject():type(T_NULL) {}
TeaObject(int64_t value):type(T_INT) {v_int = value;}
TeaObject(float value):type(T_FLOAT) {v_float = value;}
TeaObject(bool value):type(T_BOOL), v_bool(value) {}
TeaObject(const string& value):type(T_PATTERN), v_string(value) {}
TeaObject(shared_ptr<vector<tobject>> value):type(T_LIST), v_list(value) {}
TeaObject(shared_ptr<map<string, tobject>> value):type(T_MAP), v_map(value) {}
TeaObject(shared_ptr<TeaExtern> value):type(T_EXT), v_ext(value) {}
TeaObject(shared_ptr<TeaLambda> value):type(T_LAMBDA), v_lambda(value) {}
TeaObject(TeaFunc value):type(T_FUNC) {v_func = value;}
TeaObject(TeaType t, const string& symbol):type(T_SYMBOL), v_string(symbol) {
assert(t == T_SYMBOL);
}
string to_string() {
stringstream ss;
if (type == T_NULL) {
return "(nil)";
}
if (type == T_INT) {
ss << v_int;
}
if (type == T_FLOAT) {
ss << v_float;
}
if (type == T_BOOL) {
ss << v_bool;
}
if (type == T_PATTERN) {
ss << "@" << v_string;
}
if (type == T_EXT) {
ss << "(extern)";
}
if (type == T_LIST) {
ss << "(list with " << v_list->size() << " items)";
}
if (type == T_MAP) {
ss << "(map with " << v_map->size() << " items)";
}
if (type == T_SYMBOL) {
ss << v_string;
}
if (type == T_FUNC) {
ss << "(func)";
}
if (type == T_LAMBDA) {
ss << "(lambda)";
}
return ss.str();
}
static tobject build(const TeaObject& obj) {
return std::make_shared<TeaObject>(obj);
}
};
const auto tea_null = TeaObject::build(TeaObject());
const auto tea_true = TeaObject::build(TeaObject(true));
const auto tea_false = TeaObject::build(TeaObject(false));
struct TeaEnvironment {
shared_ptr<map<string, tobject>> global;
shared_ptr<map<string, tobject>> closure;
shared_ptr<map<string, tobject>> data;
// global enviroment
TeaEnvironment() {
data = make_shared<map<string, tobject>>();
}
// new env for lambda
TeaEnvironment(tenv& out_env, shared_ptr<map<string, tobject>> lambda_closue) {
if (out_env->is_global()) {
global = out_env->data;
} else {
global = out_env->global;
}
closure = lambda_closue;
data = make_shared<map<string, tobject>>();
}
bool is_global() {
if (global == nullptr) {
return true;
}
return false;
}
void set(const string& key, tobject obj) {
(*data)[key] = obj;
}
tobject get(const string& key) {
auto query = data->find(key);
if (query != data->end()) {
return query->second;
}
if (closure != nullptr) {
auto query = closure->find(key);
if (query != closure->end() ) {
return query->second;
}
}
if (global != nullptr) {
auto query = global->find(key);
if (query != global->end() ) {
return query->second;
}
}
return tea_null;
}
};
struct TeaResult {
vector<string> trace;;
tobject result;
bool is_error() {
if (trace.size() == 0) {
return false;
}
return true;
}
bool is_ok() {
return !is_error();
}
TeaResult(tobject obj) {
result = obj;
}
TeaResult(string err_message) {
trace.push_back(err_message);
}
TeaResult(TeaResult& r, string& err_message) {
trace = r.trace;
trace.push_back(err_message);
}
};
struct TeaLang {
private:
// main functions
static void init(shared_ptr<map<string, tobject>> data_) {
map<string, tobject>& data(*data_);
data["+"] = build_fobj(TeaLang::add);
data["-"] = build_fobj(TeaLang::sub);
data["*"] = build_fobj(TeaLang::mul);
data["/"] = build_fobj(TeaLang::div);
data["%"] = build_fobj(TeaLang::mod);
data["++"] = build_fobj(TeaLang::inc);
data["--"] = build_fobj(TeaLang::dec);
data[">"] = build_fobj(TeaLang::more);
data["<"] = build_fobj(TeaLang::less);
data[">="] = build_fobj(TeaLang::moreeq);
data["<="] = build_fobj(TeaLang::lesseq);
data["=="] = build_fobj(TeaLang::eqeq);
data["!"] = build_fobj(TeaLang::notnot);
data["size"] = build_fobj(TeaLang::size);
data["push"] = build_fobj(TeaLang::push);
data["pop"] = build_fobj(TeaLang::pop);
data["nth"] = build_fobj(TeaLang::nth);
data["set"] = build_fobj(TeaLang::set);
data["has"] = build_fobj(TeaLang::has);
data["rm"] = build_fobj(TeaLang::rm);
}
static tobject build_fobj(TeaFunc f) {
return TeaObject::build(f);
}
// math
static TeaResult add(vector<tobject> &args, tenv& env) {
if (args.size() == 0) {
return TeaResult("+ func synatax error, need more items");
}
if (args[0]->type == TeaObject::T_INT) {
int64_t sum = 0;
for (size_t i = 0; i < args.size(); i++) {
if ( args[i]->type != TeaObject::T_INT) {
return TeaResult("+ func synatax error, only support int/float");
}
sum += args[i]->v_int;
}
return TeaObject::build(sum);
}
if (args[0]->type == TeaObject::T_FLOAT) {
float sum = 0.0;
for (size_t i = 0; i < args.size(); i++) {
if ( args[i]->type != TeaObject::T_FLOAT) {
return TeaResult("+ func synatax error, only support int/float");
}
sum += args[i]->v_float;
}
return TeaObject::build(sum);
}
return TeaResult("+ func synatax error, only support int/float");
}
static TeaResult sub(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("- func synatax error, need two items");
}
if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) {
auto result = args[0]->v_int - args[1]->v_int;
return TeaObject::build(result);
}
if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) {
auto result = args[0]->v_float - args[1]->v_float;
return TeaObject::build(result);
}
return TeaResult("+ func synatax error, only support int/float");
}
static TeaResult mul(vector<tobject> &args, tenv& env) {
if (args.size() == 0) {
return TeaResult("* func synatax error, need more items");
}
if (args[0]->type == TeaObject::T_INT) {
int64_t result = 1;
for (size_t i = 0; i < args.size(); i++) {
if (args[i]->type != TeaObject::T_INT) {
return TeaResult("* func synatax error, only support int/float");
}
result *= args[i]->v_int;
}
return TeaObject::build(result);
}
if (args[0]->type == TeaObject::T_FLOAT) {
float result = 1.0;
for (size_t i = 0; i < args.size(); i++) {
if (args[i]->type != TeaObject::T_FLOAT) {
return TeaResult("* func synatax error, only support int/float");
}
result *= args[i]->v_float;
}
return TeaObject::build(result);
}
return TeaResult("* func synatax error, only support int/float");
}
static TeaResult div(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("/ func synatax error, need two items");
}
if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) {
auto result = args[0]->v_int / args[1]->v_int;
return TeaObject::build(result);
}
if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) {
auto result = args[0]->v_float / args[1]->v_float;
return TeaObject::build(result);
}
return TeaResult("/ func synatax error, only support int/float");
}
static TeaResult mod(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("mod func synatax error, need two items");
}
if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) {
auto result = args[0]->v_int % args[1]->v_int;
return TeaObject::build(result);
}
return TeaResult("mod func synatax error, only support int/float");
}
static TeaResult inc(vector<tobject> &args, tenv& env) {
if (args.size() != 1) {
return TeaResult("++ func synatax error, only support one items");
}
if (args[0]->type == TeaObject::T_INT) {
args[0]->v_int = args[0]->v_int + 1;
return args[0];
}
return TeaResult("++ func synatax error, only support int");
}
static TeaResult dec(vector<tobject> &args, tenv& env) {
if (args.size() != 1) {
return TeaResult("-- func synatax error, only support one items");
}
if (args[0]->type == TeaObject::T_INT) {
args[0]->v_int = args[0]->v_int - 1;
return args[0];
}
return TeaResult("-- func synatax error, only support int");
}
// comapir
static TeaResult less(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("< func synatax error, need two items");
}
if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) {
bool result = args[0]->v_int < args[1]->v_int;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) {
bool result = args[0]->v_float < args[1]->v_float;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
return TeaResult("< func synatax error, only support int/float");
}
static TeaResult more(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("> func synatax error, need two items");
}
if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) {
bool result = args[0]->v_int > args[1]->v_int;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) {
bool result = args[0]->v_float > args[1]->v_float;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
return TeaResult("> func synatax error, only support int/float");
}
static TeaResult lesseq(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("<= func synatax error, need two items");
}
if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) {
bool result = args[0]->v_int <= args[1]->v_int;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
return TeaResult("<= func synatax error, only support int");
}
static TeaResult moreeq(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult(">= func synatax error, need two items");
}
if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) {
bool result = args[0]->v_int >= args[1]->v_int;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
return TeaResult(">= func synatax error, only support int");
}
static TeaResult eqeq(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult(">= func synatax error, need two items");
}
if (args[0]->type == TeaObject::T_INT && args[1]->type == TeaObject::T_INT) {
bool result = args[0]->v_int == args[1]->v_int;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
if (args[0]->type == TeaObject::T_FLOAT && args[1]->type == TeaObject::T_FLOAT) {
bool result = args[0]->v_float == args[1]->v_float;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
if (args[0]->type == TeaObject::T_BOOL && args[1]->type == TeaObject::T_BOOL) {
bool result = args[0]->v_bool == args[1]->v_bool;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
if (args[0]->type == TeaObject::T_PATTERN && args[1]->type == TeaObject::T_PATTERN) {
bool result = args[0]->v_string == args[1]->v_string;
if (result == true) {
return tea_true;
} else {
return tea_false;
}
}
return TeaResult(">= func synatax error, only support int/float/bool/pattern");
}
// logic
static TeaResult notnot(vector<tobject> &args, tenv& env) {
if (args.size() != 1) {
return TeaResult("! func synatax error, only support one items");
}
if (args[0]->type == TeaObject::T_BOOL) {
if (args[0]->v_bool == true) {
return tea_false;
} else {
return tea_true;
}
}
return TeaResult("-- func synatax error, only support bool");
}
// list&map operation
static TeaResult size(vector<tobject> &args, tenv& env) {
if (args.size() != 1) {
return TeaResult("size func synatax error, only support one items");
}
if (args[0]->type == TeaObject::T_LIST) {
int64_t n = args[0]->v_list->size();
return TeaObject::build(n);
}
if (args[0]->type == TeaObject::T_MAP) {
int64_t n = args[0]->v_map->size();
return TeaObject::build(n);
}
return TeaResult("size func synatax error, only support list/map");
}
static TeaResult push(vector<tobject> &args, tenv& env) {
if (args.size() < 2) {
return TeaResult("push func synatax error, only support two more items");
}
if (args[0]->type == TeaObject::T_LIST) {
auto lst = args[0]->v_list;
for (size_t i = 1; i < args.size(); i++) {
lst->push_back(args[i]);
}
return tea_null;
}
return TeaResult("push func synatax error, only support list");
}
static TeaResult pop(vector<tobject> &args, tenv& env) {
if (args.size() != 1) {
return TeaResult("pop func synatax error, only support one");
}
if (args[0]->type == TeaObject::T_LIST) {
auto lst = args[0]->v_list;
if (lst->size() > 0) {
auto last = lst->back();
lst->pop_back();
return last;
}
return tea_null;
}
return TeaResult("pop func synatax error, only support list");
}
static TeaResult nth(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("push func synatax error, only support two items");
}
if (args[0]->type == TeaObject::T_LIST) {
auto lst = args[0]->v_list;
if (args[1]->type == TeaObject::T_INT) {
auto pos = args[1]->v_int;
return (*lst)[pos];
}
}
return TeaResult("nth func synatax error!");
}
static TeaResult set(vector<tobject> &args, tenv& env) {
if (args.size() != 3) {
return TeaResult("set func synatax error, only support two items");
}
if (args[0]->type == TeaObject::T_MAP) {
auto hash = args[0]->v_map;
if (args[1]->type == TeaObject::T_PATTERN) {
auto &key = args[1]->v_string;
(*hash)[key] = args[2];
return tea_null;
}
}
return TeaResult("set func synatax error!");
}
static TeaResult has(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("has func synatax error, only support two items");
}
if (args[0]->type == TeaObject::T_MAP) {
auto hash = args[0]->v_map;
if (args[1]->type == TeaObject::T_PATTERN) {
auto &key = args[1]->v_string;
if (hash->find(key) == hash->end()) {
return tea_false;
} else {
return tea_true;
}
}
}
return TeaResult("has func synatax error!");
}
static TeaResult rm(vector<tobject> &args, tenv& env) {
if (args.size() != 2) {
return TeaResult("rm func synatax error, only support two items");
}
if (args[0]->type == TeaObject::T_MAP) {
auto hash = args[0]->v_map;
if (args[1]->type == TeaObject::T_PATTERN) {
auto &key = args[1]->v_string;
hash->erase(key);
return tea_null;
}
}
return TeaResult("set func synatax error!");
}
private:
// core implementation
static bool is_builtin(const string& symbol) {
if ( symbol == "if" ||
symbol == "def" ||
symbol == "begin" ||
symbol == "while" ||
symbol == "map" ||
symbol == "list" ||
symbol == "&&" ||
symbol == "||" ||
symbol == "fn" ) {
return true;
}
return false;
}
static TeaResult eval_builtin(vector<tobject>& lst, tenv& env) {
assert(lst.size() > 0);
tobject head = lst[0];
string symbol = lst[0]->v_string;
if (symbol == "begin") {
return eval_begin(lst, env);
}
if (symbol == "if") {
return eval_if(lst, env);
}
if (symbol == "def") {
return eval_def(lst, env);
}
if (symbol == "while") {
return eval_while(lst, env);
}
if (symbol == "map") {
return eval_map(lst, env);
}
if (symbol == "list") {
return eval_list(lst, env);
}
if (symbol == "&&") {
return eval_and(lst, env);
}
if (symbol == "||") {
return eval_or(lst, env);
}
if (symbol == "fn") {
return eval_fn(lst, env);
}
return TeaResult("Bug, code can't reach here!");
}
static TeaResult eval_fn(vector<tobject>& lst, tenv& env) {
TeaLambda lambda;
if ( lst.size() == 3) {
return TeaResult("(fn) synatax error: args body");
}
if ( lst[1]->type != TeaObject::T_LIST ) {
return TeaResult("(fn) synatax error: args should be a list");
}
for (size_t i = 0; i < lst[1]->v_list->size(); i++) {
assert( (*lst[1]->v_list)[i]->type == TeaObject::T_SYMBOL);
lambda.head.push_back( (*lst[1]->v_list)[i] );
}
lambda.body = lst[2];
auto obj = TeaObject( make_shared<TeaLambda>(lambda) );
auto tobj = make_shared<TeaObject>(obj);
return TeaResult(tobj);
}
static TeaResult eval_and(vector<tobject>& lst, tenv& env) {
if ( lst.size() < 3) {
return TeaResult("(&&) synatax error: need 3 items at least");
}
bool result = true;
for (size_t i = 1; i < lst.size(); ) {
TeaResult r = eval(lst[i], env);
if (r.is_error()) {
return r;
}
if (r.result->type != TeaObject::T_BOOL) {
return TeaResult("(&&) synatax error: item must be bool ");
}
result = result && r.result->v_bool;
if (result == false) {
break;
}
}
if (result) {
return TeaResult(tea_true);
}
return TeaResult(tea_false);
}
static TeaResult eval_or(vector<tobject>& lst, tenv& env) {
if ( lst.size() < 3) {
return TeaResult("(&&) synatax error: need 3 items at least");
}
bool result = false;
for (size_t i = 1; i < lst.size(); ) {
TeaResult r = eval(lst[i], env);
if (r.is_error()) {
return r;
}
if (r.result->type != TeaObject::T_BOOL) {
return TeaResult("(&&) synatax error: item must be bool ");
}
result = result || r.result->v_bool;
if (result == true) {
break;
}
}
if (result) {
return TeaResult(tea_true);
}
return TeaResult(tea_false);
}
static TeaResult eval_list(vector<tobject>& lst, tenv& env) {
vector<tobject> new_lst;
for (size_t i = 1; i < lst.size(); ) {
TeaResult r = eval(lst[i], env);
if (r.is_error()) {
return r;
}
new_lst.push_back(r.result);
}
auto obj = TeaObject( make_shared<vector<tobject>>(new_lst) );
return TeaResult( make_shared<TeaObject>(obj) );
}
static TeaResult eval_map(vector<tobject>& lst, tenv& env) {
if ( (lst.size() % 2) != 1) {
return TeaResult("'(map)' synatax error, must include @pattern/value pair");
}
map<string, tobject> hash;
for (size_t i = 1; i < lst.size(); ) {
assert(lst[i]->type == TeaObject::T_PATTERN);
TeaResult r = eval(lst[i+1], env);
if (r.is_error()) {
return r;
}
hash[lst[i]->v_string] = r.result;
i += 2;
}
auto obj = TeaObject( make_shared<map<string, tobject>>(hash) );
return TeaResult( make_shared<TeaObject>(obj) );
}
static TeaResult eval_while(vector<tobject>& lst, tenv& env) {
if (lst.size() < 2) {
return TeaResult("'(while)' synatax error, must include condition");
}
for(;;) {
TeaResult r = eval(lst[2], env);
if (r.is_error()) {
return r;
}
auto cond = r.result;
if ( cond->type != TeaObject::T_BOOL ) {
return TeaResult("'(while)' synatax error, first item should reutrn bool!");
}
if (cond->v_bool == false) {
break;
}
for (size_t i = 2; i < lst.size(); i++) {
TeaResult r = eval(lst[2], env);
if (r.is_error()) {
return r;
}
}
}
return TeaResult(tea_null);
}
static TeaResult eval_def(vector<tobject>& lst, tenv& env) {
if (lst.size() == 3) {
TeaResult r = eval(lst[2], env);
if (r.is_error()) {
return r;
}
assert(lst[1]->type == TeaObject::T_SYMBOL);
env->set(lst[1]->v_string, r.result);
return TeaResult(tea_null);
}
return TeaResult("'(def)' synatax error!");
}
static TeaResult eval_if(vector<tobject>& lst, tenv& env) {
if (lst.size() >= 3) {
TeaResult r = eval(lst[1], env);
if (r.is_error()) {
return r;
}
auto cond = r.result;
if ( cond->type != TeaObject::T_BOOL ) {
return TeaResult("'(if)' synatax error, first item should reutrn bool!");
}
if (cond->v_bool == true) {
return eval(lst[2], env);
}
if (lst.size() == 3) {
return TeaResult(tea_null);
}
if (lst.size() == 4) {
return eval(lst[3], env);
}
}
return TeaResult("'(if)' synatax error!");
}
static TeaResult eval_begin(vector<tobject>& lst, tenv& env) {
if (lst.size() == 1) {
return TeaResult(tea_null);
}
for ( size_t i = 1; i < lst.size() - 1; i++) {
TeaResult r = eval(lst[i], env);
if (r.is_error()) {
return r;
}
}
return eval(lst[lst.size()-1], env);
}
static TeaResult eval_lambda(tobject& head, vector<tobject>& args, tenv& env) {
assert(head->type == TeaObject::T_LAMBDA);
auto lambda = head->v_lambda;
TeaEnvironment new_env(env, lambda->closure);
for (size_t i = 0; i < lambda->head.size(); i++) {
assert(lambda->head[i]->type == TeaObject::T_SYMBOL);
if ( i >= args.size() ) {
new_env.set(lambda->head[i]->v_string, tea_null);
} else {
new_env.set(lambda->head[i]->v_string, args[i]);
}
}
auto tenv = make_shared<TeaEnvironment>(new_env);
return eval(lambda->body, tenv);
}
static TeaResult eval(tobject& obj, tenv& env) {
if ( obj->type == TeaObject::T_NULL ||
obj->type == TeaObject::T_BOOL ||
obj->type == TeaObject::T_INT ||
obj->type == TeaObject::T_FLOAT ||
obj->type == TeaObject::T_PATTERN ||
obj->type == TeaObject::T_MAP ||
obj->type == TeaObject::T_EXT ||
obj->type == TeaObject::T_LAMBDA) {
return TeaResult(obj);
}
if ( obj->type == TeaObject::T_SYMBOL ) {
return TeaResult( env->get(obj->v_string));
}
// execute list
if ( obj->type == TeaObject::T_LIST ) {
// empty list return null
if (obj->v_list->size() == 0) {
return TeaResult( tea_null );
}
// get head of list
vector<tobject>& lst(*obj->v_list);
tobject head = lst[0];
assert(head->type == TeaObject::T_SYMBOL);
if (is_builtin(head->v_string)) {
// step.1 check builtin call or eval
auto tresult = eval_builtin(lst, env);
if (tresult.is_error()){
tresult.trace.push_back(obj->to_string());
}
return tresult;
} else {
// step.2 eval head of list
auto tresult = eval(head, env);
if (tresult.is_error()) {
tresult.trace.push_back(obj->to_string());
return tresult;
}
head = tresult.result;
}
// step.3 eval all the args
vector<tobject> args;
for (size_t i = 1; i < lst.size(); i++) {
TeaResult tresult = eval(lst[i], env);
if (tresult.is_error()) {
tresult.trace.push_back(obj->to_string());
return tresult;
}
args.push_back(tresult.result);
}
// step.4 check PATTERN & FUNC & LAMBODA
if ( head->type == TeaObject::T_PATTERN ) {
if (args.size() == 1) {
if (args[0]->type == TeaObject::T_MAP) {
auto query = args[0]->v_map->find(head->v_string);
if (query == args[0]->v_map->end()) {
string msg = "Can't find " + head->v_string + " in map!";
auto tresult = TeaResult(msg);
tresult.trace.push_back(obj->to_string());
return tresult;
} else {
return TeaResult(query->second);
}
}
}
auto tresult = TeaResult("query map synatax error!");
tresult.trace.push_back(obj->to_string());
return tresult;
}
if ( head->type == TeaObject::T_FUNC ) {
auto tresult = head->v_func(args, env);
if ( tresult.is_error() ) {
tresult.trace.push_back(obj->to_string());
}
return tresult;
}
if ( head->type == TeaObject::T_LAMBDA ) {
auto tresult = eval_lambda(head, args, env);
if ( tresult.is_error() ) {
tresult.trace.push_back(obj->to_string());
}
return tresult;
}
}
auto tresult = TeaResult("BUG!");
if ( tresult.is_error() ) {
tresult.trace.push_back(obj->to_string());
}
return tresult;
}
static TeaResult eval_all(vector<tobject>& codes, tenv& env) {
int last = codes.size() - 1;
if (last < 0) {
return TeaResult(tea_null);
}
for (int i = 0; i < last; i++) {
auto r = eval(codes[i], env);
if (r.is_error()) {
return r;
}
}
return eval(codes[last], env);
}
private:
// parser, compiler
static tobject parse_atom(const string& token) {
// true or false
if (token == "true") {
return tea_true;
}
if (token == "false") {
return tea_false;
}
// number
if (isdigit(token.at(0)) || (token.at(0) == '-' && token.length() >= 2 && isdigit(token.at(1)))) {
if (token.find('.') != string::npos || token.find('e') != string::npos) { // double
float value = atof(token.c_str());
return TeaObject::build(value);
} else {
int64_t value = atol(token.c_str());
return TeaObject::build(value);
}
}
// pattern
if (token.at(0) == '@') {
string pattern = token;
pattern.erase(0, 1);
if (pattern == "") {
pattern = " ";
}
return TeaObject::build(pattern);
}
// symbol
return make_shared<TeaObject>( TeaObject(TeaObject::T_SYMBOL, token) );
}
static tobject parse_tokens(const vector<string>& tokens, size_t pos, size_t &next_pos) {
size_t i = pos;
if ( tokens[i] != "(") {
return nullptr;
}
auto ret = make_shared<vector<tobject>>();
i = i + 1;
for (;;) {
if ( i >= tokens.size() ) {
break;
}
// 0. check is end of a list
const string& token(tokens[i]);
if (token == ")") {
next_pos = i + 1;
return TeaObject::build(ret);
}
// 1. an new list begin
if (token == "(") {
size_t end_pos = 0;
auto next = parse_tokens(tokens, i, end_pos);
if (next == nullptr) {
return nullptr;
}
ret->push_back(next);
i = end_pos;
}
// 2. an new symbol
ret->push_back( parse_atom(tokens[i]) );
i++;
}
return nullptr;
}
static string parse_and_compile(string& code, tenv& env, vector<tobject>& codes) {
struct _ {
static void findAndReplaceAll(std::string & data, const std::string toSearch, const std::string replaceStr) {
size_t pos = data.find(toSearch);
while( pos != std::string::npos){
data.replace(pos, toSearch.size(), replaceStr);
pos =data.find(toSearch, pos + replaceStr.size());
}
}
static void tokenize(std::string const &str, const char delim,
std::vector<std::string> &out) {
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos) {
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
};
_::findAndReplaceAll(code, "{", "(map");
_::findAndReplaceAll(code, "}", ")");
_::findAndReplaceAll(code, "[", "(list");
_::findAndReplaceAll(code, "]", ")");
_::findAndReplaceAll(code, "(", " ( ");
_::findAndReplaceAll(code, ")", " ) ");
_::findAndReplaceAll(code, "\n"," ");
vector<string> tokens;
_::tokenize(code, ' ', tokens);
codes.clear();
if (tokens.size() == 1) {
codes.push_back( parse_atom( tokens[0] ));
} else {
size_t i = 0;
while ( i < tokens.size() ) {
size_t next = 0;
auto ret = parse_tokens(tokens, i, next);
if (ret == nullptr) {
return "parse token error!";
}
codes.push_back(ret);
i = next;
}
}
return "";
}
public:
static tenv new_env() {
auto env = TeaEnvironment();
init(env.data);
return make_shared<TeaEnvironment>(env);
}
static string run(string& code, tenv& env) {
vector<tobject> codes;
auto result = parse_and_compile(code, env, codes);
if (result != "") {
return result;
}
auto ret = eval_all(codes, env);
if (ret.is_error()) {
return ret.trace[0];
}
return ret.result->to_string();
}
};
}
| 32.277827 | 119 | 0.478454 | Teaonly |
d6f23e5f9d43143eed1469a6c8f879af2cbd9592 | 3,155 | hpp | C++ | libs/ml/include/ml/state_dict.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | 3 | 2019-07-11T08:49:27.000Z | 2021-09-07T16:49:15.000Z | libs/ml/include/ml/state_dict.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | null | null | null | libs/ml/include/ml/state_dict.hpp | devjsc/ledger-1 | 2aa68e05b9f9c10a9971fc8ddf4848695511af3c | [
"Apache-2.0"
] | 2 | 2019-07-13T12:45:22.000Z | 2021-03-12T08:48:57.000Z | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "math/tensor.hpp"
#include <list>
namespace fetch {
namespace ml {
/**
* A utility class to extract the network trainable parameter and serialize them for saving /
* sharing
* @tparam T
*/
template <class T>
struct StateDict
{
using ArrayType = T;
using ArrayPtrType = std::shared_ptr<ArrayType>;
ArrayPtrType weights_;
std::map<std::string, StateDict<T>> dict_;
bool operator==(StateDict<T> const &o) const
{
return !((bool(weights_) ^ bool(o.weights_)) || (weights_ && (*weights_ != *(o.weights_))) ||
(dict_ != o.dict_));
}
void InlineDivide(typename ArrayType::Type n)
{
if (weights_)
{
weights_->InlineDivide(n);
}
for (auto &kvp : dict_)
{
kvp.second.InlineDivide(n);
}
}
void InlineAdd(StateDict const &o, bool strict = true)
{
if (o.weights_ && !weights_ && !strict)
{
weights_ = std::make_shared<ArrayType>(o.weights_->shape());
}
assert(!((bool(weights_) ^ bool(o.weights_))));
if (weights_)
{
weights_->InlineAdd(*(o.weights_));
}
for (auto const &kvp : o.dict_)
{
dict_[kvp.first].InlineAdd(kvp.second, strict);
}
}
/**
* Used to merge a list of state dict together into a new object
* All are weighted equally -- Usefull for averaging weights of multiple similar models
* @param stateDictList
*/
static StateDict MergeList(std::list<StateDict> const &stateDictList)
{
StateDict ret;
for (auto const &sd : stateDictList)
{
ret.InlineAdd(sd, false);
}
ret.InlineDivide(static_cast<typename ArrayType::Type>(stateDictList.size()));
return ret;
}
/**
* Used to merge a stateDict into another
* @param o -- The stateDict to merge into this
* @param ratio -- this = this * ration + o * (1 - ratio)
*/
StateDict &Merge(StateDict const &o, float ratio = .5f)
{
assert(ratio >= 0.0f && ratio <= 1.0f);
if (ratio > 0)
{
if (weights_)
{
weights_->InlineMultiply(typename ArrayType::Type(1.0f - ratio));
weights_->InlineAdd(o.weights_->Copy().InlineMultiply(typename ArrayType::Type(ratio)));
}
for (auto &e : dict_)
{
e.second.Merge(o.dict_.at(e.first));
}
}
return *this;
}
};
} // namespace ml
} // namespace fetch
| 27.198276 | 97 | 0.594612 | devjsc |
d6f27fd6c3a64308adf3bfb6e20133605df6fa39 | 442 | cpp | C++ | UTEngine/Native/NZoneInfo.cpp | neuromancer/UTEngine | 630398eabbaa173c933234e4c44ff2d62f0347e8 | [
"Apache-2.0",
"CC0-1.0"
] | 50 | 2020-12-02T17:41:17.000Z | 2022-03-18T05:08:21.000Z | UTEngine/Native/NZoneInfo.cpp | neuromancer/UTEngine | 630398eabbaa173c933234e4c44ff2d62f0347e8 | [
"Apache-2.0",
"CC0-1.0"
] | 11 | 2021-07-14T13:41:12.000Z | 2021-09-30T10:32:58.000Z | UTEngine/Native/NZoneInfo.cpp | neuromancer/UTEngine | 630398eabbaa173c933234e4c44ff2d62f0347e8 | [
"Apache-2.0",
"CC0-1.0"
] | 4 | 2021-07-20T20:22:36.000Z | 2022-01-06T15:30:26.000Z |
#include "Precomp.h"
#include "NZoneInfo.h"
#include "UObject/UActor.h"
#include "VM/NativeFunc.h"
#include "VM/Frame.h"
void NZoneInfo::RegisterFunctions()
{
RegisterVMNativeFunc_2("ZoneInfo", "ZoneActors", &NZoneInfo::ZoneActors, 308);
}
void NZoneInfo::ZoneActors(UObject* Self, UObject* BaseClass, UObject*& Actor)
{
Frame::CreatedIterator = std::make_unique<ZoneActorsIterator>(UObject::Cast<UZoneInfo>(Self), BaseClass, &Actor);
}
| 26 | 114 | 0.751131 | neuromancer |
d6f2ae1a29cefd6c05e7c927067c982a20a0aa0f | 4,028 | cpp | C++ | LoganEngine/old/lPhys2/lpRigidBody/lpBox.cpp | sereslorant/logan_engine | a596b4128d0a58236be00f93064e276e43484017 | [
"MIT"
] | 1 | 2019-12-26T13:22:29.000Z | 2019-12-26T13:22:29.000Z | LoganEngine/old/lPhys2/lpRigidBody/lpBox.cpp | sereslorant/logan_engine | a596b4128d0a58236be00f93064e276e43484017 | [
"MIT"
] | null | null | null | LoganEngine/old/lPhys2/lpRigidBody/lpBox.cpp | sereslorant/logan_engine | a596b4128d0a58236be00f93064e276e43484017 | [
"MIT"
] | null | null | null |
#include "lpBox.h"
void lpBox::CalculateBoxInertiaTensor()
{
InertiaTensor[0][0] = 1.0/12.0 * Mass * (Height*Height + Depth*Depth); InertiaTensor[1][0] = 0.0; InertiaTensor[2][0] = 0.0;
InertiaTensor[0][1] = 0.0; InertiaTensor[1][1] = 1.0/12.0 * Mass * (Width*Width + Depth*Depth); InertiaTensor[2][1] = 0.0;
InertiaTensor[0][2] = 0.0; InertiaTensor[1][2] = 0.0; InertiaTensor[2][2] = 1.0/12.0 * Mass * (Width*Width + Height*Height);
if(Mass != 0.0)
{
InertiaTensor.Invert(InvInertiaTensor);
}
}
void lpBox::RecalculateMesh()
{
//lmScalar BoundingSphereRadius = std::sqrt((Width/2.0)*(Width/2.0) + (Height/2.0)*(Height/2.0) + (Depth/2.0)*(Depth/2.0));
//BoundingSphere->SetRadius(BoundingSphereRadius);
/*
* Generating vertices
*/
//Front
Vertices[0] = {-Width/2.0, Height/2.0, Depth/2.0};
Vertices[1] = {-Width/2.0,-Height/2.0, Depth/2.0};
Vertices[2] = { Width/2.0,-Height/2.0, Depth/2.0};
Vertices[3] = { Width/2.0, Height/2.0, Depth/2.0};
//Back
Vertices[4] = {-Width/2.0, Height/2.0,-Depth/2.0};
Vertices[5] = {-Width/2.0,-Height/2.0,-Depth/2.0};
Vertices[6] = { Width/2.0,-Height/2.0,-Depth/2.0};
Vertices[7] = { Width/2.0, Height/2.0,-Depth/2.0};
GenerateBoundingSphere();
}
lpBox::lpBox(bool ghost,lmScalar mass,liRigidBody::liState *state,lmScalar width,lmScalar height,lmScalar depth)
:lpMesh(ghost,mass,state,LP_BOX),Width(width),Height(height),Depth(depth)
{
/*
* Generating normals
*/
/*
Normals.push_back(lmVector3D( 0.0, 0.0, 1.0));//Front face
Normals.push_back(lmVector3D( 1.0, 0.0, 0.0));//Left face
Normals.push_back(lmVector3D( 0.0, 0.0,-1.0));//Back face
Normals.push_back(lmVector3D(-1.0, 0.0, 0.0));//Right face
Normals.push_back(lmVector3D( 0.0, 1.0, 0.0));//Top face
Normals.push_back(lmVector3D( 0.0,-1.0, 0.0));//Bottom face
*/
Normals = {{ 0.0, 0.0, 1.0},
{ 1.0, 0.0, 0.0},
{ 0.0, 0.0,-1.0},
{-1.0, 0.0, 0.0},
{ 0.0, 1.0, 0.0},
{ 0.0,-1.0, 0.0}
};
/*
* Generating triangles
*/
/*
Triangles.push_back({0,1,2,0});Triangles.push_back({0,3,2,0});//Front face
Triangles.push_back({2,3,6,1});Triangles.push_back({3,7,6,1});//Left face
Triangles.push_back({4,5,6,2});Triangles.push_back({4,7,6,2});//Back face
Triangles.push_back({0,1,5,3});Triangles.push_back({0,5,4,3});//Right face
Triangles.push_back({0,3,4,4});Triangles.push_back({3,4,7,4});//Top face
Triangles.push_back({1,2,6,5});Triangles.push_back({1,5,6,5});//Bottom face
*/
Triangles = {{0,1,2,0},{0,3,2,0},//Front face
{2,3,6,1},{3,7,6,1},//Left face
{4,5,6,2},{4,7,6,2},//Back face
{0,1,5,3},{0,5,4,3},//Right face
{0,3,4,4},{3,4,7,4},//Top face
{1,2,6,5},{1,5,6,5}//Bottom face
};
Vertices.resize(8);
RecalculateMesh();
for(int i=0;i < Triangles.size();i++)
{
lmVector3D Cukcsy = lmCross(Vertices[Triangles[i].V[2]] - Vertices[Triangles[i].V[0]],Vertices[Triangles[i].V[1]] - Vertices[Triangles[i].V[0]]);
if(lmDot(Normals[Triangles[i].Normal],Cukcsy) < 0.0)
{
unsigned int Tmp = Triangles[i].V[1];
Triangles[i].V[1] = Triangles[i].V[2];
Triangles[i].V[2] = Tmp;
/*
std::cout << i << std::endl;
Cukcsy = lmCross(Vertices[Triangles[i].V3] - Vertices[Triangles[i].V1],Vertices[Triangles[i].V2] - Vertices[Triangles[i].V1]);
if(!(lmDot(Normals[Triangles[i].Normal],Cukcsy) < 0.0))
{
std::cout << "Győzelem!" << std::endl;
}
*/
}
}
CalculateBoxInertiaTensor();
}
lmScalar lpBox::GetWidth()
{
return Width;
}
lmScalar lpBox::GetHeight()
{
return Height;
}
lmScalar lpBox::GetDepth()
{
return Depth;
}
void lpBox::SetWidth(lmScalar width)
{
Width = width;
RecalculateMesh();
CalculateBoxInertiaTensor();
}
void lpBox::SetHeight(lmScalar height)
{
Height = height;
RecalculateMesh();
CalculateBoxInertiaTensor();
}
void lpBox::SetDepth(lmScalar depth)
{
Depth = depth;
RecalculateMesh();
CalculateBoxInertiaTensor();
}
| 27.77931 | 194 | 0.611221 | sereslorant |
d6f385b24d883e60228a8aa546f3808fd794dabf | 9,929 | cpp | C++ | src/TGUI/Signal.cpp | Bayonetta5/tgui | 87d0e9e53895347b04cf15c94be89473548769f3 | [
"Zlib"
] | null | null | null | src/TGUI/Signal.cpp | Bayonetta5/tgui | 87d0e9e53895347b04cf15c94be89473548769f3 | [
"Zlib"
] | null | null | null | src/TGUI/Signal.cpp | Bayonetta5/tgui | 87d0e9e53895347b04cf15c94be89473548769f3 | [
"Zlib"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TGUI - Texus' Graphical User Interface
// Copyright (C) 2012-2017 Bruno Van de Velde (vdv_b@tgui.eu)
//
// 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.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <TGUI/Signal.hpp>
#include <TGUI/Widget.hpp>
#include <TGUI/Widgets/ChildWindow.hpp>
#include <TGUI/to_string.hpp>
#include <cassert>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace
{
unsigned int lastId = 0;
unsigned int generateUniqueId()
{
return ++lastId;
}
template <typename Type>
const Type& dereference(const void* obj)
{
return *static_cast<const Type*>(obj);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace tgui
{
std::vector<const void*> Signal::m_parameters(3, nullptr);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Signal::Signal(const Signal& other) :
m_name {other.m_name},
m_handlers{} // signal handlers are not copied with the widget
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Signal& Signal::operator=(const Signal& other)
{
if (this != &other)
{
m_name = other.m_name;
m_handlers.clear(); // signal handlers are not copied with the widget
}
return *this;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int Signal::connect(const Delegate& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = handler;
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int Signal::connect(const DelegateEx& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Signal::disconnect(unsigned int id)
{
return m_handlers.erase(id) == 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Signal::disconnectAll()
{
m_handlers.clear();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
tgui::Widget::Ptr Signal::getWidget()
{
return dereference<Widget*>(m_parameters[0])->shared_from_this();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(TypeName, Type) \
unsigned int Signal##TypeName::connect(const Delegate##TypeName& handler) \
{ \
const auto id = generateUniqueId(); \
m_handlers[id] = [handler](){ handler(dereference<Type>(m_parameters[1])); }; \
return id; \
} \
\
unsigned int Signal##TypeName::connect(const Delegate##TypeName##Ex& handler) \
{ \
const auto id = generateUniqueId(); \
m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<Type>(m_parameters[1])); }; \
return id; \
}
TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(Int, int)
TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(UInt, unsigned int)
TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(Bool, bool)
TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(Float, float)
TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(String, sf::String)
TGUI_SIGNAL_VALUE_CONNECT_DEFINITION(Vector2f, sf::Vector2f)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalChildWindow::connect(const DelegateChildWindow& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler](){ handler(std::static_pointer_cast<ChildWindow>(dereference<ChildWindow*>(m_parameters[1])->shared_from_this())); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalChildWindow::connect(const DelegateChildWindowEx& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, std::static_pointer_cast<ChildWindow>(dereference<ChildWindow*>(m_parameters[1])->shared_from_this())); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool SignalChildWindow::emit(const ChildWindow* childWindow)
{
if (m_handlers.empty())
return false;
m_parameters[1] = static_cast<const void*>(&childWindow);
return Signal::emit(childWindow);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalItem::connect(const DelegateItem& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler](){ handler(dereference<sf::String>(m_parameters[1])); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalItem::connect(const DelegateItemEx& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<sf::String>(m_parameters[1])); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalItem::connect(const DelegateItemAndId& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler](){ handler(dereference<sf::String>(m_parameters[1]), dereference<sf::String>(m_parameters[2])); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalItem::connect(const DelegateItemAndIdEx& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<sf::String>(m_parameters[1]), dereference<sf::String>(m_parameters[2])); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalMenuItem::connect(const DelegateMenuItem& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler](){ handler(dereference<sf::String>(m_parameters[1])); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalMenuItem::connect(const DelegateMenuItemEx& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<sf::String>(m_parameters[1])); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalMenuItem::connect(const DelegateMenuItemFull& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler](){ handler(dereference<std::vector<sf::String>>(m_parameters[2])); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned int SignalMenuItem::connect(const DelegateMenuItemFullEx& handler)
{
const auto id = generateUniqueId();
m_handlers[id] = [handler, name=m_name](){ handler(getWidget(), name, dereference<std::vector<sf::String>>(m_parameters[2])); };
return id;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 40.526531 | 184 | 0.434988 | Bayonetta5 |
d6f419f178723f7aadc640de4316d43d8b043ea0 | 6,813 | cpp | C++ | morse/DotNet/adaptiveCellImageBuilder/PointGraph.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | 1 | 2019-12-24T15:52:45.000Z | 2019-12-24T15:52:45.000Z | morse/DotNet/adaptiveCellImageBuilder/PointGraph.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | null | null | null | morse/DotNet/adaptiveCellImageBuilder/PointGraph.cpp | jonnyzzz/phd-project | beab8615585bd52ef9ee1c19d1557e8c933c047a | [
"Apache-2.0"
] | null | null | null | #include "StdAfx.h"
#include ".\pointgraph.h"
#include <iostream>
#include <set>
#include <functional>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
PointGraph::PointGraph(ISystemFunction* function, int dimension, size_t upperLimit):
function(function), dimension(dimension),
manager((2*sizeof(Node)+4*sizeof(double)*dimension+sizeof(Edge))*100),
upperLimit(upperLimit), maxSize(0)
{
ATLASSERT(dimension > 0);
function_input = function->getInput();
function_output = function->getOutput();
}
PointGraph::~PointGraph(void)
{
}
void PointGraph::Reset() {
manager.Reset();
nodes.clear();
edges.clear();
}
PointGraph::Edge* PointGraph::createEdge() {
return manager.Allocate<Edge>();
}
PointGraph::Node* PointGraph::createNode() {
return manager.AllocateDisposable<Node>();
}
void inline PointGraph::arraycopy(double* to, const double* from) {
memcpy(to, from, sizeof(double)*dimension);
}
double* PointGraph::createArray() {
return manager.AllocateArray<double>(dimension);
}
double* PointGraph::arraycopy(const double* node) {
double* myDouble = createArray();
arraycopy(myDouble, node);
return myDouble;
}
PointGraph::Edge* PointGraph::AddEdge(PointGraph::Node* left, PointGraph::Node* right) {
Edge* edge = createEdge();
edge->left = left;
edge->right = right;
left->edges.insert(right);
right->edges.insert(left);
edges.push_back(edge);
return edge;
}
PointGraph::Node* PointGraph::AddNodeInternal(double* node) {
Node* myNode = createNode();
myNode->points = node;
myNode->valueCache = NULL;
myNode->checkedEdges = 0;
nodes.push_back(myNode);
return myNode;
}
PointGraph::Node* PointGraph::AddNode(const double* node) {
double* myDouble = arraycopy(node);
NormalizePoint(myDouble);
return AddNodeInternal(myDouble);
}
void PointGraph::evaluateNodeCache(PointGraph::Node* node) {
if (node->valueCache != NULL) return;
arraycopy(function_input, node->points);
function->evaluate();
node->valueCache = arraycopy(function_output);
}
double inline PointGraph::Abs(double x) {
return x>0 ? x : -x;
}
PointGraphAction PointGraph::checkEdgeLength(PointGraph::Edge* edge, double* precision) {
evaluateNodeCache(edge->left);
evaluateNodeCache(edge->right);
return NeedDevideEdge(edge->left->valueCache, edge->right->valueCache, precision);
}
PointGraphAction PointGraph::NeedDevideEdge(const double* left, const double* right, const double* precision) {
for (int i=0; i<dimension; i++) {
if (Abs(left[i] - right[i]) > precision[i]){
return PointGraph_Devide;
}
}
return PointGraph_NotDevide;
}
double PointGraph::EdgeLength(const double* left, const double* right) {
double length = 0;
for (int i=0; i<dimension; i++) {
length += Abs(left[i] - right[i]);
}
return length;
}
void PointGraph::EdgeLength(const double* left, const double* right, double* lengths) {
for (int i=0; i<dimension; i++) {
lengths[i] = Abs(left[i] - right[i]);
}
}
void PointGraph::ComputeMiddle(const double* left, const double* right, double* v) {
for (int i=0; i<dimension; i++) {
*v++ = (*left++ + *right++)/2;
}
}
void PointGraph::NormalizePoint(double* v) {
}
PointGraph::Node* PointGraph::split(PointGraph::Edge* edge) {
Node* left = edge->left;
Node* right = edge->right;
double* myDouble = createArray();
ComputeMiddle(left->points, right->points, myDouble);
left->edges.erase(right);
right->edges.erase(left);
Node* myNode = AddNodeInternal(myDouble);
NodeSet::const_iterator fst = left->edges.begin();
NodeSet::const_iterator fst_e = left->edges.end();
NodeSet::const_iterator snd = right->edges.begin();
NodeSet::const_iterator snd_e = right->edges.end();
NodeSet::key_compare cmp;
while (fst != fst_e && snd != snd_e) {
if (*fst == *snd) {
AddEdge(myNode, *fst);
fst++;
snd++;
} else {
if (cmp(*fst, *snd)) { //fst < snd
fst++;
} else {
snd++;
}
}
}
AddEdge(myNode, right);
AddEdge(left, myNode);
return myNode;
}
bool PointGraph::Iterate(double* precision) {
while (!edges.empty()) {
Edge* edge = edges.front();
edges.pop_front();
switch(this->checkEdgeLength(edge, precision)) {
case PointGraph_Devide:
split(edge);
break;
case PointGraph_NotDevide:
edge->left->checkedEdges++;
edge->right->checkedEdges++;
break;
}
if (upperLimit != 0 && nodes.size() > upperLimit) {
return false;
}
}
return true;
}
const PointGraph::NodeList& PointGraph::Points() {
if (maxSize < nodes.size())
maxSize = nodes.size();
return nodes;
}
bool PointGraph::IsCheckedNode(PointGraph::Node* node) {
return (node->checkedEdges == edges.size());
}
double PointGraph::NodeLength(PointGraph::Node* node, double* lengths) {
evaluateNodeCache(node);
double length;
bool isCheck = false;
Node* toLength = NULL;
for (NodeSet::iterator it = node->edges.begin(); it != node->edges.end(); it++) {
Node* to = *it;
if (!IsCheckedNode(to)) {
evaluateNodeCache(to);
double len = EdgeLength(node->valueCache, to->valueCache);
if (!isCheck || len > length) {
isCheck = true;
length = len;
toLength = to;
}
}
}
EdgeLength(node->valueCache, toLength->valueCache, lengths);
return length;
}
void PointGraph::DumpNode(PointGraph::Node* node, ostream& o) {
for (int i=0; i<dimension; i++) {
o<<node->points[i];
if (i+1 != dimension)
o<<", ";
}
}
void PointGraph::Dump(ostream& o) {
o<<"\n\nDumping Point Graph\nNodes = "<<nodes.size()<<"\n";
o<<"Edges counter: \n";
int cnt = 0;
for (NodeList::iterator it = nodes.begin(); it != nodes.end(); ++it) {
o<<"Node[";
DumpNode((*it),o);
o<<"]->Edges="<<(*it)->edges.size()<<"\n";
}
o<<"\n\n";
o<<"Adj matrix :\n";
for (NodeList::iterator it = nodes.begin(); it != nodes.end(); ++it) {
o<<"Node[";
DumpNode((*it), o);
o<<"] -> ";
for (NodeSet::iterator itt = (*it)->edges.begin(); itt != (*it)->edges.end(); itt++) {
Node* tmp = *itt;
o<<"Node[";
DumpNode(tmp, o);
o<<"], ";
}
o<<"\n";
}
o<<"\n\n";
}
size_t PointGraph::GetMaximumNumberOfPoints() {
return maxSize;
} | 24.684783 | 111 | 0.5968 | jonnyzzz |
d6f512daa20b8ce86475f8486b8c413f54b9932a | 784 | cpp | C++ | src/classwork/04_assign/main.cpp | acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-SageElephant | 6fa25968c9c57263be2700f4c39892d863e5e78f | [
"MIT"
] | null | null | null | src/classwork/04_assign/main.cpp | acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-SageElephant | 6fa25968c9c57263be2700f4c39892d863e5e78f | [
"MIT"
] | null | null | null | src/classwork/04_assign/main.cpp | acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-SageElephant | 6fa25968c9c57263be2700f4c39892d863e5e78f | [
"MIT"
] | null | null | null | //write includes statements
#include <iostream>
#include "loops.h"
//write using statements for cin and cout
using std::cin; using std::cout;
/*
Use a do while loop to prompt the user for
a number, call the factorial function, and display the number's
factorial. Also, loop continues as long as user wants to.
*/
int main()
{
int num;
char go_again;
do
{
do
{
cout << "Enter an integer number between 1 and 10: \n";
cin >> num;
}
while (!(num >= 1 && num <= 10));
cout << "The factorial of " << num << " is " << factorial(num) << "\n";
cout << "Would you like to enter another number? Type 'Y' to continue.";
cin >> go_again;
}
while (go_again == 'Y');
cout << "Thanks! The program has finished. \n";
return 0;
} | 21.777778 | 76 | 0.604592 | acc-cosc-1337-spring-2021 |
d6f8949cdb108e259bdd0e918695e83419637eba | 1,666 | cpp | C++ | Olympiad Solutions/URI/1314.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | Olympiad Solutions/URI/1314.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | Olympiad Solutions/URI/1314.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | // Ivan Carvalho
// Solution to https://www.urionlinejudge.com.br/judge/problems/view/1314
#include <cstdio>
#include <vector>
#include <algorithm>
#define MAXN 10001
using namespace std;
vector<int> grafo[MAXN];
int pai[MAXN],dfs_low[MAXN],dfs_num[MAXN],dfs_parent[MAXN],pontosdearticulacao[MAXN],dfsNumberCounter,dfsRoot,dfsRootChildren,n,m,q;
int find(int x){
if(x == pai[x]) return x;
return pai[x] = find(pai[x]);
}
void join(int x,int y){
x=find(x);y=find(y);
if(x==y) return;
if(x>y) swap(x,y);
pai[y] = x;
}
void dfs(int u){
dfs_low[u] = dfs_num[u] = ++dfsNumberCounter;
for(int i=0;i<grafo[u].size();i++){
int v = grafo[u][i];
if(dfs_num[v] == 0){
dfs_parent[v] = u;
if(u == dfsRoot) dfsRootChildren++;
dfs(v);
if(dfs_low[v] >= dfs_num[u]){
pontosdearticulacao[u] = 1;
}
if(dfs_low[v] > dfs_num[u]){
//printf("%d %d is bridge\n",u,v);
join(u,v);
}
dfs_low[u] = min(dfs_low[v],dfs_low[u]);
}
else if(v != dfs_parent[u]){
dfs_low[u] = min(dfs_low[v],dfs_low[u]);
}
}
}
int main(){
while(scanf("%d %d %d",&n,&m,&q) && (n||m||q)){
for(int i=1;i<=n;i++){
pai[i] = i;
dfs_low[i] = dfs_num[i] = dfs_parent[i] = pontosdearticulacao[i] = 0;
grafo[i].clear();
}
dfsNumberCounter = 0;
while(m--){
int u,v;
scanf("%d %d",&u,&v);
grafo[u].push_back(v);
grafo[v].push_back(u);
}
for(int i=1;i<=n;i++){
if(dfs_num[i] == 0){
dfsRoot = i;
dfsRootChildren = 0;
dfs(i);
pontosdearticulacao[i] = (dfsRootChildren > 1);
}
}
while(q--){
int u,v;
scanf("%d %d",&u,&v);
printf("%c\n",find(u) == find(v) ? 'Y' : 'N');
}
printf("-\n");
}
return 0;
}
| 22.821918 | 132 | 0.57503 | Ashwanigupta9125 |
d6fae5859b1906929543bf4d4b27827b90a8394e | 6,962 | cpp | C++ | source/JsMaterialX/JsMaterialXCore/JsDocument.cpp | sdunkel/MaterialX | e76a27d01be379929b9adb3cad6d89aa570511ab | [
"BSD-3-Clause"
] | 1 | 2021-11-20T20:56:27.000Z | 2021-11-20T20:56:27.000Z | source/JsMaterialX/JsMaterialXCore/JsDocument.cpp | testpassword/MaterialX | 7c69782196b11fa43c67aee0707801983bb81e6c | [
"BSD-3-Clause"
] | null | null | null | source/JsMaterialX/JsMaterialXCore/JsDocument.cpp | testpassword/MaterialX | 7c69782196b11fa43c67aee0707801983bb81e6c | [
"BSD-3-Clause"
] | null | null | null | //
// TM & (c) 2021 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd.
// All rights reserved. See LICENSE.txt for license.
//
#include "../VectorHelper.h"
#include "../Helpers.h"
#include <MaterialXCore/Document.h>
#include <emscripten/bind.h>
namespace ems = emscripten;
namespace mx = MaterialX;
EMSCRIPTEN_BINDINGS(document)
{
ems::function("createDocument", &mx::createDocument);
ems::class_<mx::Document, ems::base<mx::GraphElement>>("Document")
.smart_ptr_constructor("Document", &std::make_shared<mx::Document, mx::ElementPtr, const std::string &>)
.smart_ptr<std::shared_ptr<const mx::Document>>("Document")
// At the moment only the Document type is used. Once more types are added this binding needs to be adapted accordingly.
.class_function("createDocument", &mx::Document::createDocument<mx::Document>)
.function("initialize", &mx::Document::initialize)
.function("copy", &mx::Document::copy)
.function("importLibrary", &mx::Document::importLibrary)
.function("getReferencedSourceUris", ems::optional_override([](mx::Document &self) {
mx::StringSet set = self.getReferencedSourceUris();
return ems::val::array(set.begin(), set.end());
}))
BIND_MEMBER_FUNC("addNodeGraph", mx::Document, addNodeGraph, 0, 1, stRef)
.function("getNodeGraph", &mx::Document::getNodeGraph)
.function("getNodeGraphs", &mx::Document::getNodeGraphs)
.function("removeNodeGraph", &mx::Document::removeNodeGraph)
.function("getMatchingPorts", &mx::Document::getMatchingPorts)
BIND_MEMBER_FUNC("addGeomInfo", mx::Document, addGeomInfo, 0, 2, stRef, stRef)
.function("getGeomInfo", &mx::Document::getGeomInfo)
.function("getGeomInfos", &mx::Document::getGeomInfos)
.function("removeGeomInfo", &mx::Document::removeGeomInfo)
BIND_MEMBER_FUNC("getGeomPropValue", mx::Document, getGeomPropValue, 1, 2, stRef, stRef)
.function("addGeomPropDef", &mx::Document::addGeomPropDef)
.function("getGeomPropDef", &mx::Document::getGeomPropDef)
.function("getGeomPropDefs", &mx::Document::getGeomPropDefs)
.function("removeGeomPropDef", &mx::Document::removeGeomPropDef)
BIND_MEMBER_FUNC("addLook", mx::Document, addLook, 0, 1, stRef)
.function("getLook", &mx::Document::getLook)
.function("getLooks", &mx::Document::getLooks)
.function("removeLook", &mx::Document::removeLook)
.function("mergeLooks", &mx::Document::mergeLooks)
BIND_MEMBER_FUNC("addLookGroup", mx::Document, addLookGroup, 0, 1, stRef)
.function("getLookGroup", &mx::Document::getLookGroup)
.function("getLookGroups", &mx::Document::getLookGroups)
.function("removeLookGroup", &mx::Document::removeLookGroup)
BIND_MEMBER_FUNC("addCollection", mx::Document, addCollection, 0, 1, stRef)
.function("getCollection", &mx::Document::getCollection)
.function("getCollections", &mx::Document::getCollections)
.function("removeCollection", &mx::Document::removeCollection)
.function("addTypeDef", &mx::Document::addTypeDef)
.function("getTypeDef", &mx::Document::getTypeDef)
.function("getTypeDefs", &mx::Document::getTypeDefs)
.function("removeTypeDef", &mx::Document::removeTypeDef)
BIND_MEMBER_FUNC("addNodeDef", mx::Document, addNodeDef, 0, 3, stRef, stRef, stRef)
BIND_MEMBER_FUNC("addNodeDefFromGraph", mx::Document, addNodeDefFromGraph, 7, 8, const mx::NodeGraphPtr,
stRef, stRef, stRef, bool, stRef, std::string, stRef)
.function("getNodeDef", &mx::Document::getNodeDef)
.function("getNodeDefs", &mx::Document::getNodeDefs)
.function("removeNodeDef", &mx::Document::removeNodeDef)
.function("getMatchingNodeDefs", &mx::Document::getMatchingNodeDefs)
BIND_MEMBER_FUNC("addAttributeDef", mx::Document, addAttributeDef, 0, 1, stRef)
.function("getAttributeDef", &mx::Document::getAttributeDef)
.function("getAttributeDefs", &mx::Document::getAttributeDefs)
.function("removeAttributeDef", &mx::Document::removeAttributeDef)
BIND_MEMBER_FUNC("addTargetDef", mx::Document, addTargetDef, 0, 1, stRef)
.function("getTargetDef", &mx::Document::getTargetDef)
.function("getTargetDefs", &mx::Document::getTargetDefs)
.function("removeTargetDef", &mx::Document::removeTargetDef)
BIND_MEMBER_FUNC("addPropertySet", mx::Document, addPropertySet, 0, 1, stRef)
.function("getPropertySet", &mx::Document::getPropertySet)
.function("getPropertySets", &mx::Document::getPropertySets)
.function("removePropertySet", &mx::Document::removePropertySet)
BIND_MEMBER_FUNC("addVariantSet", mx::Document, addVariantSet, 0, 1, stRef)
.function("getVariantSet", &mx::Document::getVariantSet)
.function("getVariantSets", &mx::Document::getVariantSets)
.function("removeVariantSet", &mx::Document::removeVariantSet)
BIND_MEMBER_FUNC("addImplementation", mx::Document, addImplementation, 0, 1, stRef)
.function("getImplementation", &mx::Document::getImplementation)
.function("getImplementations", &mx::Document::getImplementations)
.function("removeImplementation", &mx::Document::removeImplementation)
.function("getMatchingImplementations", &mx::Document::getMatchingImplementations)
.function("addUnitDef", &mx::Document::addUnitDef)
.function("getUnitDef", &mx::Document::getUnitDef)
.function("getUnitDefs", &mx::Document::getUnitDefs)
.function("removeUnitDef", &mx::Document::removeUnitDef)
.function("addUnitTypeDef", &mx::Document::addUnitTypeDef)
.function("getUnitTypeDef", &mx::Document::getUnitTypeDef)
.function("getUnitTypeDefs", &mx::Document::getUnitTypeDefs)
.function("removeUnitTypeDef", &mx::Document::removeUnitTypeDef)
.function("getVersionIntegers", &mx::Document::getVersionIntegers)
.function("upgradeVersion", &mx::Document::upgradeVersion)
.function("setColorManagementSystem", &mx::Document::setColorManagementSystem)
.function("hasColorManagementSystem", &mx::Document::hasColorManagementSystem)
.function("getColorManagementSystem", &mx::Document::getColorManagementSystem)
.function("setColorManagementConfig", &mx::Document::setColorManagementConfig)
.function("hasColorManagementConfig", &mx::Document::hasColorManagementConfig)
.function("getColorManagementConfig", &mx::Document::getColorManagementConfig)
.function("invalidateCache", &mx::Document::invalidateCache)
.class_property("CATEGORY", &mx::Document::CATEGORY)
.class_property("CMS_ATTRIBUTE", &mx::Document::CMS_ATTRIBUTE)
.class_property("CMS_CONFIG_ATTRIBUTE", &mx::Document::CMS_CONFIG_ATTRIBUTE);
}
| 62.720721 | 132 | 0.692473 | sdunkel |
d6fbb97f3a224763185abd6812a6916e1e34a265 | 3,113 | cpp | C++ | Testing/Backend/auxiliary_resolver.cpp | uscope-platform/makefile_gen | 06bd4405afbbd9584911f495ebefff828f05aa0d | [
"Apache-2.0"
] | null | null | null | Testing/Backend/auxiliary_resolver.cpp | uscope-platform/makefile_gen | 06bd4405afbbd9584911f495ebefff828f05aa0d | [
"Apache-2.0"
] | null | null | null | Testing/Backend/auxiliary_resolver.cpp | uscope-platform/makefile_gen | 06bd4405afbbd9584911f495ebefff828f05aa0d | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Filippo Savi
// Author: Filippo Savi <filssavi@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include "data_model/data_store.h"
#include "Backend/Auxiliary_resolver.h"
class aux_resolver : public ::testing::Test {
protected:
void SetUp() {
d_store = std::make_shared<data_store>(true);
Script s1_spec("python_test", "py");
s1_spec.set_path("/tests/script.py");
d_store->store_script(s1_spec);
Script s2_spec("tcl_test", "tcl");
s2_spec.set_path("/tests/tcl_test.tcl");
d_store->store_script(s2_spec);
Constraints c("test_constr");
c.set_path("/test/constraints.xdc");
d_store->store_constraint(c);
}
virtual void TearDown() {
}
std::shared_ptr<data_store> d_store;
};
TEST_F(aux_resolver, get_py_obj){
Auxiliary_resolver res(d_store);
Script s1("python_test", "py");
s1.set_arguments({"arg1", "arg2", "arg3"});
s1.set_product(true, "test.tcl");
auto result = res.get_python_objects({s1});
Script s1_check("python_test", "py");
s1_check.set_path("/tests/script.py");
s1_check.set_arguments({"arg1", "arg2", "arg3"});
s1_check.set_product(true, "test.tcl");
ASSERT_EQ(result[0], s1_check);
}
TEST_F(aux_resolver, get_python_path){
Auxiliary_resolver res(d_store);
Script s1("python_test", "py");
s1.set_arguments({"arg1", "arg2", "arg3"});
s1.set_product(true, "test.tcl");
auto result = res.get_python_script_paths({s1});
std::unordered_set<std::string> check = {"/tests/script.py"};
ASSERT_EQ(result, check);
}
TEST_F(aux_resolver, get_tcl_script){
Auxiliary_resolver res(d_store);
Script s1("tcl_test", "tcl");
s1.set_arguments({"arg1", "arg2", "arg3"});
auto result = res.get_tcl_objects({s1});
Script s2_check("tcl_test", "tcl");
s2_check.set_path("/tests/tcl_test.tcl");
s2_check.set_arguments({"arg1", "arg2", "arg3"});
ASSERT_EQ(result[0], s2_check);
}
TEST_F(aux_resolver, get_tcl_path){
Auxiliary_resolver res(d_store);
Script s1("tcl_test", "tcl");
s1.set_arguments({"arg1", "arg2", "arg3"});
auto result = res.get_tcl_script_paths({s1});
std::unordered_set<std::string> check = {"/tests/tcl_test.tcl"};
ASSERT_EQ(result, check);
}
TEST_F(aux_resolver, get_constraints){
Auxiliary_resolver res(d_store);
Constraints c("test_constr");
auto result = res.get_constraints({c});
std::unordered_set<std::string> check = {"/test/constraints.xdc"};
ASSERT_EQ(result, check);
} | 29.093458 | 75 | 0.673627 | uscope-platform |
d6fcb97a5580e130b76fe3944853ae93cd1b1ceb | 1,314 | cpp | C++ | object_recognition/src/object.cpp | Birkehoj/vis3 | 70e71f1763a8818680bc9eea8d5fc041d4ec8075 | [
"BSD-2-Clause"
] | 2 | 2015-11-11T12:39:26.000Z | 2021-07-04T13:16:30.000Z | object_recognition/src/object.cpp | Birkehoj/vis3 | 70e71f1763a8818680bc9eea8d5fc041d4ec8075 | [
"BSD-2-Clause"
] | null | null | null | object_recognition/src/object.cpp | Birkehoj/vis3 | 70e71f1763a8818680bc9eea8d5fc041d4ec8075 | [
"BSD-2-Clause"
] | 2 | 2017-04-04T13:47:28.000Z | 2019-05-14T14:30:11.000Z | #include "object.h"
#include <pcl/io/obj_io.h>
#include <fstream>
using std::ifstream;
Object::Object(const std::string& object_folder_path, const std::string& file_name)
: Feature_cloud(file_name.substr(0,file_name.find_last_of(".")))
{
CloudT::Ptr xyz(new CloudT);
pcl::io::loadOBJFile<PointT>(object_folder_path+"/" + file_name, *xyz);
for (pcl::PointCloud<PointT>::iterator i = xyz->begin(); i != xyz->end(); i++)
{
i->z *= mm_to_m_factor; i->y *= mm_to_m_factor; i->x *= mm_to_m_factor;
}
computeFeatures(xyz);
setGrasps(object_folder_path);
}
void Object::setGrasps(const string& object_folder_path)
{
const string grasp_folder_name = "grasps";
string grasp_file_path = object_folder_path + '/' + grasp_folder_name + '/' + name + ".txt";
cout << "loading grasps from: " << grasp_file_path << endl;
std::ifstream fs(grasp_file_path.c_str());
if(fs.is_open())
{
while(fs.good())
{
Eigen::Matrix4f grasp;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
fs >> grasp(i,j);
}
}
//cout << endl << name << "'s grasp = " << endl << grasp << endl;
grasps.push_back(grasp);
}
grasps.pop_back(); // one too much added??
fs.close();
}
else {
PCL_ERROR("Unable to open grasp file\n");
}
}
| 29.863636 | 94 | 0.611872 | Birkehoj |
d90096bf47ed042bbdd91a0f413286d866c6394d | 9,033 | cpp | C++ | lite/mach.cpp | richardkchapman/nlp-engine | 393d9f2b6352f6c41c3aa79ed5f7075cd93950c4 | [
"MIT"
] | 3 | 2021-01-08T19:14:43.000Z | 2021-06-08T04:52:22.000Z | lite/mach.cpp | richardkchapman/nlp-engine | 393d9f2b6352f6c41c3aa79ed5f7075cd93950c4 | [
"MIT"
] | 62 | 2020-06-04T02:37:12.000Z | 2022-03-12T12:43:39.000Z | lite/mach.cpp | richardkchapman/nlp-engine | 393d9f2b6352f6c41c3aa79ed5f7075cd93950c4 | [
"MIT"
] | 7 | 2019-07-18T19:58:27.000Z | 2022-02-02T13:21:20.000Z | /*******************************************************************************
Copyright (c) 2001-2010 by Text Analysis International, Inc.
All rights reserved.
********************************************************************************
*
* NAME: MACH.CPP
* FILE: lite\mach.cpp
* CR: 10/29/98 AM.
* SUBJ: Things that may be machine specific.
*
*******************************************************************************/
#include "StdAfx.h"
#include <time.h>
#ifndef LINUX
#include <direct.h>
#endif
#include <sys/types.h> // WORKAROUND. // 02/25/00 AM.
#include <sys/timeb.h> // WORKAROUND. // 02/25/00 AM.
#include "machine.h" // 10/25/06 AM.
#include "prim/libprim.h" // 01/24/06 AM.
#include "u_out.h" // 01/24/06 AM.
#include "lite/global.h"
#include "inline.h" // 09/26/01 AM.
#include "lite/mach.h"
#include "lite/dir.h"
/********************************************
* FN: TODAY
* CR: 10/29/98 AM.
* SUBJ: Get the current date and time.
* NOTE: Annoying that ctime includes a carriage return at end of string.
********************************************/
LITE_API _TCHAR *today()
{
static _TCHAR buf[64];
_TCHAR *tptr; // Debugging mem leak. // 02/25/00 AM.
time_t ltime;
struct tm *newtime; // FIX MEM LEAK!! // 02/25/00 AM.
time(<ime);
newtime = localtime(<ime); // TRYING. // 02/25/00 AM.
tptr = _tasctime(newtime); // TRYING. // 02/25/00 AM.
//tptr = ctime(<ime); // 02/25/00 AM.
_tcscpy(buf, tptr); // 02/25/00 AM.
_TCHAR *ptr;
ptr = _tcschr(buf, '\n');
if (ptr)
*ptr = '\0'; // Wipe out first newline.
return buf;
}
/**************************************************
* DATE_STR
* FUN: date_str
* SUBJ: Get current date-time, nicely formatted.
* CR: 10/7/95 AM.
* RET: str - formatted date-time.
* NOTE: 04/20/99 AM. Taken from LIBPRIM (Consh&Conan), so as to remove
* the mach.cpp file from that library.
*
**************************************************/
LITE_API void
date_str(
_TCHAR str[], /* Buffer to fill with date-time. */
int siz /* Max size of buffer. */
)
{
time_t now;
struct tm *date;
/* Get the current calendar time. */
time(&now);
/* Break down time. */
date = localtime(&now);
/* Convert to string. */
_tcsftime(str, siz, _T("%x %H:%M"), date);
}
/********************************************
* FN: DOSREADARGS
* CR: 11/30/98 AM.
* SUBJ: Get command line arguments.
* RET: True if ok read, else false if failed.
********************************************/
LITE_API bool dosReadargs(
int argc,
_TCHAR *argv[],
/*UP*/
_TCHAR* &input, // Input file from args.
_TCHAR* &output, // Output file from args.
bool &develop, // Development mode (output intermediate files).
bool &compiled // true - compiled ana. false=interp(DEFAULT).
)
{
_TCHAR *ptr;
_TCHAR **parg;
bool f_in = false;
bool f_out = false;
bool flag = false;
bool compiledck = false; // If compiled/interp arg seen. // 07/05/00 AM.
input = output = 0;
develop = false; // Default is not development mode. // 12/25/98 AM.
compiled = false; // INTERP ANALYZER BY DEFAULT. // 07/05/00 AM.
for (--argc, parg = &(argv[1]); argc > 0; --argc, ++parg)
{
// For each command line argument.
//*gout << "command arg=" << *parg << endl;
ptr = *parg;
if (*ptr == '/' || *ptr == '-') // DOS or UNIX style arg.
{
if (flag)
{
_t_strstream gerrStr;
gerrStr << _T("[Error in command line args for ") << argv[0]
<< _T("]") << ends;
errOut(&gerrStr,false);
return false;
}
++ptr;
if (!strcmp_i(ptr, _T("in")))
f_in = flag = true; // Expecting input file.
else if (!strcmp_i(ptr, _T("out")))
f_out = flag = true; // Expecting output file.
else if (!strcmp_i(ptr, _T("dev"))) // 12/25/98 AM.
develop = true; // Development mode.
else if (!strcmp_i(ptr, _T("interp"))) // Run interpreted analyzer.
{
if (compiledck)
{
_t_strstream gerrStr;
gerrStr << _T("[Ignoring extra /compiled or /interp flag.]") << ends;
errOut(&gerrStr,false);
}
else
{
compiledck = true;
compiled = false;
}
}
else if (!strcmp_i(ptr, _T("compiled"))) // Run compiled analyzer.
{
if (compiledck)
{
_t_strstream gerrStr;
gerrStr << _T("[Ignoring extra /compiled or /interp flag.]") << ends;
errOut(&gerrStr,false);
}
else
{
compiledck = true;
compiled = true;
}
}
}
else if (flag) // Expected an argument value.
{
if (f_in)
{
if (input)
{
_t_strstream gerrStr;
gerrStr << _T("[") << argv[0] << _T(": Input file specified twice.]")
<< ends;
errOut(&gerrStr,false);
dosHelpargs(argv[0]);
return false;
}
// Grab value as input file.
input = ptr;
f_in = flag = false;
}
else if (f_out)
{
if (output)
{
_t_strstream gerrStr;
gerrStr << _T("[") << argv[0]
<< _T(": Output file specified twice.]") << ends;
errOut(&gerrStr,false);
dosHelpargs(argv[0]);
return false;
}
// Grab value as output file.
output = ptr;
f_out = flag = false;
}
}
else // Got a "floating" value.
{
if (input && output)
{
_t_strstream gerrStr;
gerrStr << _T("[") << argv[0] << _T(": Extra arguments.]") << ends;
errOut(&gerrStr,false);
dosHelpargs(argv[0]);
return false;
}
else if (input)
output = ptr;
else
input = ptr;
}
}
return true;
}
/********************************************
* FN: DOSHELPARGS
* CR: 11/30/98 AM.
* SUBJ: Print command line argument help.
* RET: True if ok read, else false if failed.
********************************************/
LITE_API void dosHelpargs(_TCHAR *name)
{
_t_cout << name
<< _T(" [/INTERP][/COMPILED][/IN infile] [/OUT outfile] [/DEV] [infile [outfile]]")
<< endl
<< _T("Note: /INTERP, the interpreted analyzer, is default.")
<< endl;
}
////////////////////////////////////////////////////////////
#ifdef TIMING_REFERENCE_
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void _tmain( void ){
time_t start, finish;
long loop;
double result, elapsed_time;
_tprintf( _T("Multiplying 2 floating point numbers 10 million times...\n") );
time( &start );
for( loop = 0; loop < 10000000; loop++ )
result = 3.63 * 5.27;
time( &finish );
elapsed_time = difftime( finish, start );
_tprintf( _T("\nProgram takes %6.0f seconds.\n"), elapsed_time );
}
#endif
////////////////////////////////////////////////////////////////
/********************************************
* FN: DIR_EXISTS
* CR: 03/10/99 AM.
* SUBJ: See if given directory exists.
* RET: True if exists.
* OPT: Probably not the most efficient or principled method.
********************************************/
LITE_API bool dir_exists(_TCHAR *name)
{
_TCHAR cwd[MAXSTR];
/* Get the current working directory: */
#ifndef LINUX
if(_tgetcwd( cwd, MAXSTR) == NULL)
{
_t_strstream gerrStr;
gerrStr << _T("[dir_exists: Couldn't get working dir.]") << ends;
errOut(&gerrStr,false);
return false;
}
if(_tchdir(name))
return false;
// Was able to change to it. Now change back.
_tchdir(cwd);
#endif
return true;
}
/********************************************
* FN: MAKE_DIR
* CR: 03/10/99 AM.
* SUBJ: Make given directory.
* RET: True if exists.
* OPT: Probably not the most efficient or principled method.
********************************************/
LITE_API bool make_dir(_TCHAR *name)
{
#ifndef LINUX
if(_tmkdir(name) == 0)
return true;
#endif
return false;
}
/********************************************
* FN: RM_DIR
* CR: 03/10/99 AM.
* SUBJ: Remove given directory. Must be empty.
* RET: True if exists.
* OPT: Probably not the most efficient or principled method.
********************************************/
LITE_API bool rm_dir(_TCHAR *name)
{
#ifndef LINUX
if(_trmdir(name) == 0)
return true;
#endif
return false;
}
/********************************************
* FN: REMOVE_PATH
* CR: 03/10/99 AM.
* SUBJ: Remove given path.
* RET: True if success.
* NOTE: Remove file or remove directory.
********************************************/
LITE_API bool remove_path(_TCHAR *name)
{
if (!safe_dir(name))
return false;
if(_tremove(name) == 0)
return true;
return false;
}
/********************************************
* FN: TODAY1
* CR: 02/25/00 AM.
* SUBJ: Get the current date and time.
* NOTE: Trying workaround to spurious error message from Purify 6.5,
* about memory leak in asctime when that fn is in a dll.
********************************************/
LITE_API _TCHAR *today1()
{
static _TCHAR buf[256];
_TCHAR tmpbuf1[128], tmpbuf2[128];
/* Set time zone from TZ environment variable. If TZ is not set,
* the operating system is queried to obtain the default value
* for the variable.
*/
#ifndef LINUX
_tzset();
/* Display operating system-style date and time. */
_tstrtime( tmpbuf1 );
_tstrdate( tmpbuf2 );
_stprintf(buf, _T("%s %s"), tmpbuf1, tmpbuf2);
return buf;
#else
return today();
#endif
}
| 24.217158 | 83 | 0.539577 | richardkchapman |
d901c987854d1faa741cf947dd691b10ca83570a | 2,604 | cpp | C++ | Board.cpp | Stav-Nof/-messageboard-b | ef98415c0aca9c8c3472a96a8970be092749990e | [
"MIT"
] | null | null | null | Board.cpp | Stav-Nof/-messageboard-b | ef98415c0aca9c8c3472a96a8970be092749990e | [
"MIT"
] | null | null | null | Board.cpp | Stav-Nof/-messageboard-b | ef98415c0aca9c8c3472a96a8970be092749990e | [
"MIT"
] | null | null | null | #include "Board.hpp"
#include <iostream>
#include <string>
#include <array>
#include <limits.h>
#include <stdexcept>
#include <map>
using namespace std;
namespace ariel{
unsigned int max_colums;
unsigned int min_colums;
unsigned int max_row;
unsigned int min_row;
Board::Board(){
min_row = INT_MAX;
max_row = 0;
min_colums = INT_MAX;
max_colums = 0;
}
void Board::post(unsigned int row, unsigned int column, enum Direction d, const string &s){
if (d == Direction::Horizontal){
for(unsigned int i=0; i<s.length(); i++){
b[row][column + i] = s[i];
}
min_row = min(min_row,row);
max_row = max(max_row,row);
min_colums = min(min_colums,column);
max_colums = max((column + unsigned(s.length())), max_colums);
}
else
{
for(unsigned int i=0; i<s.length(); i++)
{
b[row + i][column] = s[i];
}
min_row = min(min_row,row);
max_row = max((row + unsigned(s.length())), max_row);
min_colums = min(min_colums,column);
max_colums = max(min_colums,column);
}
}
string Board::read(unsigned int row, unsigned int column , enum Direction d, unsigned int num){
string ans;
for(unsigned int i=0; i<num; i++)
{
if (d == Direction::Horizontal)
{
if(b[row][column+i] == 0)
{
ans += "_";
}
else
{
ans += b[row][column+i];
}
}
else
{
if(b[row+i][column] == 0)
{
ans += "_";
}
else
{
ans += b[row+i][column];
}
}
}
return ans;
}
void Board::show(){
unsigned int display_rows = (max_row - min_row) + 1;
unsigned int display_cols = (max_colums - min_colums);
for(unsigned int i = 0; i<display_rows; i++) {
for(unsigned int j = 0; j<display_cols; j++)
{
if(b[i][j] != 0)
{
cout << b[i][j];
}
else
{
cout << "_";
}
}
cout << endl;
}
}
Board::~Board(){
}
} | 25.782178 | 99 | 0.409754 | Stav-Nof |
d902f59288b89d7e73930197565603c8cce54a72 | 1,243 | cpp | C++ | HANGCAYMAXMIN.cpp | phuongnam2002/testlib | a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa | [
"MIT"
] | 2 | 2022-01-14T13:34:09.000Z | 2022-02-21T07:27:29.000Z | HANGCAYMAXMIN.cpp | phuongnam2002/testlib | a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa | [
"MIT"
] | null | null | null | HANGCAYMAXMIN.cpp | phuongnam2002/testlib | a5cb8e2be7ac7a7e7dca7942a79ec20076f5d1aa | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int ssXau (string a, string b)
{
while (1)
{
if (a.length()==b.length()) break;
if (a.length()>b.length()) b='0'+b;
else a='0'+a;
}
for (int i=0; i<a.length(); i++)
{
int soA=a[i]-'0';
int soB=b[i]-'0';
if (soA>soB) return 1;
else if (soA<soB) return -1;
}
return 0;
}
string chXau (string a)
{
int vt=-1;
for (int i=0; i<a.length(); i++)
{
if (a[i]!='0')
{
vt=i;
break;
}
}
if (vt==-1) return "0";
else
{
string b="";
for (int i=vt; i<a.length(); i++)
{
b+=a[i];
}
return b;
}
} //chuan hoa xau->
int main ()
{
int N;
int t=0;
while (1)
{
cin>>N;
if (N==0) break;
t++;
string Min="", Max="";
string a;
int kt=0;
for (int i=1; i<=N; i++)
{
cin>>a;
if (i==1)
{
Min=a;
Max=a;
}
else
{
if (ssXau (a, Max)==1)
{
Max=a;
kt=1;
}
if (ssXau (a, Min)==-1)
{
Min=a;
kt=1;
}
}
}
if (kt==1) cout<<"Case "<<t<<": "<<chXau (Min)<<" "<<chXau(Max)<<endl;
else cout<<"Case "<<t<<": "<<"There is a row of trees having equal height."<<endl;
}
return 0;
}
| 14.453488 | 85 | 0.43041 | phuongnam2002 |
d90b701176a4b0010470310f7743f9263b20b028 | 5,237 | hpp | C++ | src/xalanc/XSLT/ElemUse.hpp | kidaa/xalan-c | bb666d0ab3d0a192410823e6857c203d83c27b16 | [
"Apache-2.0"
] | null | null | null | src/xalanc/XSLT/ElemUse.hpp | kidaa/xalan-c | bb666d0ab3d0a192410823e6857c203d83c27b16 | [
"Apache-2.0"
] | 1 | 2021-08-18T12:32:31.000Z | 2021-08-18T12:32:31.000Z | src/xalanc/XSLT/ElemUse.hpp | AaronNGray/xalan | 6741bbdcb64a9d33df8bd7e21b558d66bb4292ec | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALAN_ELEMUSE_HEADER_GUARD)
#define XALAN_ELEMUSE_HEADER_GUARD
// Base include file. Must be first.
#include "XSLTDefinitions.hpp"
// Base class header file.
#include "ElemTemplateElement.hpp"
XALAN_CPP_NAMESPACE_BEGIN
class ElemUse : public ElemTemplateElement
{
public:
#if defined(XALAN_STRICT_ANSI_HEADERS)
typedef std::size_t size_type;
#else
typedef size_t size_type;
#endif
/**
* Construct an object corresponding to an "use-attribute-sets" attribute.
* This is a base class for "xsl:element," "xsl:copy" and
* "xsl:attribute-set" elements, which may specify attribute sets to use.
*
* @param constructionContext context for construction of object
* @param stylesheetTree stylesheet containing element
* @param atts list of attributes for element
* @param lineNumber line number in document
* @param columnNumber column number in document
*/
ElemUse(
StylesheetConstructionContext& constructionContext,
Stylesheet& stylesheetTree,
XalanFileLoc lineNumber,
XalanFileLoc columnNumber,
int xslToken);
virtual
~ElemUse();
/**
* See if this is a use-attribute-sets attribute, and, if so, process it.
*
* @param attrName qualified name of attribute
* @param atts attribute list where the element comes from (not used at
* this time)
* @param which index into the attribute list (not used at this time)
* @return true if this is a use-attribute-sets attribute
*/
bool
processUseAttributeSets(
StylesheetConstructionContext& constructionContext,
const XalanDOMChar* attrName,
const AttributeListType& atts,
XalanSize_t which);
// These methods are inherited from ElemTemplateElement ...
virtual const XalanDOMString&
getElementName() const;
virtual void
postConstruction(
StylesheetConstructionContext& constructionContext,
const NamespacesHandler& theParentHandler);
#if !defined(XALAN_RECURSIVE_STYLESHEET_EXECUTION)
virtual const ElemTemplateElement*
startElement(StylesheetExecutionContext& executionContext) const;
virtual void
endElement(StylesheetExecutionContext& executionContext) const;
virtual const ElemTemplateElement*
getNextChildElemToExecute(
StylesheetExecutionContext& executionContext,
const ElemTemplateElement* currentElem) const;
virtual const ElemTemplateElement*
getFirstChildElemToExecute(
StylesheetExecutionContext& executionContext) const;
#else
virtual void
execute(StylesheetExecutionContext& executionContext) const;
#endif
protected:
#if !defined(XALAN_RECURSIVE_STYLESHEET_EXECUTION)
/**
* Get the next attribute set to execute.
*
* @param executionContext context to execute this element
* @returns a pointer to the attribute set element, 0 if no more attribute sets
*/
const ElemTemplateElement*
getNextAttributeSet(
StylesheetExecutionContext& executionContext) const;
/**
* Evalute the AVTs for this element
*
* @param executionContext context to execute this element
*/
virtual void
evaluateAVTs(
StylesheetExecutionContext& executionContext) const;
#else
/**
* Execute and conditionally apply any attribute sets. To be used
* by deriving classes who want ElemUse to do any default execution
* but skip applying attribute sets. Typically, this would be done
* when attempting to recover from an error.
*
* @param executionContext The current execution context.
* @param applyAttributeSets If true, attribute sets will be applied.
*/
virtual void
doExecute(
StylesheetExecutionContext& executionContext,
bool applyAttributeSets) const;
#endif
private:
const XalanQName** m_attributeSetsNames;
size_type m_attributeSetsNamesCount;
};
XALAN_CPP_NAMESPACE_END
#endif // XALAN_ELEMUSE_HEADER_GUARD
| 31.548193 | 84 | 0.670422 | kidaa |
d90bb62d1d39d1ff072ddb6bede4fe8c7ad1370b | 9,338 | cpp | C++ | src/systemcmds/esc_calib/esc_calib.cpp | iamarkaj/PX4-Autopilot | 77b65ee5640ee46142a22e716126c0777c964bd9 | [
"BSD-3-Clause"
] | 1,537 | 2020-10-28T17:49:02.000Z | 2022-03-31T13:55:38.000Z | src/systemcmds/esc_calib/esc_calib.cpp | iamarkaj/PX4-Autopilot | 77b65ee5640ee46142a22e716126c0777c964bd9 | [
"BSD-3-Clause"
] | 2,514 | 2020-10-28T17:49:10.000Z | 2022-03-31T17:47:22.000Z | src/systemcmds/esc_calib/esc_calib.cpp | iamarkaj/PX4-Autopilot | 77b65ee5640ee46142a22e716126c0777c964bd9 | [
"BSD-3-Clause"
] | 1,945 | 2020-10-28T18:14:05.000Z | 2022-03-31T23:15:37.000Z | /****************************************************************************
*
* Copyright (C) 2013 PX4 Development Team. All rights reserved.
* Author: Julian Oes <joes@student.ethz.ch>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file esc_calib.c
*/
#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/getopt.h>
#include <px4_platform_common/module.h>
#include <px4_platform_common/defines.h>
#include <px4_platform_common/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/mount.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include "drivers/drv_pwm_output.h"
#include <uORB/topics/actuator_controls.h>
static void usage(const char *reason)
{
if (reason != nullptr) {
PX4_ERR("%s", reason);
}
PRINT_MODULE_DESCRIPTION("Tool for ESC calibration\n"
"\n"
"Calibration procedure (running the command will guide you through it):\n"
"- Remove props, power off the ESC's\n"
"- Stop attitude and rate controllers: mc_rate_control stop, fw_att_control stop\n"
"- Make sure safety is off\n"
"- Run this command\n"
);
PRINT_MODULE_USAGE_NAME_SIMPLE("esc_calib", "command");
PRINT_MODULE_USAGE_PARAM_STRING('d', "/dev/pwm_output0", "<file:dev>", "Select PWM output device", true);
PRINT_MODULE_USAGE_PARAM_INT('l', 1000, 0, 3000, "Low PWM value in us", true);
PRINT_MODULE_USAGE_PARAM_INT('h', 2000, 0, 3000, "High PWM value in us", true);
PRINT_MODULE_USAGE_PARAM_STRING('c', nullptr, nullptr,
"select channels in the form: 1234 (1 digit per channel, 1=first)", true);
PRINT_MODULE_USAGE_PARAM_INT('m', -1, 0, 4096, "Select channels via bitmask (eg. 0xF, 3)", true);
PRINT_MODULE_USAGE_PARAM_FLAG('a', "Select all channels", true);
}
extern "C" __EXPORT int esc_calib_main(int argc, char *argv[])
{
const char *dev = PWM_OUTPUT0_DEVICE_PATH;
char *ep;
int ch;
int ret;
char c;
unsigned max_channels = 0;
uint32_t set_mask = 0;
unsigned long channels;
unsigned single_ch = 0;
uint16_t pwm_high = PWM_DEFAULT_MAX;
uint16_t pwm_low = PWM_DEFAULT_MIN;
struct pollfd fds;
fds.fd = 0; /* stdin */
fds.events = POLLIN;
if (argc < 2) {
usage("no channels provided");
return 1;
}
int myoptind = 1;
const char *myoptarg = nullptr;
while ((ch = px4_getopt(argc, argv, "d:c:m:al:h:", &myoptind, &myoptarg)) != EOF) {
switch (ch) {
case 'd':
dev = myoptarg;
break;
case 'c':
/* Read in channels supplied as one int and convert to mask: 1234 -> 0xF */
channels = strtoul(myoptarg, &ep, 0);
while ((single_ch = channels % 10)) {
set_mask |= 1 << (single_ch - 1);
channels /= 10;
}
break;
case 'm':
/* Read in mask directly */
set_mask = strtoul(myoptarg, &ep, 0);
if (*ep != '\0') {
usage("bad set_mask value");
return 1;
}
break;
case 'a':
/* Choose all channels */
for (unsigned i = 0; i < PWM_OUTPUT_MAX_CHANNELS; i++) {
set_mask |= 1 << i;
}
break;
case 'l':
/* Read in custom low value */
pwm_low = strtoul(myoptarg, &ep, 0);
if (*ep != '\0'
#if PWM_LOWEST_MIN > 0
|| pwm_low < PWM_LOWEST_MIN
#endif
|| pwm_low > PWM_HIGHEST_MIN) {
usage("low PWM invalid");
return 1;
}
break;
case 'h':
/* Read in custom high value */
pwm_high = strtoul(myoptarg, &ep, 0);
if (*ep != '\0' || pwm_high > PWM_HIGHEST_MAX || pwm_high < PWM_LOWEST_MAX) {
usage("high PWM invalid");
return 1;
}
break;
default:
usage(nullptr);
return 1;
}
}
if (set_mask == 0) {
usage("no channels chosen");
return 1;
}
if (pwm_low > pwm_high) {
usage("low pwm is higher than high pwm");
return 1;
}
/* make sure no other source is publishing control values now */
struct actuator_controls_s actuators;
int act_sub = orb_subscribe(ORB_ID(actuator_controls_0));
/* clear changed flag */
orb_copy(ORB_ID(actuator_controls_0), act_sub, &actuators);
/* wait 50 ms */
px4_usleep(50000);
/* now expect nothing changed on that topic */
bool orb_updated;
orb_check(act_sub, &orb_updated);
if (orb_updated) {
PX4_ERR("ABORTING! Attitude control still active. Please ensure to shut down all controllers:\n"
"\tmc_rate_control stop\n"
"\tfw_att_control stop\n");
return 1;
}
printf("\nATTENTION, please remove or fix propellers before starting calibration!\n"
"\n"
"Make sure\n"
"\t - that the ESCs are not powered\n"
"\t - that safety is off (two short blinks)\n"
"\t - that the controllers are stopped\n"
"\n"
"Do you want to start calibration now: y or n?\n");
/* wait for user input */
while (1) {
ret = poll(&fds, 1, 0);
if (ret > 0) {
if (read(0, &c, 1) <= 0) {
printf("ESC calibration read error\n");
return 0;
}
if (c == 'y' || c == 'Y') {
break;
} else if (c == 0x03 || c == 0x63 || c == 'q') {
printf("ESC calibration exited\n");
return 0;
} else if (c == 'n' || c == 'N') {
printf("ESC calibration aborted\n");
return 0;
} else {
printf("Unknown input, ESC calibration aborted\n");
return 0;
}
}
/* rate limit to ~ 20 Hz */
px4_usleep(50000);
}
/* open for ioctl only */
int fd = open(dev, 0);
if (fd < 0) {
PX4_ERR("can't open %s", dev);
return 1;
}
/* get number of channels available on the device */
ret = ioctl(fd, PWM_SERVO_GET_COUNT, (unsigned long)&max_channels);
if (ret != OK) {
PX4_ERR("PWM_SERVO_GET_COUNT");
goto cleanup;
}
/* tell IO/FMU that its ok to disable its safety with the switch */
ret = ioctl(fd, PWM_SERVO_SET_ARM_OK, 0);
if (ret != OK) {
PX4_ERR("PWM_SERVO_SET_ARM_OK");
goto cleanup;
}
/* tell IO/FMU that the system is armed (it will output values if safety is off) */
ret = ioctl(fd, PWM_SERVO_ARM, 0);
if (ret != OK) {
PX4_ERR("PWM_SERVO_ARM");
goto cleanup;
}
printf("Outputs armed");
/* wait for user confirmation */
printf("\nHigh PWM set: %d\n"
"\n"
"Connect battery now and hit ENTER after the ESCs confirm the first calibration step\n"
"\n", pwm_high);
fflush(stdout);
while (1) {
/* set max PWM */
for (unsigned i = 0; i < max_channels; i++) {
if (set_mask & 1 << i) {
ret = ioctl(fd, PWM_SERVO_SET(i), pwm_high);
if (ret != OK) {
PX4_ERR("PWM_SERVO_SET(%d), value: %d", i, pwm_high);
goto cleanup;
}
}
}
ret = poll(&fds, 1, 0);
if (ret > 0) {
if (read(0, &c, 1) <= 0) {
printf("ESC calibration read error\n");
goto done;
}
if (c == 13) {
break;
} else if (c == 0x03 || c == 0x63 || c == 'q') {
printf("ESC calibration exited");
goto done;
}
}
/* rate limit to ~ 20 Hz */
px4_usleep(50000);
}
printf("Low PWM set: %d\n"
"\n"
"Hit ENTER when finished\n"
"\n", pwm_low);
while (1) {
/* set disarmed PWM */
for (unsigned i = 0; i < max_channels; i++) {
if (set_mask & 1 << i) {
ret = ioctl(fd, PWM_SERVO_SET(i), pwm_low);
if (ret != OK) {
PX4_ERR("PWM_SERVO_SET(%d), value: %d", i, pwm_low);
goto cleanup;
}
}
}
ret = poll(&fds, 1, 0);
if (ret > 0) {
if (read(0, &c, 1) <= 0) {
printf("ESC calibration read error\n");
goto done;
}
if (c == 13) {
break;
} else if (c == 0x03 || c == 0x63 || c == 'q') {
printf("ESC calibration exited\n");
goto done;
}
}
/* rate limit to ~ 20 Hz */
px4_usleep(50000);
}
/* disarm */
ret = ioctl(fd, PWM_SERVO_DISARM, 0);
if (ret != OK) {
PX4_ERR("PWM_SERVO_DISARM");
goto cleanup;
}
printf("Outputs disarmed");
printf("ESC calibration finished\n");
done:
close(fd);
return 0;
cleanup:
close(fd);
return 1;
}
| 23.760814 | 106 | 0.624438 | iamarkaj |
d90c4943eaa716a559451a45d8a00abd2c01ee9a | 4,639 | cpp | C++ | src/NVProperty_ESP32NVS.cpp | RadioShuttle/NVProperty | 5028d28c2addcd2a4091e37989fd0817e7d7fbe9 | [
"Apache-2.0"
] | null | null | null | src/NVProperty_ESP32NVS.cpp | RadioShuttle/NVProperty | 5028d28c2addcd2a4091e37989fd0817e7d7fbe9 | [
"Apache-2.0"
] | null | null | null | src/NVProperty_ESP32NVS.cpp | RadioShuttle/NVProperty | 5028d28c2addcd2a4091e37989fd0817e7d7fbe9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Helmut Tschemernjak
* 30826 Garbsen (Hannover) Germany
* Licensed under the Apache License, Version 2.0);
*/
#ifdef ARDUINO_ARCH_ESP32
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <NVPropertyProviderInterface.h>
#include <NVProperty_ESP32NVS.h>
#include <NVProperty.h>
#include <nvs.h>
NVProperty_ESP32NVS::NVProperty_ESP32NVS()
{
_didWrite = false;
_handle = 0;
}
NVProperty_ESP32NVS::~NVProperty_ESP32NVS()
{
if (_handle) {
nvs_close(_handle);
}
}
int
NVProperty_ESP32NVS::GetProperty(int key)
{
int32_t value;
esp_err_t err = nvs_get_i32(_handle, _setKey(key), &value);
if(!err)
return value;
return NVProperty::NVP_ENOENT;
};
const char *
NVProperty_ESP32NVS::GetPropertyStr(int key)
{
char *value;
size_t len = sizeof(value);
esp_err_t err = nvs_get_str(_handle, _setKey(key), NULL, &len);
if (!err && len > 0) {
/*
* Yes we leak memory here, however for the Arduino ESP32 this ok
* to make the API easier for users
*/
value = new char[len+1];
if (value == NULL)
return NULL;
memset(value, 0, len+1);
esp_err_t err = nvs_get_str(_handle, _setKey(key), value, &len);
if(!err)
return value;
}
return NULL; // NVP_ENOENT
}
int
NVProperty_ESP32NVS::GetPropertyBlob(int key, const void *blob, int *size)
{
char *value;
size_t len = sizeof(value);
esp_err_t err = nvs_get_blob(_handle, _setKey(key), NULL, &len);
if (!err && len > 0) {
/*
* Yes we leak memory here, however for the Arduino ESP32 this ok
* to make the API easier for users
*/
value = new char[len];
if (value == NULL)
return 0;
memset(value, 0, len);
esp_err_t err = nvs_get_blob(_handle, _setKey(key), value, &len);
if(!err)
return len;
}
return 0; // NVP_ENOENT
}
int64_t
NVProperty_ESP32NVS::GetProperty64(int key)
{
int64_t value;
esp_err_t err = nvs_get_i64(_handle, _setKey(key), &value);
if(!err)
return value;
return NVProperty::NVP_ENOENT;
}
int
NVProperty_ESP32NVS::SetProperty(int key, int64_t value, int type)
{
esp_err_t err = 0;
switch(type) {
case NVProperty::T_BIT:
case NVProperty::T_8BIT:
case NVProperty::T_16BIT:
case NVProperty::T_32BIT: { // T_32BIT and less
int32_t i32 = (int32_t) value;
err = nvs_set_i32(_handle, _setKey(key), i32);
}
break;
case NVProperty::T_64BIT:
err = nvs_set_i64(_handle, _setKey(key), value);
break;
case NVProperty::T_STR:
break;
case NVProperty::T_BLOB:
break;
}
if (!err) {
_didWrite = true;
return NVProperty::NVP_OK;
}
return NVProperty::NVP_ENOENT;
}
int
NVProperty_ESP32NVS::SetPropertyStr(int key, const char *value, int type)
{
esp_err_t err = 0;
if (type != NVProperty::T_STR)
return NVProperty::NVP_INVALD_PARM;
err = nvs_set_str(_handle, _setKey(key), value);
if (!err) {
_didWrite = true;
return NVProperty::NVP_OK;
}
return NVProperty::NVP_ENOENT;
}
int
NVProperty_ESP32NVS::SetPropertyBlob(int key, const void *blob, int size, int type)
{
esp_err_t err = 0;
if (type != NVProperty::T_BLOB)
return NVProperty::NVP_INVALD_PARM;
err = nvs_set_blob(_handle, _setKey(key), blob, size);
if (!err) {
_didWrite = true;
return NVProperty::NVP_OK;
}
return NVProperty::NVP_ENOENT;
}
int
NVProperty_ESP32NVS::EraseProperty(int key)
{
esp_err_t err = nvs_erase_key(_handle, _setKey(key));
if (!err) {
_didWrite = true;
return 0;
}
return NVProperty::NVP_ENOENT;
}
int
NVProperty_ESP32NVS::ReorgProperties(void)
{
return NVProperty::NVP_OK;
}
int
NVProperty_ESP32NVS::OpenPropertyStore(bool forWrite)
{
esp_err_t err;
if (forWrite) {
err = nvs_open("RS", NVS_READWRITE, &_handle);
} else {
err = nvs_open("RS", NVS_READONLY, &_handle);
}
if (err)
return NVProperty::NVP_ERR_FAIL;
return NVProperty::NVP_OK;
}
int
NVProperty_ESP32NVS::ClosePropertyStore(bool flush)
{
esp_err_t err = 0;
if (_didWrite && flush) {
err = nvs_commit(_handle);
}
_didWrite = false;
if (err)
return NVProperty::NVP_ERR_FAIL;
return NVProperty::NVP_OK;
}
#endif // ARDUINO_ARCH_ESP32
| 20.896396 | 83 | 0.609399 | RadioShuttle |
d90c918ef58420e11cb3ae0ae69ff15b92b81acd | 1,349 | cpp | C++ | Codeforces-Code/Codeforces Round 338 (Div. 2)/D.cpp | PrayStarJirachi/Exercise-Code | 801a5926eccc971ab2182e5e99e3a0746bd6a7f0 | [
"MIT"
] | null | null | null | Codeforces-Code/Codeforces Round 338 (Div. 2)/D.cpp | PrayStarJirachi/Exercise-Code | 801a5926eccc971ab2182e5e99e3a0746bd6a7f0 | [
"MIT"
] | null | null | null | Codeforces-Code/Codeforces Round 338 (Div. 2)/D.cpp | PrayStarJirachi/Exercise-Code | 801a5926eccc971ab2182e5e99e3a0746bd6a7f0 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <numeric>
#include <iostream>
#include <algorithm>
const double EPS = 1e-7;
const double PI = 3.1415926535897932384626;
const int MAXN = 222222;
const int MOD = 1000000007;
int n, a[MAXN], pred[MAXN], succ[MAXN];
std::vector<std::pair<int, int> > group;
int fpm(int a, long long b) {
int ret = 1;
for (; b; b >>= 1) {
if (b & 1) ret = 1ll * ret * a % MOD;
a = 1ll * a * a % MOD;
}
return ret;
}
int main() {
std::cin >> n;
for (int i = 1; i <= n; i++)
std::cin >> a[i];
std::sort(a + 1, a + n + 1);
for (int i = 1; i <= n; i++) {
int z = i;
while (i < n && a[i] == a[i + 1]) {
i++;
}
group.push_back(std::make_pair(a[i], i - z + 1));
}
for (int i = 0; i < group.size(); i++) {
pred[i] = 1ll * ((i == 0) ? 1 : pred[i - 1]) * (group[i].second + 1) % (MOD - 1);
}
succ[group.size()] = 1;
for (int i = (int)group.size() - 1; i >= 0; i--) {
succ[i] = 1ll * succ[i + 1] * (group[i].second + 1) % (MOD - 1);
}
int answer = 1;
for (int i = 0, size = group.size(); i < size; i++) {
long long exp = 0;
exp = (1ll * group[i].second * (group[i].second + 1) >> 1) % (MOD - 1);
exp = 1ll * exp * (i == 0 ? 1 : pred[i - 1]) % (MOD - 1) * succ[i + 1] % (MOD - 1);
answer = 1ll * answer * fpm(group[i].first, exp) % MOD;
}
std::cout << answer << std::endl;
return 0;
}
| 25.45283 | 85 | 0.509266 | PrayStarJirachi |
d90da9b7701d58a3058b3ff1a8882c291e23b7d9 | 2,174 | cpp | C++ | src/database/overlay/SoXipAngle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/database/overlay/SoXipAngle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/database/overlay/SoXipAngle.cpp | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
Copyright (c) 2011, Siemens Corporate Research a Division of Siemens Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <Inventor/actions/SoGLRenderAction.h>
#include <Inventor/nodes/SoSeparator.h>
#include <Inventor/sensors/SoFieldSensor.h>
#include "SoXipAngle.h"
#include "SoXipLine.h"
#include "geomutils.h"
SO_NODE_SOURCE( SoXipAngle );
SoXipAngle::SoXipAngle()
{
SO_NODE_CONSTRUCTOR( SoXipAngle );
addChild( new SoXipLine );
addChild( new SoXipLine );
setCreationChild(1);
setUpConnections( TRUE, TRUE );
}
SoXipAngle::~SoXipAngle()
{
}
void
SoXipAngle::initClass()
{
SO_NODE_INIT_CLASS( SoXipAngle, SoXipShapeGroup, "SoXipShapeGroup" );
}
void
SoXipAngle::GLRender( SoGLRenderAction* action )
{
if( !on.getValue() )
return ;
computeAngle();
SoXipShapeGroup::GLRender( action );
}
void
SoXipAngle::computeAngle()
{
SoXipLine* line0 = (SoXipLine *) getChild(0);
SoXipLine* line1 = (SoXipLine *) getChild(1);
if( line0->point.getNum() == 2 && line1->point.getNum() == 2 )
{
SbVec3f u = line0->point[1] - line0->point[0];
SbVec3f v = line1->point[1] - line1->point[0];
float angle = 0;
if( u.length() && v.length() )
{
angle = angleBetweenVectors( u, v, u.cross(v) );
}
// Convert to degrees
angle = angle * 180. / M_PI;
if(angle > 180)
angle = 360 - angle;
char stringName[1024];
sprintf( stringName, "%.0f deg.", angle);
line0->caption.setValue( stringName );
}
}
void
SoXipAngle::setRank( int rank )
{
((SoXipShape *) getChild(1))->rank.setValue( rank );
}
void
SoXipAngle::setCaption( const SbString& caption )
{
((SoXipShape *) getChild(1))->caption.setValue( caption );
}
| 21.74 | 81 | 0.709292 | OpenXIP |
d90eddb2b04218f80a7fa06500d1ce8d8f0675d4 | 545 | hpp | C++ | ui/include/xaml/ui/qt5/control.hpp | Berrysoft/XamlCpp | cc7da0cf83892ceb88926292b7c90b9f8da6128d | [
"MIT"
] | 27 | 2020-01-02T07:40:57.000Z | 2022-03-09T14:43:56.000Z | ui/include/xaml/ui/qt5/control.hpp | Berrysoft/XamlCpp | cc7da0cf83892ceb88926292b7c90b9f8da6128d | [
"MIT"
] | null | null | null | ui/include/xaml/ui/qt5/control.hpp | Berrysoft/XamlCpp | cc7da0cf83892ceb88926292b7c90b9f8da6128d | [
"MIT"
] | 3 | 2020-05-21T07:02:08.000Z | 2021-07-01T00:56:38.000Z | #ifndef XAML_UI_QT_CONTROL_H
#define XAML_UI_QT_CONTROL_H
#include <QWidget>
#include <memory>
#include <xaml/meta/meta_macros.h>
XAML_CLASS(xaml_qt5_control, { 0x0cafa395, 0x4050, 0x4b84, { 0x8f, 0xeb, 0x02, 0xaa, 0xa1, 0x27, 0x21, 0x7b } })
#define XAML_QT5_CONTROL_VTBL(type) \
XAML_VTBL_INHERIT(XAML_OBJECT_VTBL(type)); \
XAML_PROP(handle, type, QWidget**, QWidget*)
XAML_DECL_INTERFACE_(xaml_qt5_control, xaml_object)
{
XAML_DECL_VTBL(xaml_qt5_control, XAML_QT5_CONTROL_VTBL);
};
#endif // !XAML_UI_QT_CONTROL_H
| 27.25 | 112 | 0.752294 | Berrysoft |
d90f3248dd4979fbd4bbc8bfc8a78cad4d6c4c91 | 982 | cpp | C++ | Source/Boids/Systems/Persistent/BoidsDebugDrawSystem.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | 5 | 2022-02-09T21:19:03.000Z | 2022-03-03T01:53:03.000Z | Source/Boids/Systems/Persistent/BoidsDebugDrawSystem.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | null | null | null | Source/Boids/Systems/Persistent/BoidsDebugDrawSystem.cpp | PsichiX/Unreal-Systems-Architecture | fb2ccb243c8e79b0890736d611db7ba536937a93 | [
"Apache-2.0"
] | null | null | null | #include "Boids/Systems/Persistent/BoidsDebugDrawSystem.h"
#include "DrawDebugHelpers.h"
#include "Shared/Components/VelocityComponent.h"
#include "Systems/Public/SystemsWorld.h"
#include "Boids/Components/BoidComponent.h"
#include "Boids/Resources/BoidsSystemsRunCriteria.h"
const float ARROW_LENGTH = 20;
const float THICKNESS = 8;
void BoidsDebugDrawSystem(USystemsWorld& Systems)
{
const auto* BoidsSystemsRunCriteria = Systems.Resource<UBoidsSystemsRunCriteria>();
if (IsValid(BoidsSystemsRunCriteria) && BoidsSystemsRunCriteria->bRunDebugDraw == false)
{
return;
}
Systems.Query<UVelocityComponent, UBoidComponent>().ForEach(
[&](const auto& QueryItem)
{
const auto* Actor = QueryItem.Get<0>();
const auto* Velocity = QueryItem.Get<1>();
const auto From = Actor->GetActorLocation();
const auto To = From + Velocity->Value;
DrawDebugDirectionalArrow(
Systems.GetWorld(), From, To, ARROW_LENGTH, FColor::Red, false, 0, 0, THICKNESS);
});
}
| 29.757576 | 89 | 0.751527 | PsichiX |
d90f49d66b25b39b21b9533521b95f866bb7a6f0 | 2,570 | hpp | C++ | time.hpp | komasaru/calc_greenwich_time | af45776181c2a457a944cd472e1b5069589aa2d8 | [
"MIT"
] | null | null | null | time.hpp | komasaru/calc_greenwich_time | af45776181c2a457a944cd472e1b5069589aa2d8 | [
"MIT"
] | null | null | null | time.hpp | komasaru/calc_greenwich_time | af45776181c2a457a944cd472e1b5069589aa2d8 | [
"MIT"
] | null | null | null | #ifndef CALC_GREENWICH_TIME_HPP_
#define CALC_GREENWICH_TIME_HPP_
#include "delta_t.hpp"
#include "file.hpp"
#include <cmath>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
namespace calc_greenwich {
struct timespec jst2utc(struct timespec); // JST -> UTC 変換
std::string gen_time_str(struct timespec); // 日時文字列生成
class Time {
static std::vector<std::vector<std::string>> l_ls; // List of Leap Second
static std::vector<std::vector<std::string>> l_dut; // List of DUT1
struct timespec ts; // timespec of UTC
struct timespec ts_tai; // timespec of TAI
struct timespec ts_ut1; // timespec of UT1
struct timespec ts_tt; // timespec of TT
struct timespec ts_tcg; // timespec of TCG
struct timespec ts_tcb; // timespec of TCB
struct timespec ts_tdb; // timespec of TDB
double jd; // JD (ユリウス日)
double t; // T (ユリウス世紀数)
double dut1; // UTC - TAI (協定世界時と国際原子時の差 = うるう秒の総和)
double dlt_t; // ΔT (TT(地球時) と UT1(世界時1)の差)
int utc_tai; // UTC - TAI (協定世界時と国際原子時の差 = うるう秒の総和)
public:
Time(struct timespec); // コンストラクタ
struct timespec calc_jst(); // 計算: JST (日本標準時)
double calc_jd(); // 計算: JD (ユリウス日)
double calc_t(); // 計算: T (ユリウス世紀数)
int calc_utc_tai(); // 計算: UTC - TAI (協定世界時と国際原子時の差 = うるう秒の総和)
double calc_dut1(); // 計算: DUT1 (UT1(世界時1) と UTC(協定世界時)の差)
double calc_dlt_t(); // 計算: ΔT (TT(地球時) と UT1(世界時1)の差)
struct timespec calc_tai(); // 計算: TAI (国際原子時)
struct timespec calc_ut1(); // 計算: UT1 (世界時1)
struct timespec calc_tt(); // 計算: TT (地球時)
struct timespec calc_tcg(); // 計算: TCG (地球重心座標時)
struct timespec calc_tcb(); // 計算: TCB (太陽系重心座標時)
struct timespec calc_tdb(); // 計算: TDB (太陽系力学時)
private:
struct timespec utc2jst(struct timespec); // UTC -> JST
double gc2jd(struct timespec); // GC -> JD
double jd2t(double); // JD -> T
int get_utc_tai(struct timespec); // UTC -> UTC - TAI
double get_dut1(struct timespec); // UTC -> DUT1
struct timespec utc2tai(struct timespec); // UTC -> TAI
struct timespec utc2ut1(struct timespec); // UTC -> UT1
struct timespec tai2tt(struct timespec); // TAI -> TT
struct timespec tt2tcg(struct timespec); // TT -> TCG
struct timespec tt2tcb(struct timespec); // TT -> TCB
struct timespec tcb2tdb(struct timespec); // TCB -> TDB
};
} // namespace calc_greenwich
#endif
| 37.246377 | 77 | 0.62607 | komasaru |
d911c6933e9ea1fef855ebe910662962014816ff | 1,314 | hpp | C++ | src/rooms/task.hpp | snailbaron/rooms | 03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa | [
"MIT"
] | null | null | null | src/rooms/task.hpp | snailbaron/rooms | 03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa | [
"MIT"
] | null | null | null | src/rooms/task.hpp | snailbaron/rooms | 03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa | [
"MIT"
] | null | null | null | #pragma once
#include <cmath>
#include <functional>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
enum class TaskState {
Running,
Finished,
};
class TaskPool {
public:
void addTask(std::function<TaskState(float)>&& task)
{
_tasks.push_back(std::move(task));
}
void update(float delta)
{
for (size_t i = 0; i < _tasks.size(); ) {
auto state = _tasks[i](delta);
if (state == TaskState::Finished) {
std::swap(_tasks[i], _tasks.back());
_tasks.resize(_tasks.size() - 1);
} else {
i++;
}
}
}
private:
std::vector<std::function<TaskState(float)>> _tasks;
};
class SwayTask {
public:
SwayTask(
float period,
std::function<void(float value)>&& setter)
: _period(period)
, _setter(std::move(setter))
{ }
TaskState operator()(float delta)
{
_point = std::fmod(_point * _period + delta, _period) / _period;
float value = 0.5f + std::sin(static_cast<float>(_point * 2 * M_PI)) / 2;
_setter(value);
return TaskState::Running;
}
private:
const float _period;
const std::function<void(float value)> _setter;
float _point = 0;
};
| 21.540984 | 81 | 0.554795 | snailbaron |
d914ea2e328f679ff6d69cf8520492f7b34fabfd | 32,343 | cpp | C++ | projDir/antenna_code/Antenna0_5/drvwrapper.cpp | NCAR/titan-cswr | 67efb4f775b69ed35052e9014ccb2ea1d86e5e6d | [
"BSD-2-Clause"
] | null | null | null | projDir/antenna_code/Antenna0_5/drvwrapper.cpp | NCAR/titan-cswr | 67efb4f775b69ed35052e9014ccb2ea1d86e5e6d | [
"BSD-2-Clause"
] | null | null | null | projDir/antenna_code/Antenna0_5/drvwrapper.cpp | NCAR/titan-cswr | 67efb4f775b69ed35052e9014ccb2ea1d86e5e6d | [
"BSD-2-Clause"
] | null | null | null | //***************************************************************************************
// This file contains c-callable wrapper functions representing a one to one mapping
// of the WDM driver capabilities. This is a VERY limited set of functions at only
// the lowest level. This will include the interrupt on and off functions, and a function
// that returns a useable pointer to the hardware.
//
// This file gets compiled and linked together with other files in this project to
// generate a Generic HIQ DLL Library that will be used for all future HIQ applications.
//
// Other c subroutines in this project will have access to the HIQ base addresses and
// the ability to read and write registers.
//
// At one time the philosophy was that only the WDM driver would actually read and
// write registers, but I changed my mind!!
//
// For now, these functions will use Jungo routines in place of a home made WDM driver
// because there is no such driver yet. In the future if and when we do our own WDM driver
// this will be the only routine that will need to be changed for this project. That is
// the underlying purpose of this wrapper file.
//
// List of callable functionalities:
//
// 1) Get base address of hiq card
// 2) Enable interrupts (including registering the user mode interrupt routine)
// 3) Disable interrupts
//
// List of other functions the driver provides but aren't callable:
//
// 1) Kernal mode interrupt routine (sets up the DMA transfer only)
//
//***************************************************************************************
//#include "Forcelib.h"
#include <windows.h>
#include <stdlib.h>
#include "windrvr.h"
#include "wdc_lib.h" // req'd for WDC_IntEnable
#include "windrvr_int_thread.h"
#include "windrvr_events.h"
#include "pci_regs.h"
#include "bits.h"
#include "status_strings.h"
#ifndef __KERNEL__
#include <stdio.h>
#endif
#include <math.h> // for sqrt in phase correction algorithm
#include "hiq_hardware.h"
#include "hiq_lib.h"
#include "smfifo.h"
#include "hiq.h" /* HIQ struct plus status reg defines */
#include "udpsock.h" /* IQ record structure define */
#include "iqdata.h" /* IQ record structure define */
#include "drvwrapper.h" /* jungo prototypes for now */
#include "hiqop.h"
#include "piraqx.h" /* For ctrlflags */
#include "mydata.h" // for IS_DUAL_POL #ifdef
#include "hiqutil.h"
#include "angles.h"
// CONSOLE display
#define CONSOLE true
#define VENDORID 0x10B5
#define DEVICEID 0x9056
// If an error occurs, this string will be set to contain a relevant error message
CHAR HIQ_ErrorString[1024];
// Customized WinDriver Debug Monitor constants
WD_DEBUG_ADD dbgMsg;
/* KPTODO: Obsolete?
// internal data structures
typedef struct
{
WD_INTERRUPT Int;
HANDLE hThread;
HIQ_INT_HANDLER funcIntHandler;
} HIQ_INT_INTERRUPT;
typedef struct
{
DWORD index;
BOOL fIsMemory;
BOOL fActive;
} HIQ_ADDR_DESC;
typedef struct HIQ_STRUCT
{
HANDLE hWD;
HANDLE hEvent;
HIQ_INT_INTERRUPT Int;
WD_PCI_SLOT pciSlot;
HIQ_ADDR_DESC addrDesc[HIQ_ITEMS];
WD_CARD_REGISTER cardReg;
} HIQ_STRUCT;
*/ //KPTODO: Obsolete?
static HIQ_INT_DATA Hiq_Int_Data[INT_MAX_BOARDS]; // Use in User mode interrupt service routine called by KP_HIQ_IntAtDpc().
//***************************************************************************************
// Get a contiguous chunk of locked Kernel memory
//****************************************************************************************
WD_DMA *GetContiguousLockedMem(HIQ *hiq, int size)
{
char *self = "GetContiguousLockedMem:";
int dwStatus;
WD_DMA *pdma;
//WD_DMA **ppDma = NULL;
//PVOID *ppBuf = NULL;
DWORD dwOptions = DMA_KERNEL_BUFFER_ALLOC | DMA_FROM_DEVICE; // KPTODO: is DMA_KERNEL_BUFFER_ALLOC needed/allowed?
PWDC_DEVICE pDev = (PWDC_DEVICE)(hiq->hDev); // KPTODO: why do they do this? PWDC_DEVICE == WDC_DEVICE_HANDLE?
pdma = (WD_DMA *)malloc(sizeof(WD_DMA)); // allocate the WD_DMA struct defining the buffer
if(!pdma) {printf("failed to allocate WD_DMA struct to describe contiguous kernel buffer\n"); return(NULL);}
// first, get a Kernel buffer for the DMA_STUFF structure
memset(pdma, 0, sizeof(WD_DMA));
pdma->pUserAddr = NULL; // output, for contiguous case.
pdma->dwBytes = size;
pdma->dwOptions = DMA_KERNEL_BUFFER_ALLOC | DMA_READ_FROM_DEVICE; // huh????
//pdma->hCard = ((HIQ_HANDLE)hiq->jungo)->cardReg.hCard;
pdma->hCard = pDev->cardReg.hCard;
//dwStatus = WD_DMALock(((HIQ_HANDLE)(hiq->jungo))->hWD,pdma);
dwStatus = WD_DMALock(WD_Open(),pdma); // This works, but is the handle correct?
//dwStatus = WDC_DMAContigBufLock (hiq->hDev, ppBuf, dwOptions, size, ppDma );
if(dwStatus)
{
printf("%s Failed locking down contiguous kernel buffer. Error 0x%1x - %s\n",
self,dwStatus,Stat2Str(dwStatus));
return(NULL);
}
return(pdma);
//return(*ppDma);
}
//***************************************************************************************
// Lock down user buffer (so the operation system doesn't swap it)
// Works for buffers of all sizes
//****************************************************************************************
WD_DMA *LockUserMem(HIQ *hiq, void *buf, int size)
{
char *self = "LockUserMem:";
int dwPagesNeeded,extrapages;
int dwStatus;
WD_DMA *pdma = NULL;
//WD_DMA **ppDma = &pdma;
PWDC_DEVICE pDev = (PWDC_DEVICE)(hiq->hDev); // KPTODO: why do they do this? PWDC_DEVICE == WDC_DEVICE_HANDLE?
//PVOID *pBuf = NULL;
dwPagesNeeded = (size - 1) / 4096 + 2;
extrapages = dwPagesNeeded - WD_DMA_PAGES; // structure already has space for WD_DMA_PAGES (256) pages
if(extrapages < 0){ extrapages = 0; }
pdma = (WD_DMA *)calloc(sizeof(WD_DMA) + sizeof(WD_DMA_PAGE) * extrapages, 1);
pdma->pUserAddr = buf; // fifo as input, so this is a Scatter/Gather request.
pdma->dwBytes = size;
pdma->dwOptions = DMA_FROM_DEVICE;
if(extrapages > 0) pdma->dwOptions |= DMA_LARGE_BUFFER;
pdma->dwPages = (extrapages > 0) ? dwPagesNeeded : 0;
//pdma->hCard = ((HIQ_HANDLE)hiq->jungo)->cardReg.hCard;
pdma->hCard = pDev->cardReg.hCard;
//dwStatus = WD_DMALock(((HIQ_HANDLE)(hiq->jungo))->hWD,pdma); // prev implementation: works
//dwStatus = WD_DMALock(hiq->hDev,pdma); // invalid WinDriver handle!
//dwStatus = WD_DMALock((HANDLE)(hiq->hDev),pdma); // invalid WinDriver handle!
//dwStatus = WD_DMALock((HANDLE)(pDev),pdma); // invalid WinDriver handle!
dwStatus = WD_DMALock(WD_Open(),pdma); // This works, but is the handle correct?
if(dwStatus)
{
printf("%s Failed locking down Scatter-Gather buffer. Error 0x%1x - %s\n",
self,dwStatus,Stat2Str(dwStatus));
return(NULL);
}
return(pdma);
/* Hig Level interface way of doing this?
dwStatus = WDC_DMASGBufLock(hiq->hDev, &buf, DMA_FROM_DEVICE|DMA_ALLOW_CACHE, size, ppDma);
if(dwStatus)
{
printf("%s Failed locking down contiguous kernel buffer. Error 0x%1x - %s\n",
self,dwStatus,Stat2Str(dwStatus));
return(NULL);
}
return(*ppDma);
*/
}
//***********************************************************************************
// This routine
// 1) Locks the FIFO memory so it can be used within an interrupt routine.
// 2) Allocates a locked memory buffer to hold the scatter/gather tables - an array of tables.
// 3) returns the address of the Jungo memory descriptor list
// 4) returns the address of a PLX formatted memory descriptor list (not initialized)
// FifoDma is a pointer to a pointer to the WD_DMA struct for the FIFO
// ListDma is a pointer to a pointer to the WD_DMA struct for the memory descriptor list pList
// pList is a pointer to a pointer to a PLX formatted memory descriptor list
//***********************************************************************************
void LockFIFO(HIQ *hiq, FIFO *fifo)
{
//DWORD dwStatus;
int dwPagesNeeded,align,pagesperrecord;
// allocate the DMA_STUFF structure pointed to by hiq
hiq->dma = malloc(sizeof(DMA_STUFF));
if(!hiq->dma) {printf("LockFIFO: Could not allocate DMA_STUFF structure\n"); exit(-1);}
// allocate the listaddr array pointed to by DMA_STUFF structure
((DMA_STUFF *)hiq->dma)->listaddr = (int *)malloc(sizeof(int) * fifo->record_num);
if(!((DMA_STUFF *)hiq->dma)->listaddr) {printf("LockFIFO: Could not allocate listaddr array\n"); exit(-1);}
// allocate the FifoDma structure pointed to by the DMA_STUFF structure
// Lock the fifo and get the pointer to it's WD_DMA struct for later use
((DMA_STUFF *)hiq->dma)->FifoDma = LockUserMem(hiq, fifo, fifo->size);
//printf("FYI: The fifo buffer was scattered into %d pages by the operating system\n",((DMA_STUFF *)hiq->dma)->FifoDma->dwPages);
// allocate the ListDma structure pointed to by the DMA_STUFF structure
// Also allocate the pList array pointed to by the DMA_STUFF structure
// Now get a locked kernal buffer (contiguous) for the memory descriptor chain list
pagesperrecord = (fifo->record_size - 1) / 4096 + 2;
dwPagesNeeded = pagesperrecord * fifo->record_num;
((DMA_STUFF *)hiq->dma)->ListDma = GetContiguousLockedMem(hiq, dwPagesNeeded * sizeof(DMA_LIST) + 0x10);
// point the pList element of DMA_STUFF to the contiguous memory that was just allocated
align = 0x10 - (int)((DMA_STUFF *)hiq->dma)->ListDma->pUserAddr & 0xf;
((DMA_STUFF *)hiq->dma)->pList = (DMA_LIST *)((int)((DMA_STUFF *)hiq->dma)->ListDma->pUserAddr + align); // get byte-aligned address
((DMA_STUFF *)hiq->dma)->ListDma->Page[0].pPhysicalAddr += align; // use the aligned address later for the PLX chip
((DMA_STUFF *)hiq->dma)->ListDma->pKernelAddr += align; // point the Kernal address there, too
((DMA_STUFF *)hiq->dma)->ListDma->pUserAddr = (PVOID *)((int)((DMA_STUFF *)hiq->dma)->ListDma->pUserAddr + align); // as well as the user address
//printf("The ListDma array was allocated successfully\n");
printf("physical address of pList = ((DMA_STUFF *)hiq->dma)->ListDma->Page[0].pPhysicalAddr = %08X\n",((DMA_STUFF *)hiq->dma)->ListDma->Page[0].pPhysicalAddr);
printf("dma->pList (userspace) = %08X\n",(unsigned long long)((DMA_STUFF *)hiq->dma)->pList);
printf("FIFO physical address = dma->FifoDma->Page[0].pPhysicalAddr = %08X\n",((DMA_STUFF *)hiq->dma)->FifoDma->Page[0].pPhysicalAddr);
printf("in LockFIFO, fifo->record_num = %d\n",fifo->record_num);
}
#define LocalFifoPhysAddr 0x30 // Eric says so
//***********************************************************************************
// This routine
// 1) Initializes the memory descriptor list for each record of the FIFO.
//***********************************************************************************
void DMAListsetup(HIQ *hiq, FIFO *fifo, PHIQ_DEV_CTX pCtx, int whichhiq)
{
int i,j,transferbytes; // use this to calculate addresses
unsigned int k;
unsigned int start,end;
int pagesperrecord,addraccum,bytes;
unsigned int m;
//printf("gates used to program DMA: %d\n",hiq->gates);
// note: this in conjuction with the start point gets gate[0] in the right place. The gate0mode data has two spaces before it
// because it is a series of differences. Later in the interrupt it will be expanded to the correct number of absolute values
transferbytes = 4 * (2 * hiq->gates + 1) + 4 * (hiq->gate0mode ? 2 * hiq->pulsewidth - 2 : 0); // Reads EOF, too. later, add in read for gate0mode
// have to make sure DMAListsetup is called after gate0mode is set to reflect how data is actually being taken
// if it's wrong, it will just generate an EOF
pagesperrecord = (fifo->record_size - 1) / 4096 + 2;
//printf("pagesperrecord = %d\n",pagesperrecord);
//printf("fifo->record_num = %d\n",fifo->record_num);
for(i=0; i<fifo->record_num; i++) // for all records
{
start = fifo->fifobuf_off + i * fifo->record_size + (sizeof(IQRECORD) - 4) + (hiq->gate0mode ? 4 * 2 : 0); // the -4 puts the first word on top of iqrec.gatezero
// if gate0mode, then leave room at the begining for a total of pulsewidth time series points
end = start + transferbytes;
for (j=0; j<pagesperrecord && start < end; j++) // for all fifo pages
{
// find the fifo page k where start lies
for(addraccum=0,k=0; k<((DMA_STUFF *)hiq->dma)->FifoDma->dwPages && addraccum + ((DMA_STUFF *)hiq->dma)->FifoDma->Page[k].dwBytes <= start; k++)
addraccum += ((DMA_STUFF *)hiq->dma)->FifoDma->Page[k].dwBytes;
// addraccum <= start < addraccum + dwBytes for page k
if(addraccum + ((DMA_STUFF *)hiq->dma)->FifoDma->Page[k].dwBytes > end) // > or >= work the same
bytes = end - start;
else
bytes = addraccum + ((DMA_STUFF *)hiq->dma)->FifoDma->Page[k].dwBytes - start;
m = i * pagesperrecord + j;
((DMA_STUFF *)hiq->dma)->pList[m].dwPADR = ((DMA_STUFF *)hiq->dma)->FifoDma->Page[k].pPhysicalAddr + start - addraccum;
((DMA_STUFF *)hiq->dma)->pList[m].dwLADR = LocalFifoPhysAddr;
((DMA_STUFF *)hiq->dma)->pList[m].dwSIZ = bytes;
((DMA_STUFF *)hiq->dma)->pList[m].dwDPR =
((DWORD) ((DMA_STUFF *)hiq->dma)->ListDma->Page[0].pPhysicalAddr + sizeof(DMA_LIST) * (i * pagesperrecord + (j + 1)))
| BIT0 | BIT3 | (addraccum + ((DMA_STUFF *)hiq->dma)->FifoDma->Page[k].dwBytes >= end ? BIT1 : 0);
start = addraccum + ((DMA_STUFF *)hiq->dma)->FifoDma->Page[k].dwBytes;
}
((DMA_STUFF *)hiq->dma)->listaddr[i] = ((DWORD) ((DMA_STUFF *)hiq->dma)->ListDma->Page[0].pPhysicalAddr + sizeof(DMA_LIST) * (i * pagesperrecord)) | BIT0;
pCtx->Hiq_Kp_Int_Data[whichhiq].pDmaDescriptor[i] = ((DMA_STUFF *)hiq->dma)->listaddr[i]; // Save DMA description ptrs for Kernel Plugin.
}
}
#define BITMASK 0xFFFFC000
#define BITSHIFT ((double)((~BITMASK)+1))
/*
Get the HiQ Interrupt data specific to the card handle, by searching for the card handle.
Return the index of the data structure.
*/
int getWhichhiqHiqIntData(DWORD desired_hCard)
{
for(int i=0; i<INT_MAX_BOARDS; i++)
{
if(desired_hCard == Hiq_Int_Data[i].hCard)
{
return i;
}
}
// Error data not found!
printf("ERROR:HIQ_INT_DATA for this interrupt was not found!");
return -1;
}
//#define INTTEST0 // Turns on INT LED during entire intterupt service routine
//#define INTTEST1 // Turns on INT LED during phase correction
//#define INTTEST2 // Turns on INT LED during discriminator computations
#define INTLEDNORMAL // Toggles LED every integration period
/* KPTODO: how much of this to use?
//static int hitctr = 0;
//static int *olddiscptr, *curdiscptr;
//static long discptrdiff;
// Debug display for interrupt handler. See Jungo FAQ for WinDbg printing, e.g. KdPrint().
void HIQ_PCIINT_debug_card_display( HIQ_HANDLE hHIQ )
{
// Visually display on console hex card slot number on each interrupt.
if(CONSOLE) { printf("%x",hHIQ->pciSlot.dwSlot);fflush(stdout); }
// Visually display on console hex card handle on each interrupt.
if(CONSOLE) { printf("%x",hHIQ->cardReg.hCard);fflush(stdout); }
}
*/
static unsigned short hwcounter = 0; // Simulates hardware counter in CSWR version
static unsigned long long hwpulsenum = 0;
static unsigned short old_hwcounter = 0;
// Computation that should not be in kernel interrupt handler for DMADONE condition.
void HIQ_DmaDoneCompute( WDC_DEVICE_HANDLE hDev, HIQ_INT_RESULT *pIntResult )
{
char *self = "HIQ_DmaDoneCompute";
FIFO *pFifo;
HIQ *pHiq;
int i,size;
int whichhiq; // card index, is = whichhiq, or Jungo style - 1.
int sign,*ts;
int *iqptr;
float a,b,c,d,num,den;
int ledCounter;
IQRECORD *record;
HIQOP *hiqop;
bool haveLostSync = false; // Initial sync hifreq burst location is unknown.
int v_gate_offset = 0;
uint8 tempSecs = 0; // temporary variable.
bool isInSync = true;
PWDC_DEVICE pDev = (PWDC_DEVICE)hDev;
// Determine which card sourced the interrupt and use that card's data.
whichhiq = (pDev->cardReg.hCard) - 1;
if(pIntResult->dwCounter % 10000 == 0 && pIntResult->dwLost>0)
{
printf("%s: whichhiq=%d, interrupts=%ld, lost=%ld\n", self, whichhiq, pIntResult->dwCounter, pIntResult->dwLost ); // Print Interrupt count.
}
// Determine which card sourced the interrupt and use that card's data.
PHIQ_DEV_CTX pDevCtx = (PHIQ_DEV_CTX)WDC_GetDevContext(hDev);
pFifo = Hiq_Int_Data[whichhiq].mHIQ; // the fifo.
pHiq = Hiq_Int_Data[whichhiq].mH; // the HIQ structure.
v_gate_offset = Hiq_Int_Data[whichhiq].v_gate_offset;
isInSync = Hiq_Int_Data[whichhiq].isInSync;
ledCounter = Hiq_Int_Data[whichhiq].ledCounter;
#define CSWR
// Init or Update pulse number.
if(pHiq->pulsenum == 0) // On the first time interrupt...
{
#ifdef CSWR
// For CSWR the pulse numbers will start with 1, not at the epoch
pHiq->pulsenum = 1;
hwpulsenum = 0;
// hwcounter = 1;
#else
// Generate the starting pulse number.
pHiq->pulsenum = getStartPulseNumber(Hiq_Int_Data[whichhiq].prt1);
#endif
getUtcTime(&Hiq_Int_Data[whichhiq].secs, &Hiq_Int_Data[whichhiq].nanosecs); // Establish a single start time.
}
else
{
#ifdef CSWR2
// This scheme was an attempt to sync two separate HiQ boxes. Didn't work because
// the hardware counter was operating in realtime and this code operates in XP time. (DPC)
if((abs(hwcounter - old_hwcounter) > 0xFFF)) // We've wrapped
{
hwpulsenum++;
}
old_hwcounter = hwcounter;
pHiq->pulsenum = hwcounter;
pHiq->pulsenum = (hwpulsenum << 16) | (hwcounter);
#else
pHiq->pulsenum += 1; // Increment pulse number since epoch.
#endif
}
old_hwcounter = hwcounter; // Save the old value
// Increment the head to match the record where the data was just sent to
fifo_increment_head(pFifo);
// All the I's and Q's and the EOF has just been received in this record
// Now fill in the other data for the record
hiqop = (HIQOP *)fifo_get_header_address(pFifo);
record = (IQRECORD *)((int)fifo_get_write_address(pFifo));
// First, grab the current antenna data and put them in the IQRECORD structure.
get_angles(record, Hiq_Int_Data[whichhiq].angle_source, &hwcounter);
// Get seconds and nanoseconds
record->secs = Hiq_Int_Data[whichhiq].secs;
record->nanosecs = Hiq_Int_Data[whichhiq].nanosecs;
// Another pulse occurred so increment time by the pulse time.
if(Hiq_Int_Data[whichhiq].dual_prt) // If dual PRT we need to know if the pulse is short or long, and add that time.
{
if(pHiq->pulsenum & 0x0000000000000001) // Odd numbered int64 pulse, started with long interval.
{
record->nanosecs += (uint4)(Hiq_Int_Data[whichhiq].prt2*1.0e9);
}
else
{
record->nanosecs += (uint4)(Hiq_Int_Data[whichhiq].prt1*1.0e9);
}
}
else // If single PRT, then all pulses take the same time.
{
record->nanosecs += (uint4)(Hiq_Int_Data[whichhiq].prt1*1.0e9);
}
// Roll over nanosecs to seconds, but can not trust the PRT to be accurate so just reset to a new time.
if(record->nanosecs > 1000000000)
{
getUtcTime(&tempSecs, &record->nanosecs);
record->secs = (uint8)tempSecs;
}
// always set the size of a record for anything that might eventually be recorded or sent over a socket
size = sizeof(int) * (2 * pHiq->gates + (pHiq->gate0mode ? 2 * pHiq->pulsewidth : 0)) + (sizeof(IQRECORD) - sizeof(int));
fifo_set_rec_size(pFifo,size);
record->pulsenum = pHiq->pulsenum;
// record->beamnum = pHiq->beamnum;
record->configid = hiqop->configid;
// note, this is right based on the definition.
// 3/17/2009 Had to add a one to address to get just past the data area and pick up EOF character (0's).
record->eofstatus = 0xFFFFC000 & (&record->gatezero)[2 * pHiq->gates + (pHiq->gate0mode ? 2 * pHiq->pulsewidth : 0) + 1];
// record->eofstatus = (&record->gatezero)[2 * pHiq->gates + (pHiq->gate0mode ? 2 * pHiq->pulsewidth : 0)];
// record->eofstatus = 0xAAAAAAAA;
record->pulsewidth = pHiq->pulsewidth | (pHiq->gate0mode ? 1 : 0); // pulsewidth with bit0 indicating gate0mode
record->gates = pHiq->gates;
// prepare things for the next DMA transfer
// clear out the EOF on the next record, so that even weird errors get caught!
int tail;
fifo_clear(pFifo,&tail); // Reset SW fifo ptrs.
IQRECORD *trecord = (IQRECORD *)((int)fifo_get_address(pFifo,tail,1));
// (&trecord->gatezero)[2 * pHiq->gates + (pHiq->gate0mode ? 2 * pHiq->pulsewidth : 0)] = 0xAAAAAAAA; // note, this is right based on the definition
//#define PCIINT_PRINT_BLIP
#ifdef PCIINT_PRINT_BLIP
// print a little blip in console, mark every 10th interrupt.
if(whichhiq==0)
{
if(Hiq_Int_Data[0].intCnt%10 == 1){printf("%c",'1');}else{printf("%c",'.');}
}
if(whichhiq==1)
{
if(Hiq_Int_Data[1].intCnt%10 == 1){printf("%c",'2');}else{printf("%c",':');}
}
#endif
// Assume in sync unless detected below as not in sync.
if(Hiq_Int_Data[whichhiq].intCnt < 1000)
{
isInSync = true;
}
//------------------------------------------------------------------
// TESTCASE: Test loss of AFC hi freq burst of data used for sync by
// setting flag monitored by Runhiq.exe.
// Count on next line determines how many interrupts before restart condition.
//#define FORCE_OUT_OF_SYNC 100000 // TEST: Forced OUT OF SYNC condition!
#ifdef FORCE_OUT_OF_SYNC
if(Hiq_Int_Data[whichhiq].intCnt>FORCE_OUT_OF_SYNC && isInSync)
#else
if((record->eofstatus != 0x00000000) && isInSync) // TODO: Don't understand this condition
#endif
//------------------------------------------------------------------
{
isInSync = false; // enter only once.
haveLostSync = true;
#define EOF_SEARCH 10
#ifdef EOF_SEARCH
for(int eofindex = 0; eofindex < EOF_SEARCH; eofindex++)
{
printf("%d: 0x%08X\n", -eofindex+5,
(&trecord->gatezero)[2 * pHiq->gates + (pHiq->gate0mode ? 2 * pHiq->pulsewidth : 0) - eofindex+5]);
}
printf("\n");
#else
//printf("*****************************************************\n");
printf("* Loss of Sync Occurred: %8X on card %d of {1,2}*\n",record->eofstatus, hHIQ->cardReg.hCard);
//printf("*****************************************************\n");
//printf("%c",(record->eofstatus == 0xAAAAAAAA) ? '!' : '#'); // print a little blip if out of sync
#endif
fflush(stdout);
WDC_Err("%s: Card %d: Loss of Sync int error!",self,whichhiq);
//HIQ_DebugMsg(hHIQ, "Loss of Sync int error!", D_ERROR, S_INT);
}
// This is where the gate 0 converter goes!!!!!!!!!!!!!!!
if(pHiq->gate0mode)
{
ts = &record->gatezero;
iqptr = ts + 2;
sign = 0;
if(*iqptr & 0x80000000) sign = 2; // if the first value is negative.
*ts++ = (int)(((sign?-1: 1) * (int)(iqptr[0] & BITMASK) - 0x8000000) / BITSHIFT);
*ts++ = (int)(((sign? 1:-1) * (int)(iqptr[1] & BITMASK) - 0x8000000) / BITSHIFT);
for(i=2; i<2*pHiq->pulsewidth; i++)
{
if(((i+1)&2)^sign)
{
*ts++ = (int)(( (int)(iqptr[i-2] & BITMASK) - (int)(iqptr[i] & BITMASK) - 0x8000000) / BITSHIFT);
} else {
*ts++ = (int)((-(int)(iqptr[i-2] & BITMASK) + (int)(iqptr[i] & BITMASK) - 0x8000000) / BITSHIFT);
}
}
}
#ifdef INTTEST2
turnLedOn(hDev); // turn on the LED.
#endif
// This is where the discriminator goes
// this is supposed to be XMITWIDTH!
a = (float)((&record->gatezero)[pHiq->pulsewidth - 2 + 0]);
b = (float)((&record->gatezero)[pHiq->pulsewidth - 2 + 1]);
c = (float)((&record->gatezero)[pHiq->pulsewidth - 2 + 2]);
d = (float)((&record->gatezero)[pHiq->pulsewidth - 2 + 3]);
num = a * d - b * c;
den = b * (b - d) + c * (c - a); // max = 2 * ADFULLSCALE^2.
//#define DEBUGDISC0 // debug discriminator: For grabbing interrupts with debugger
#ifdef DEBUGDISC0
static int *olddiscptr, *curdiscptr;
static long discptrdiff;
curdiscptr = &(&record->gatezero)[pHiq->pulsewidth-2];
discptrdiff = curdiscptr - olddiscptr;
if(discptrdiff != 0x806)
{
int qq = 1;
}
olddiscptr = curdiscptr;
printf("DISCPTR: cur 0x%p, diff 0x%p\n",&(&record->gatezero)[pHiq->pulsewidth-2] , discptrdiff);
#endif
// if den less than -30 dB, set at -30 dB (make discriminator read zero for weak signals).
if(den < 2 * ADFULLSCALE * ADFULLSCALE / 1000.0) den = (float)(2 * ADFULLSCALE * ADFULLSCALE / 1000.0);
// Exponential filter on numerator and denominator
// Set DELTA to a value between 0 and 1, say 0.9. The higher DELTA, the longer the time constant (longer integration time).
#define DELTA 0.99 // 0.0 shuts off exp averaging // Was .75 GRG 8/12/10
pHiq->numdiscrim = num;
pHiq->dendiscrim = den;
pHiq->err = fabs(num/den) < 7.0 ? num/den: pHiq->avgerr; // avgerr not changed if err too large
pHiq->avgerr = (float)((1.0 - DELTA) * pHiq->err + DELTA * pHiq->avgerr);
//#define DEBUGDISC1 // debug discriminator: For grabbing data with debugger
#ifdef DEBUGDISC1
static int hitctr = 0;
float test = pHiq->numdiscrim/pHiq->dendiscrim;
if(hitctr++ %pHiq->hits == 0)
printf("DISC-DRVW: num %20.3f, den %20.3f, err %8.3f\n", num*1e-6, den*1e-6, den != 0? test: 0);
#endif
#ifdef INTTEST2
turnLedOff(hDev); // turn off the LED.
#endif
if(pHiq->gate0mode) // Only correct phase in gate0mode is on (non-coherent xmitter).
{
//#define INTEGER_ARITHMETIC
#ifndef INTEGER_ARITHMETIC
float I,Q,I0,Q0;
// This is where the phase correction goes!
// This is the floating point version
// normalize and conjugate gate zero
iqptr = &record->gatezero + 2 * (pHiq->pulsewidth & ~1);
I0 = (float)iqptr[0];
Q0 = (float)iqptr[1];
if(I0 == 0.0 && Q0 == 0.0) pHiq->g0invmag = 1.0;
else pHiq->g0invmag = (float)(1.0 / sqrt(I0 * I0 + Q0 * Q0));
I0 *= pHiq->g0invmag;
Q0 *= -pHiq->g0invmag;
#ifdef INTTEST1
turnLedOn(hDev); // turn on the LED.
#endif
// Adjust the vertical channel gate offset correction with config file value.
if(whichhiq == 0)
{
v_gate_offset = 0; // Only correct Vertical channel.
}
// correct all but the zeroeth of the gates with m and n
iqptr += 2;
for(i=1; i<pHiq->gates - v_gate_offset; i++) // Shift everything toward radar by v_gate_offset gates.
{
I = (float)iqptr[0 + v_gate_offset];
Q = (float)iqptr[1 + v_gate_offset];
*iqptr++ = (int)(I0 * I - Q0 * Q);
*iqptr++ = (int)(Q0 * I + I0 * Q);
}
int *iqptre = iqptr-2*v_gate_offset;
if(whichhiq > 0)
{
for(i = 0; i < 2*v_gate_offset; i++)
*iqptr++ = *iqptre++; // Repeat last v_gate_offset gates at end
}
#ifdef INTTEST1
turnLedOff(hDev); // turn off the LED.
#endif
#ifdef INTLEDNORMAL
if(ledCounter++ % hiqop->hits == 0)
{
toggleLed(hDev);
}
#endif
#endif // INTEGER_ARITHMETIC
#ifdef INTEGER_ARITHMETIC
int I,Q,I0,Q0;
// This is where the phase correction goes!
// This is the integer version 5us for 260 gates benchmark on Mitch's lab machine
// normalize and conjugate gate zero.
iqptr = &record->gatezero + 2 * (pHiq->pulsewidth & ~1);
I0 = iqptr[0];
Q0 = iqptr[1];
if(I0 == 0.0 && Q0 == 0.0)
pHiq->g0invmag = 16384.0;
else
pHiq->g0invmag = 16383.0 / sqrt((double)(I0 * I0) + (double)(Q0 * Q0));
I0 = (int)((double)I0 * pHiq->g0invmag);
Q0 = (int)((double)Q0 * -pHiq->g0invmag);
// turnLedOn(hDev); // turn on the LED.
// correct all but the zeroeth of the gates with m and n.
iqptr += 2;
for(i=1; i<pHiq->gates; i++)
{
I = iqptr[0] / 16384;
Q = iqptr[1] / 16384;
*iqptr++ = I0 * I - Q0 * Q;
*iqptr++ = Q0 * I + I0 * Q;
}
if(ledCounter++ % hiqop->hits == 0)
{
toggleLed(hDev);
}
#endif
} // if(pHiq->gate0mode)
// Rollover interrupt count.
if(Hiq_Int_Data[whichhiq].intCnt == 0xEFFFFFFF ){ // Max positive value.
Hiq_Int_Data[whichhiq].intCnt = 1; // Skip 0 as it means first ever interrupt.
} else {
Hiq_Int_Data[whichhiq].intCnt++;
}
// Save updated data.
Hiq_Int_Data[whichhiq].mH = pHiq; // the HIQ structure.
Hiq_Int_Data[whichhiq].secs = record->secs;
Hiq_Int_Data[whichhiq].nanosecs = record->nanosecs;
Hiq_Int_Data[whichhiq].isInSync = isInSync;
Hiq_Int_Data[whichhiq].ledCounter = ledCounter;
#ifdef INTTEST0
turnLedOff(hDev); // turn off the LED.
#endif
}
/* KPTODO: add lated as needed. */
// Data for monitoring health of system.
int HIQ_getIntCnt( int whichhiq ) { return Hiq_Int_Data[whichhiq].intCnt; }
int HIQ_getIntErrCnt( int whichhiq ) { return Hiq_Int_Data[whichhiq].intErrCnt; }
bool HIQ_isInSync( int whichhiq ) { return Hiq_Int_Data[whichhiq].isInSync; }
// Return a ptr to the per card interrupt data structure.
HIQ_INT_DATA *getHiq_Int_Data(int whichhiq)
{
return &(Hiq_Int_Data[whichhiq]);
}
// Set the KP interrupt context. Initialize the specific HiQ card's FIFO and HIQ data structures.
void HIQ_setDeviceContext(int whichhiq, HIQ *hiq, FIFO *pFifo, PHIQ_DEV_CTX pCtx)
{
WD_DMA *ListDma = ((DMA_STUFF *)hiq->dma)->ListDma; // ptr to DMA structures.
DMA_LIST *pList = NULL; //((DMA_STUFF *)hiq->dma)->pList; // ptr to PLX descriptor list structure.
pCtx->Hiq_Kp_Int_Data[whichhiq].waitingForHF = TRUE; // this flag mirrors the HF enable bit.
pCtx->Hiq_Kp_Int_Data[whichhiq].startedDMA = FALSE; // this flag mirrors DMASTART.
// pCtx->Hiq_Kp_Int_Data[whichhiq].mHIQ = fifo; // Pointer to FIFO struct.
// pCtx->Hiq_Kp_Int_Data[whichhiq].fifoHead = pFifo->head; // FIFO head.
// pCtx->Hiq_Kp_Int_Data[whichhiq].fifoRecordNumber = pFifo->record_num; // FIFO record number.
pCtx->Hiq_Kp_Int_Data[whichhiq].pDmaDescriptorIndex = 1; // Initialize index into DMA descriptor ptr list.
pCtx->funcIntHandler = HIQ_DmaDoneCompute;
}
// High level interrupt enabler, which initializes necessary data stuctures.
bool HIQ_enableint(int whichhiq, HIQ *hiq, FIFO *fifo)
{
char *self = "HIQ_enableint";
DWORD dwStatus;
//int cardHandle;
WDC_DEVICE_HANDLE hDev = hiq->hDev;
bool result = true;
PWDC_DEVICE pDev = (PWDC_DEVICE)(hiq->hDev);
dwStatus = HIQ_IntEnable(hDev, HIQ_DmaDoneCompute);
if (WD_STATUS_SUCCESS != dwStatus)
{
printf("%s:FAILED TO ENABLE INTERRUPTS on whichhiq %d, Bus:Slot %d:%d. Error 0x%lx - %s\n",
self,whichhiq,pDev->slot.pciSlot.dwBus,pDev->slot.pciSlot.dwSlot,
dwStatus,Stat2Str(dwStatus));
result = false;
}
else
{
printf("%s: INTERRUPT ENABLED on whichhiq %d, Bus:Slot %d:%d.\n",
self,whichhiq,pDev->slot.pciSlot.dwBus,pDev->slot.pciSlot.dwSlot);
printf("HW FIFO is %s half full.\n",(HIQ_ReadISTAT(hDev)& 0x02)?"greater than":"less than");
}
return result;
}
void HIQ_disableint(HIQ *hiq, int whichhiq)
{
char *self = "HIQ_disableint";
if(HIQ_IntDisable(hiq->hDev) == WD_STATUS_SUCCESS)
{
printf("%s:Card %d (of 1-N) INTERRUPT DISABLED.\n", self, whichhiq);
}
else
{
printf("%s: Card %d (of 1-N) INTERRUPT DISABLE FAILED.\n", self, whichhiq);
}
}
// setup debug monitor input.
/* KPTODO: Use WDC_Err() instead.
void HIQ_DebugSetup(void)
{
BZERO(dbgMsg);
dbgMsg.dwLevel = D_ERROR; //default
//dbgMsg.dwLevel = D_TRACE;
dbgMsg.dwSection = S_ALL;
/*
debugInfo.dwSection =
S_IO
| S_MEM
| S_INT
| S_PCI
| S_DMA
| S_MISC
| S_LICENSE
// | S_ISAPNP
| S_PCMCIA
| S_PNP
| S_CARD_REG
| S_KER_DRV
// | S_US
// | S_KER_PLUG
| S_EVENT
;
*/
//}
// Add a message at a level to the Debug Monitor.
// See windrvr.h for definitions.
/* KPTODO: Use WDC_Err() instead.
void HIQ_DebugMsg(HIQ_HANDLE hHIQ, char* pDbgMsg, DEBUG_LEVEL aLevel, DEBUG_SECTION aSection)
{
strcpy(dbgMsg.pcBuffer, pDbgMsg);
dbgMsg.dwLevel = aLevel;
dbgMsg.dwSection = aSection;
WD_DebugAdd(hHIQ->hWD, &dbgMsg);
}
*/
// Init/update the interrupt structure with the angle source (see angles.h).
void setAngleSource(int whichhiq, int anAngleSource)
{
// KPTODO: just so it will compile for now.
Hiq_Int_Data[whichhiq].angle_source = anAngleSource;
}
// Get the interrupt structure with the angle source (see angles.h).
int getAngleSource(int whichhiq)
{
//return 0; // KPTODO: just so it will compile for now.
return Hiq_Int_Data[whichhiq].angle_source;
}
| 38.005875 | 165 | 0.650651 | NCAR |
d9150398e1d9d41dbfd7c16f8ac0d0a9c395dd3c | 7,081 | hpp | C++ | Drivers/BuR/Implementation/libmcdriver_bur_connector.hpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | 15 | 2020-11-10T17:22:39.000Z | 2021-12-16T14:45:11.000Z | Drivers/BuR/Implementation/libmcdriver_bur_connector.hpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | 5 | 2021-08-30T06:58:52.000Z | 2022-03-09T15:25:49.000Z | Drivers/BuR/Implementation/libmcdriver_bur_connector.hpp | alexanderoster/AutodeskMachineControlFramework | 17aec986c2cb3c9ea46bbe583bdc0e766e6f980b | [
"BSD-3-Clause"
] | 20 | 2020-08-06T15:53:34.000Z | 2022-02-09T13:49:59.000Z | /*++
Copyright (C) 2020 Autodesk Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Autodesk Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL AUTODESK INC. 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.
Abstract: This is the class declaration of CDriver_BuR
*/
#ifndef __LIBMCDRIVER_BUR_CONNECTOR
#define __LIBMCDRIVER_BUR_CONNECTOR
#include "libmcdriver_bur_connector.hpp"
#include "libmcdriver_bur_definitions.hpp"
// Include custom headers here.
#include <mutex>
#include <map>
#include <memory>
#include <queue>
#include <functional>
#define BUR_MINCUSTOMCOMMANDID 1024
#define BUR_MAXCUSTOMCOMMANDID 65535
#define BUR_COMMAND_DIRECT_INIT 100
#define BUR_COMMAND_DIRECT_BEGINLIST 101
#define BUR_COMMAND_DIRECT_FINISHLIST 102
#define BUR_COMMAND_DIRECT_EXECUTELIST 103
#define BUR_COMMAND_DIRECT_PAUSELIST 104
#define BUR_COMMAND_DIRECT_LISTSTATUS 105
#define BUR_COMMAND_DIRECT_ABORTLIST 106
#define BUR_COMMAND_DIRECT_RESUMELIST 107
#define BUR_COMMAND_DIRECT_MACHINESTATUS 108
#define BUR_COMMAND_DIRECT_JOURNALSTART 109
#define BUR_COMMAND_DIRECT_JOURNALSTOP 110
#define BUR_COMMAND_DIRECT_JOURNALRETRIEVE 111
namespace LibMCDriver_BuR {
namespace Impl {
class CDriver_BuRSocketConnection;
#pragma pack(push)
#pragma pack(1)
struct sAMCFToPLCPacket {
uint32_t m_nSignature;
uint8_t m_nMajorVersion;
uint8_t m_nMinorVersion;
uint8_t m_nPatchVersion;
uint8_t m_nBuildVersion;
uint32_t m_nClientID;
uint32_t m_nSequenceID;
uint32_t m_nCommandID;
sAMCFToPLCPacketPayload m_Payload;
uint32_t m_nChecksum;
};
struct sPLCToAMCFPacket {
uint32_t m_nSignature;
uint8_t m_nMajorVersion;
uint8_t m_nMinorVersion;
uint8_t m_nPatchVersion;
uint8_t m_nBuildVersion;
uint32_t m_nClientID;
uint32_t m_nSequenceID;
uint32_t m_nErrorCode;
uint32_t m_nCommandID;
uint32_t m_nMessageLen;
uint32_t m_nHeaderChecksum;
uint32_t m_nDataChecksum;
};
#pragma pack(pop)
/*************************************************************************************************************************
Class declaration of CDriver_BuR
**************************************************************************************************************************/
class CDriver_BuRPacket {
private:
uint32_t m_nCommandID;
uint32_t m_nStatusCode;
std::vector<uint8_t> m_Data;
public:
CDriver_BuRPacket(uint32_t nCommandID, uint32_t nStatusCode);
~CDriver_BuRPacket();
uint32_t getCommandID();
uint32_t getStatusCode();
uint32_t readUInt32(uint32_t nAddress);
uint16_t readUInt16(uint32_t nAddress);
uint8_t readUInt8(uint32_t nAddress);
float readFloat(uint32_t nAddress);
double readDouble(uint32_t nAddress);
bool readBool(uint32_t nAddress);
std::string readString(uint32_t nAddress, uint32_t nLength);
std::vector<uint8_t> & getDataBuffer ();
};
typedef std::shared_ptr<CDriver_BuRPacket> PDriver_BuRPacket;
class CDriver_BuRSendInfo;
typedef std::function<void(CDriver_BuRSendInfo * pSendInfo, CDriver_BuRPacket * pPacket)> BurSendCallback;
class CDriver_BuRSendInfo {
private:
uint32_t m_nCommandID;
uint32_t m_nSequenceID;
uint32_t m_nClientID;
uint64_t m_nTimeStamp;
BurSendCallback m_Callback;
public:
CDriver_BuRSendInfo(uint32_t nCommandID, uint32_t nSequenceID, uint32_t nClientID, uint64_t nTimeStamp, BurSendCallback sendCallback);
~CDriver_BuRSendInfo();
uint32_t getCommandID();
uint32_t getSequenceID();
uint32_t getClientID();
uint64_t getTimeStamp();
void resetCallback();
void triggerCallback(CDriver_BuRPacket* pPacket);
};
typedef std::shared_ptr<CDriver_BuRSendInfo> PDriver_BuRSendInfo;
class CDriver_BuRConnector {
private:
protected:
uint32_t m_nWorkerThreadCount;
uint32_t m_nMaxReceiveBufferSize;
uint32_t m_nMajorVersion;
uint32_t m_nMinorVersion;
uint32_t m_nPatchVersion;
uint32_t m_nBuildVersion;
uint32_t m_nMaxPacketQueueSize;
uint32_t m_nSequenceID;
bool m_StartJournaling;
std::shared_ptr<CDriver_BuRSocketConnection> m_pCurrentConnection;
std::map<uint32_t, PDriver_BuRSendInfo> m_SentPacketQueue;
std::queue<sAMCFToPLCPacket> m_PacketsToSend;
std::mutex m_ConnectionMutex;
std::mutex m_SequenceMapMutex;
std::list<PDriver_BuRValue> m_DriverParameters;
std::map<std::string, PDriver_BuRValue> m_DriverParameterMap;
std::map<std::string, PDriver_BuRCommandDefinition> m_CommandDefinitions;
std::map<std::string, PDriver_BuRValue> m_ControlParameterMap;
PDriver_BuRPacket receiveCommandFromPLCEx (CDriver_BuRSocketConnection* pConnection);
void handlePacket();
public:
CDriver_BuRConnector (uint32_t nWorkerThreadCount, uint32_t nMaxReceiveBufferSize, uint32_t nMajorVersion, uint32_t nMinorVersion, uint32_t nPatchVersion, uint32_t nBuildVersion, uint32_t nMaxPacketQueueSize);
void queryParameters(uint64_t nTimeStamp, BurSendCallback pCallback);
void refreshJournal();
void connect(const std::string& sIPAddress, const uint32_t nPort, const uint32_t nTimeout);
void disconnect();
uint32_t sendCommandToPLC(uint32_t nCommandID, sAMCFToPLCPacketPayload payLoad, uint64_t nTimeStamp, BurSendCallback pCallback);
uint32_t sendSimpleCommandToPLC(uint32_t nCommandID, uint64_t nTimeStamp, BurSendCallback pCallback, uint32_t nParameter0 = 0, uint32_t nParameter1 = 0, uint32_t nParameter2 = 0);
void unregisterSendCallback(uint32_t nSequenceID);
};
typedef std::shared_ptr<CDriver_BuRConnector> PDriver_BuRConnector;
} // namespace Impl
} // namespace LibMCDriver_BuR
#endif // __LIBMCDRIVER_BUR_CONNECTOR
| 31.471111 | 210 | 0.751306 | alexanderoster |
d917a216ecb2c10ea9b4d9922ee47ac8cdd93c13 | 12,314 | cpp | C++ | CrashRpt/reporting/crashsender/DetailDlg.cpp | codereba/bittrace | 6826559565aaafc9412d20427d21b73e23febcfe | [
"Unlicense"
] | 10 | 2018-11-09T01:08:15.000Z | 2020-06-21T05:39:54.000Z | CrashRpt/reporting/crashsender/DetailDlg.cpp | codereba/bittrace | 6826559565aaafc9412d20427d21b73e23febcfe | [
"Unlicense"
] | null | null | null | CrashRpt/reporting/crashsender/DetailDlg.cpp | codereba/bittrace | 6826559565aaafc9412d20427d21b73e23febcfe | [
"Unlicense"
] | 4 | 2018-11-09T03:29:52.000Z | 2021-07-23T03:30:03.000Z | /*************************************************************************************
This file is a part of CrashRpt library.
Copyright (c) 2003, Michael Carruth
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************************/
#include "stdafx.h"
#include "DetailDlg.h"
#include "Utility.h"
#include "CrashInfoReader.h"
#include "ErrorReportSender.h"
#include "strconv.h"
LRESULT CDetailDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
DlgResize_Init();
// Mirror this window if RTL language is in use
CString sRTL = Utility::GetINIString(g_CrashInfo.m_sLangFileName,
_T("Settings"), _T("RTLReading"));
if(sRTL.CompareNoCase(_T("1"))==0)
{
Utility::SetLayoutRTL(m_hWnd);
}
SetWindowText(Utility::GetINIString(g_CrashInfo.m_sLangFileName,
_T("DetailDlg"), _T("DlgCaption")));
m_previewMode = PREVIEW_AUTO;
m_filePreview.SubclassWindow(GetDlgItem(IDC_PREVIEW));
m_filePreview.SetBytesPerLine(10);
m_filePreview.SetEmptyMessage(Utility::GetINIString(g_CrashInfo.m_sLangFileName,
_T("DetailDlg"), _T("NoDataToDisplay")));
// Init "Privacy Policy" link
m_linkPrivacyPolicy.SubclassWindow(GetDlgItem(IDC_PRIVACYPOLICY));
m_linkPrivacyPolicy.SetHyperLink(g_CrashInfo.m_sPrivacyPolicyURL);
m_linkPrivacyPolicy.SetLabel(Utility::GetINIString(g_CrashInfo.m_sLangFileName,
_T("DetailDlg"), _T("PrivacyPolicy")));
if(!g_CrashInfo.m_sPrivacyPolicyURL.IsEmpty())
m_linkPrivacyPolicy.ShowWindow(SW_SHOW);
else
m_linkPrivacyPolicy.ShowWindow(SW_HIDE);
CStatic statHeader = GetDlgItem(IDC_HEADERTEXT);
statHeader.SetWindowText(Utility::GetINIString(g_CrashInfo.m_sLangFileName,
_T("DetailDlg"), _T("DoubleClickAnItem")));
m_list = GetDlgItem(IDC_FILE_LIST);
m_list.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);
m_list.InsertColumn(0, Utility::GetINIString(g_CrashInfo.m_sLangFileName,
_T("DetailDlg"), _T("FieldName")), LVCFMT_LEFT, 150);
m_list.InsertColumn(1, Utility::GetINIString(g_CrashInfo.m_sLangFileName,
_T("DetailDlg"), _T("FieldDescription")), LVCFMT_LEFT, 180);
m_list.InsertColumn(3, Utility::GetINIString(g_CrashInfo.m_sLangFileName,
_T("DetailDlg"), _T("FieldSize")), LVCFMT_RIGHT, 60);
m_iconList.Create(16, 16, ILC_COLOR32|ILC_MASK, 3, 1);
m_list.SetImageList(m_iconList, LVSIL_SMALL);
// Insert items to the list
WIN32_FIND_DATA findFileData = {0};
HANDLE hFind = NULL;
CString sSize;
std::map<CString, ERIFileItem>::iterator p;
unsigned i;
for (i = 0, p = g_CrashInfo.GetReport(m_nCurReport).m_FileItems.begin();
p != g_CrashInfo.GetReport(m_nCurReport).m_FileItems.end(); p++, i++)
{
CString sDestFile = p->first;
CString sSrcFile = p->second.m_sSrcFile;
CString sFileDesc = p->second.m_sDesc;
SHFILEINFO sfi;
SHGetFileInfo(sSrcFile, 0, &sfi, sizeof(sfi),
SHGFI_DISPLAYNAME | SHGFI_ICON | SHGFI_TYPENAME | SHGFI_SMALLICON);
int iImage = -1;
if(sfi.hIcon)
{
iImage = m_iconList.AddIcon(sfi.hIcon);
DestroyIcon(sfi.hIcon);
}
int nItem = m_list.InsertItem(i, sDestFile, iImage);
CString sFileType = sfi.szTypeName;
m_list.SetItemText(nItem, 1, sFileDesc);
hFind = FindFirstFile(sSrcFile, &findFileData);
if (INVALID_HANDLE_VALUE != hFind)
{
FindClose(hFind);
ULARGE_INTEGER lFileSize;
lFileSize.LowPart = findFileData.nFileSizeLow;
lFileSize.HighPart = findFileData.nFileSizeHigh;
sSize = Utility::FileSizeToStr(lFileSize.QuadPart);
m_list.SetItemText(nItem, 2, sSize);
}
}
// Select the first list item
m_list.SetItemState(0, LVIS_SELECTED, LVIS_SELECTED);
// Init "Preview" static control
m_statPreview = GetDlgItem(IDC_PREVIEWTEXT);
m_statPreview.SetWindowText(Utility::GetINIString(
g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("Preview")));
// Init "OK" button
m_btnClose = GetDlgItem(IDOK);
m_btnClose.SetWindowText(Utility::GetINIString(
g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("Close")));
// Init "Export..." button
m_btnExport = GetDlgItem(IDC_EXPORT);
m_btnExport.SetWindowText(Utility::GetINIString(
g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("Export")));
// center the dialog on the screen
CenterWindow();
return TRUE;
}
LRESULT CDetailDlg::OnItemChanged(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
LPNMLISTVIEW lpItem = (LPNMLISTVIEW)pnmh;
int iItem = lpItem->iItem;
if (lpItem->uChanged & LVIF_STATE
&& lpItem->uNewState & LVIS_SELECTED)
{
SelectItem(iItem);
}
return 0;
}
LRESULT CDetailDlg::OnItemDblClicked(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
LPNMLISTVIEW lpItem = (LPNMLISTVIEW)pnmh;
int iItem = lpItem->iItem;
DWORD_PTR dwRet = 0;
if (iItem < 0 || (int)g_CrashInfo.GetReport(m_nCurReport).m_FileItems.size() < iItem)
return 0;
std::map<CString, ERIFileItem>::iterator p = g_CrashInfo.GetReport(m_nCurReport).m_FileItems.begin();
for (int i = 0; i < iItem; i++, p++);
CString sFileName = p->second.m_sSrcFile;
dwRet = (DWORD_PTR)::ShellExecute(0, _T("open"), sFileName,
0, 0, SW_SHOWNORMAL);
ATLASSERT(dwRet > 32);
return 0;
}
void CDetailDlg::SelectItem(int iItem)
{
// Sanity check
if (iItem < 0 || (int)g_CrashInfo.GetReport(m_nCurReport).m_FileItems.size() < iItem)
return;
std::map<CString, ERIFileItem>::iterator p = g_CrashInfo.GetReport(m_nCurReport).m_FileItems.begin();
for (int i = 0; i < iItem; i++, p++);
m_previewMode = PREVIEW_AUTO;
m_textEncoding = ENC_AUTO;
m_filePreview.SetFile(p->second.m_sSrcFile, m_previewMode);
}
LRESULT CDetailDlg::OnOK(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
EndDialog(0);
return 0;
}
LRESULT CDetailDlg::OnExport(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CString sFileName = g_CrashInfo.GetReport(m_nCurReport).m_sCrashGUID + _T(".zip");
CFileDialog dlg(FALSE, _T("*.zip"), sFileName,
OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT,
_T("ZIP Files (*.zip)\0*.zip\0All Files (*.*)\0*.*\0\0"), m_hWnd);
INT_PTR result = dlg.DoModal();
if(result==IDOK)
{
CString sExportFileName = dlg.m_szFileName;
g_ErrorReportSender.SetExportFlag(TRUE, sExportFileName);
g_ErrorReportSender.DoWork(COMPRESS_REPORT);
}
return 0;
}
LRESULT CDetailDlg::OnPreviewRClick(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
{
CPoint pt;
GetCursorPos(&pt);
CMenu menu;
menu.LoadMenu(IDR_POPUPMENU);
CMenu submenu = menu.GetSubMenu(1);
MENUITEMINFO mii;
memset(&mii, 0, sizeof(MENUITEMINFO));
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_STRING;
strconv_t strconv;
CString sAuto = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PreviewAuto"));
CString sText = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PreviewText"));
CString sHex = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PreviewHex"));
CString sImage = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("PreviewImage"));
CString sEncoding = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T("DetailDlg"), _T("Encoding"));
mii.dwTypeData = sAuto.GetBuffer(0);
submenu.SetMenuItemInfo(ID_PREVIEW_AUTO, FALSE, &mii);
mii.dwTypeData = sHex.GetBuffer(0);
submenu.SetMenuItemInfo(ID_PREVIEW_HEX, FALSE, &mii);
mii.dwTypeData = sText.GetBuffer(0);
submenu.SetMenuItemInfo(ID_PREVIEW_TEXT, FALSE, &mii);
mii.dwTypeData = sImage.GetBuffer(0);
submenu.SetMenuItemInfo(ID_PREVIEW_IMAGE, FALSE, &mii);
UINT uItem = ID_PREVIEW_AUTO;
if(m_previewMode==PREVIEW_HEX)
uItem = ID_PREVIEW_HEX;
else if(m_previewMode==PREVIEW_TEXT)
uItem = ID_PREVIEW_TEXT;
else if(m_previewMode==PREVIEW_IMAGE)
uItem = ID_PREVIEW_IMAGE;
submenu.CheckMenuRadioItem(ID_PREVIEW_AUTO, ID_PREVIEW_IMAGE, uItem, MF_BYCOMMAND);
if(m_filePreview.GetPreviewMode()!=PREVIEW_TEXT)
{
submenu.DeleteMenu(5, MF_BYPOSITION);
submenu.DeleteMenu(4, MF_BYPOSITION);
}
else
{
CMenuHandle TextEncMenu = submenu.GetSubMenu(5);
mii.dwTypeData = sEncoding.GetBuffer(0);
submenu.SetMenuItemInfo(5, TRUE, &mii);
UINT uItem2 = ID_ENCODING_AUTO;
if(m_textEncoding==ENC_AUTO)
uItem2 = ID_ENCODING_AUTO;
else if(m_textEncoding==ENC_ASCII)
uItem2 = ID_ENCODING_ASCII;
else if(m_textEncoding==ENC_UTF8)
uItem2 = ID_ENCODING_UTF8;
else if(m_textEncoding==ENC_UTF16_LE)
uItem2 = ID_ENCODING_UTF16;
else if(m_textEncoding==ENC_UTF16_BE)
uItem2 = ID_ENCODING_UTF16BE;
TextEncMenu.CheckMenuRadioItem(ID_ENCODING_AUTO, ID_ENCODING_UTF16BE, uItem2, MF_BYCOMMAND);
}
submenu.TrackPopupMenu(TPM_LEFTBUTTON, pt.x, pt.y, m_hWnd);
return 0;
}
LRESULT CDetailDlg::OnPreviewModeChanged(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
PreviewMode mode = PREVIEW_AUTO;
if(wID==ID_PREVIEW_TEXT)
mode = PREVIEW_TEXT;
else if(wID==ID_PREVIEW_HEX)
mode = PREVIEW_HEX;
else if(wID==ID_PREVIEW_IMAGE)
mode = PREVIEW_IMAGE;
m_previewMode = mode;
m_textEncoding = ENC_AUTO;
m_filePreview.SetPreviewMode(mode);
return 0;
}
LRESULT CDetailDlg::OnTextEncodingChanged(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
TextEncoding enc = ENC_AUTO;
if(wID==ID_ENCODING_AUTO)
enc = ENC_AUTO;
else if(wID==ID_ENCODING_ASCII)
enc = ENC_ASCII;
else if(wID==ID_ENCODING_UTF8)
enc = ENC_UTF8;
else if(wID==ID_ENCODING_UTF16)
enc = ENC_UTF16_LE;
else if(wID==ID_ENCODING_UTF16BE)
enc = ENC_UTF16_BE;
m_textEncoding = enc;
m_filePreview.SetTextEncoding(enc);
return 0;
} | 36.868263 | 112 | 0.65592 | codereba |
0bab5e0055eeaa98b65af6f542e804b4d693c9d5 | 651 | cpp | C++ | src/utf8.cpp | dfdchain/fc | fed8efa292e8c6ffccb2153887a73038ae6700d8 | [
"MIT"
] | 66 | 2017-09-29T07:09:59.000Z | 2020-01-12T06:45:08.000Z | src/utf8.cpp | dfdchain/fc | fed8efa292e8c6ffccb2153887a73038ae6700d8 | [
"MIT"
] | 5 | 2017-12-13T13:12:05.000Z | 2018-01-18T10:34:02.000Z | src/utf8.cpp | dfdchain/fc | fed8efa292e8c6ffccb2153887a73038ae6700d8 | [
"MIT"
] | 11 | 2017-12-05T07:02:05.000Z | 2018-01-28T02:52:50.000Z | #include "fc/utf8.hpp"
#include "utf8/checked.h"
#include "utf8/core.h"
#include "utf8/unchecked.h"
#include <assert.h>
namespace fc {
bool is_utf8( const std::string& str )
{
return utf8::is_valid( str.begin(), str.end() );
}
void decodeUtf8(const std::string& input, std::wstring* storage)
{
assert(storage != nullptr);
utf8::utf8to32(input.begin(), input.end(), std::back_inserter(*storage));
}
void encodeUtf8(const std::wstring& input, std::string* storage)
{
assert(storage != nullptr);
utf8::utf32to8(input.begin(), input.end(), std::back_inserter(*storage));
}
} ///namespace fc
| 19.727273 | 78 | 0.635945 | dfdchain |
0bae1863be3083185ef6ca8cb82fb1ba80eff93f | 17,567 | cc | C++ | elements/ip/directiplookup.cc | BorisPis/asplos22-nicmem-fastclick | ab4df08ee056ed48a4c534ec5f8536a958f756b5 | [
"BSD-3-Clause-Clear"
] | 129 | 2015-10-08T14:38:35.000Z | 2022-03-06T14:54:44.000Z | elements/ip/directiplookup.cc | BorisPis/asplos22-nicmem-fastclick | ab4df08ee056ed48a4c534ec5f8536a958f756b5 | [
"BSD-3-Clause-Clear"
] | 241 | 2016-02-17T16:17:58.000Z | 2022-03-15T09:08:33.000Z | elements/ip/directiplookup.cc | BorisPis/asplos22-nicmem-fastclick | ab4df08ee056ed48a4c534ec5f8536a958f756b5 | [
"BSD-3-Clause-Clear"
] | 61 | 2015-12-17T01:46:58.000Z | 2022-02-07T22:25:19.000Z | // -*- c-basic-offset: 4 -*-
/*
* directiplookup.{cc,hh} -- lookup for output port and next-hop gateway
* in one to max. two DRAM accesses with potential CPU cache / TLB misses
* Marko Zec
*
* Copyright (c) 2005 International Computer Science Institute
* Copyright (c) 2005 University of Zagreb
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "directiplookup.hh"
#include <click/ipaddress.hh>
#include <click/straccum.hh>
#include <click/router.hh>
#include <click/error.hh>
CLICK_DECLS
// DIRECTIPLOOKUP::TABLE
// The DirectIPLookup table must be stored in a sub-object in the Linux
// kernel, because it's too large to be allocated all at once.
int
DirectIPLookup::Table::initialize()
{
assert(!_tbl_0_23 && !_tbl_24_31 && !_vport && !_rtable && !_rt_hashtbl
&& !_tbl_0_23_plen && !_tbl_24_31_plen);
_tbl_24_31_capacity = 4096;
_vport_capacity = 1024;
_rtable_capacity = 2048;
if ((_tbl_0_23 = (uint16_t *) CLICK_LALLOC((sizeof(uint16_t) + sizeof(uint8_t)) * (1 << 24)))
&& (_tbl_24_31 = (uint16_t *) CLICK_LALLOC((sizeof(uint16_t) + sizeof(uint8_t)) * _tbl_24_31_capacity))
&& (_vport = (VirtualPort *) CLICK_LALLOC(sizeof(VirtualPort) * _vport_capacity))
&& (_rtable = (CleartextEntry *) CLICK_LALLOC(sizeof(CleartextEntry) * _rtable_capacity))
&& (_rt_hashtbl = (int *) CLICK_LALLOC(sizeof(int) * PREF_HASHSIZE))) {
_tbl_0_23_plen = (uint8_t *) (_tbl_0_23 + (1 << 24));
_tbl_24_31_plen = (uint8_t *) (_tbl_24_31 + _tbl_24_31_capacity);
return 0;
} else
return -ENOMEM;
}
void
DirectIPLookup::Table::cleanup()
{
CLICK_LFREE(_tbl_0_23, (sizeof(uint16_t) + sizeof(uint8_t)) * (1 << 24));
CLICK_LFREE(_tbl_24_31, (sizeof(uint16_t) + sizeof(uint8_t)) * _tbl_24_31_capacity);
CLICK_LFREE(_vport, sizeof(VirtualPort) * _vport_capacity);
CLICK_LFREE(_rtable, sizeof(CleartextEntry) * _rtable_capacity);
CLICK_LFREE(_rt_hashtbl, sizeof(int) * PREF_HASHSIZE);
_tbl_0_23 = _tbl_24_31 = 0;
_vport = 0;
_rtable = 0;
_tbl_0_23_plen = _tbl_24_31_plen = 0;
_rt_hashtbl = 0;
}
inline uint32_t
DirectIPLookup::Table::prefix_hash(uint32_t prefix, uint32_t len)
{
// An arbitrary hash function - it'd better be good...
uint32_t hash = prefix ^ (len << 5) ^ ((prefix >> (len >> 2)) - len);
hash ^= (hash >> 23) ^ ((hash >> 15) * len) ^ ((prefix >> 17) * 53);
hash -= (prefix >> 3) ^ ((hash >> len) * 7) ^ ((hash >> 11) * 103);
hash = (hash ^ (hash >> 17)) & (PREF_HASHSIZE - 1);
return hash;
}
void
DirectIPLookup::Table::flush()
{
memset(_rt_hashtbl, -1, sizeof(int) * PREF_HASHSIZE);
// _vport[0] is our "discard" port
_vport_head = 0;
_vport[0].ll_prev = -1;
_vport[0].ll_next = -1;
_vport[0].refcount = 1; // _rtable[0] will point to _vport[0]
_vport[0].gw = IPAddress(0);
_vport[0].port = DISCARD_PORT;
_vport_size = 1;
_vport_empty_head = -1;
// _rtable[0] is the default route entry
_rt_hashtbl[prefix_hash(0, 0)] = 0;
_rtable[0].ll_prev = -1;
_rtable[0].ll_next = -1;
_rtable[0].prefix = 0;
_rtable[0].plen = 0;
_rtable[0].vport = 0;
_rtable_size = 1;
_rt_empty_head = -1;
// Bzeroed lookup tables resolve 0.0.0.0/0 to _vport[0]
memset(_tbl_0_23, 0, (sizeof(uint16_t) + sizeof(uint8_t)) * (1 << 24));
_tbl_24_31_size = 0;
_tbl_24_31_empty_head = 0x8000;
}
String
DirectIPLookup::Table::dump() const
{
StringAccum sa;
for (uint32_t i = 0; i < PREF_HASHSIZE; i++)
for (int rt_i = _rt_hashtbl[i]; rt_i >= 0; rt_i = _rtable[rt_i].ll_next) {
const CleartextEntry &rt = _rtable[rt_i];
if (_vport[rt.vport].port != -1) {
IPRoute route = IPRoute(IPAddress(htonl(rt.prefix)), IPAddress::make_prefix(rt.plen), _vport[rt.vport].gw, _vport[rt.vport].port);
route.unparse(sa, true) << '\n';
}
}
return sa.take_string();
}
int
DirectIPLookup::Table::vport_find(IPAddress gw, int16_t port)
{
for (int vp = _vport_head; vp >= 0; vp = _vport[vp].ll_next)
if (_vport[vp].gw == gw && _vport[vp].port == port)
return vp;
if (_vport_empty_head < 0 && _vport_size == _vport_capacity) {
if (_vport_capacity == vport_capacity_limit)
return -ENOMEM;
VirtualPort *new_vport = (VirtualPort *) CLICK_LALLOC(sizeof(VirtualPort) * 2 * _vport_capacity);
if (!new_vport)
return -ENOMEM;
memcpy(new_vport, _vport, sizeof(VirtualPort) * _vport_capacity);
CLICK_LFREE(_vport, sizeof(VirtualPort) * _vport_capacity);
_vport = new_vport;
_vport_capacity *= 2;
}
if (_vport_empty_head < 0) {
_vport[_vport_size].ll_next = _vport_empty_head;
_vport_empty_head = _vport_size;
++_vport_size;
}
_vport[_vport_empty_head].refcount = 0;
return _vport_empty_head;
}
void
DirectIPLookup::Table::vport_unref(uint16_t vport_i)
{
if (--_vport[vport_i].refcount == 0) {
int16_t prev, next;
// Prune our entry from the vport list
prev = _vport[vport_i].ll_prev;
next = _vport[vport_i].ll_next;
if (prev >= 0)
_vport[prev].ll_next = next;
else
_vport_head = next;
if (next >= 0)
_vport[next].ll_prev = prev;
// Add the entry to empty vports list
_vport[vport_i].ll_next = _vport_empty_head;
_vport_empty_head = vport_i;
}
}
int
DirectIPLookup::Table::find_entry(uint32_t prefix, uint32_t plen) const
{
int hash = prefix_hash(prefix, plen);
for (int rt_i = _rt_hashtbl[hash]; rt_i >= 0; rt_i = _rtable[rt_i].ll_next)
if (_rtable[rt_i].prefix == prefix && _rtable[rt_i].plen == plen)
return rt_i;
return -1;
}
int
DirectIPLookup::Table::add_route(const IPRoute& route, bool allow_replace, IPRoute* old_route, ErrorHandler *errh)
{
uint32_t prefix = ntohl(route.addr.addr());
uint32_t plen = route.prefix_len();
int rt_i = find_entry(prefix, plen);
if (rt_i >= 0) {
// Attempt to replace an existing route.
// Save the old route if requested so that a rollback can be performed.
if ((rt_i != 0 || (rt_i == 0 && _vport[0].port != DISCARD_PORT)) &&
old_route)
*old_route = IPRoute(IPAddress(htonl(_rtable[rt_i].prefix)),
IPAddress::make_prefix(_rtable[rt_i].plen),
_vport[_rtable[rt_i].vport].gw,
_vport[_rtable[rt_i].vport].port);
if (rt_i == 0) {
// We actually only update the vport entry for the default route
if (_vport[0].port != DISCARD_PORT && !allow_replace)
return -EEXIST;
_vport[0].gw = route.gw;
_vport[0].port = route.port;
return 0;
}
// Check if we allow for atomic route replacements at all
if (!allow_replace)
return -EEXIST;
vport_unref(_rtable[rt_i].vport);
} else {
// Attempt to allocate a new _rtable[] entry.
if (_rt_empty_head < 0 && _rtable_size == _rtable_capacity) {
CleartextEntry *new_rtable = (CleartextEntry *) CLICK_LALLOC(sizeof(CleartextEntry) * _rtable_capacity * 2);
if (!new_rtable)
return -ENOMEM;
memcpy(new_rtable, _rtable, sizeof(CleartextEntry) * _rtable_capacity);
CLICK_LFREE(_rtable, sizeof(CleartextEntry) * _rtable_capacity);
_rtable = new_rtable;
_rtable_capacity *= 2;
}
if (_rt_empty_head < 0) {
_rtable[_rtable_size].ll_next = _rt_empty_head;
_rt_empty_head = _rtable_size;
++_rtable_size;
}
rt_i = _rt_empty_head;
}
// find vport index
int vport_i = vport_find(route.gw, route.port);
if (vport_i < 0)
return vport_i;
// find overflow table space
int start = prefix >> 8;
int end = start + (plen < 24 ? 1 << (24 - plen) : 1);
if (plen > 24 && !(_tbl_0_23[start] & 0x8000)
&& (_tbl_24_31_empty_head & 0x8000) != 0) {
if (_tbl_24_31_size == _tbl_24_31_capacity
&& _tbl_24_31_capacity >= tbl_24_31_capacity_limit)
return -ENOMEM;
if (_tbl_24_31_size == _tbl_24_31_capacity) {
uint16_t *new_tbl = (uint16_t *) CLICK_LALLOC((sizeof(uint16_t) + sizeof(uint8_t)) * 2 * _tbl_24_31_capacity);
if (!new_tbl)
return -ENOMEM;
memcpy(new_tbl, _tbl_24_31, sizeof(uint16_t) * _tbl_24_31_capacity);
memcpy(new_tbl + _tbl_24_31_capacity, _tbl_24_31_plen, sizeof(uint8_t) * _tbl_24_31_capacity);
CLICK_LFREE(_tbl_24_31, (sizeof(uint16_t) + sizeof(uint8_t)) * _tbl_24_31_capacity);
_tbl_24_31 = new_tbl;
_tbl_24_31_plen = (uint8_t *) (new_tbl + 2 * _tbl_24_31_capacity);
_tbl_24_31_capacity *= 2;
}
_tbl_24_31_empty_head = _tbl_24_31_size >> 8;
_tbl_24_31[_tbl_24_31_empty_head << 8] = 0x8000;
_tbl_24_31_size += 256;
}
// At this point we have successfully allocated all memory.
if (rt_i == _rt_empty_head) {
_rt_empty_head = _rtable[rt_i].ll_next;
_rtable[rt_i].prefix = prefix; // in host-order format
_rtable[rt_i].plen = plen;
// Insert the new entry in our hashtable
uint32_t hash = prefix_hash(prefix, plen);
_rtable[rt_i].ll_prev = -1;
_rtable[rt_i].ll_next = _rt_hashtbl[hash];
if (_rt_hashtbl[hash] >= 0)
_rtable[_rt_hashtbl[hash]].ll_prev = rt_i;
_rt_hashtbl[hash] = rt_i;
}
if (vport_i == _vport_empty_head) {
_vport_empty_head = _vport[vport_i].ll_next;
_vport[vport_i].refcount = 0;
_vport[vport_i].gw = route.gw;
_vport[vport_i].port = route.port;
// Add the entry to the vport linked list
_vport[vport_i].ll_prev = -1;
_vport[vport_i].ll_next = _vport_head;
if (_vport_head >= 0)
_vport[_vport_head].ll_prev = vport_i;
_vport_head = vport_i;
}
++_vport[vport_i].refcount;
_rtable[rt_i].vport = vport_i;
for (int i = start; i < end; i++) {
if (_tbl_0_23[i] & 0x8000) {
// Entries with plen > 24 already there in _tbl_24_31[]!
int sec_i = (_tbl_0_23[i] & 0x7fff) << 8, sec_start, sec_end;
if (plen > 24) {
sec_start = prefix & 0xFF;
sec_end = sec_start + (1 << (32 - plen));
} else {
sec_start = 0;
sec_end = 256;
}
for (int j = sec_i + sec_start; j < sec_i + sec_end; j++) {
if (plen > _tbl_24_31_plen[j]) {
_tbl_24_31[j] = vport_i;
_tbl_24_31_plen[j] = plen;
} else if (plen < _tbl_24_31_plen[j]) {
// Skip a sequence of more-specific entries
if (_tbl_24_31_plen[j] > 24) {
j |= 0x000000ff >> (_tbl_24_31_plen[j] - 24);
} else {
i |= 0x00ffffff >> _tbl_24_31_plen[j];
break;
}
} else if (allow_replace) {
_tbl_24_31[j] = vport_i;
} else {
// plen == _tbl_24_31_plen[j] -> damn!
return errh->error("BUG: _tbl_24_31[%08X] collision", j);
}
}
} else {
if (plen > _tbl_0_23_plen[i]) {
if (plen > 24) {
// Allocate a new _tbl_24_31[] entry and populate it
assert(!(_tbl_24_31_empty_head & 0x8000));
int sec_i = _tbl_24_31_empty_head << 8;
_tbl_24_31_empty_head = _tbl_24_31[sec_i];
int sec_start = prefix & 0xFF;
int sec_end = sec_start + (1 << (32 - plen));
for (int j = 0; j < 256; j++) {
if (j >= sec_start && j < sec_end) {
_tbl_24_31[sec_i + j] = vport_i;
_tbl_24_31_plen[sec_i + j] = plen;
} else {
_tbl_24_31[sec_i + j] = _tbl_0_23[i];
_tbl_24_31_plen[sec_i + j] = _tbl_0_23_plen[i];
}
}
_tbl_0_23[i] = (sec_i >> 8) | 0x8000;
} else {
_tbl_0_23[i] = vport_i;
_tbl_0_23_plen[i] = plen;
}
} else if (plen < _tbl_0_23_plen[i]) {
// Skip a sequence of more-specific entries
i |= 0x00ffffff >> _tbl_0_23_plen[i];
} else if (allow_replace) {
_tbl_0_23[i] = vport_i;
} else {
// plen == _tbl_0_23_plen[i] - must never happen!!!
return errh->error("BUG: _tbl_0_23[%08X] collision", i);
}
}
}
return 0;
}
int
DirectIPLookup::Table::remove_route(const IPRoute& route, IPRoute* old_route, ErrorHandler *errh)
{
uint32_t prefix = ntohl(route.addr.addr());
uint32_t plen = route.prefix_len();
int rt_i = find_entry(prefix, plen);
IPRoute found_route;
if (rt_i < 0 || (rt_i == 0 && _vport[0].port == DISCARD_PORT))
return -ENOENT;
found_route = IPRoute(IPAddress(htonl(_rtable[rt_i].prefix)),
IPAddress::make_prefix(_rtable[rt_i].plen),
_vport[_rtable[rt_i].vport].gw,
_vport[_rtable[rt_i].vport].port);
if (!route.match(found_route))
return -ENOENT;
if (old_route)
*old_route = found_route;
if (plen == 0) {
// Default route is a special case. We never remove it from lookup
// tables, but instead only point it to the "discard port".
if (rt_i > 0) // Must never happen, checking it just in case...
return errh->error("BUG: default route rt_i=%d, should be 0", rt_i);
_vport[0].port = DISCARD_PORT;
} else {
uint32_t start, end, i, j, sec_i, sec_start, sec_end;
int newent = -1;
int newmask, prev, next;
vport_unref(_rtable[rt_i].vport);
// Prune our entry from the prefix/len hashtable
prev = _rtable[rt_i].ll_prev;
next = _rtable[rt_i].ll_next;
if (prev >= 0)
_rtable[prev].ll_next = next;
else
_rt_hashtbl[prefix_hash(prefix, plen)] = next;
if (next >= 0)
_rtable[next].ll_prev = prev;
// Add entry to the list of empty _rtable entries
_rtable[rt_i].ll_next = _rt_empty_head;
_rt_empty_head = rt_i;
// Find an entry covering current prefix/len with the longest prefix.
for (newmask = plen - 1 ; newmask >= 0 ; newmask--)
if (newmask == 0) {
newent = 0; // rtable[0] is always the default route
break;
} else {
newent = find_entry(prefix & (0xffffffff << (32 - newmask)),
newmask);
if (newent > 0)
break;
}
// Replace prefix/plen with newent/mask in lookup tables
start = prefix >> 8;
if (plen >= 24)
end = start + 1;
else
end = start + (1 << (24 - plen));
for (i = start; i < end; i++) {
if (_tbl_0_23[i] & 0x8000) {
sec_i = (_tbl_0_23[i] & 0x7fff) << 8;
if (plen > 24) {
sec_start = prefix & 0xFF;
sec_end = sec_start + (1 << (32 - plen));
} else {
sec_start = 0;
sec_end = 256;
}
for (j = sec_i + sec_start; j < sec_i + sec_end; j++) {
if (plen == _tbl_24_31_plen[j]) {
_tbl_24_31[j] = _rtable[newent].vport;
_tbl_24_31_plen[j] = newmask;
} else if (plen < _tbl_24_31_plen[j]) {
// Skip a sequence of more-specific entries
if (_tbl_24_31_plen[j] > 24) {
j |= 0x000000ff >> (_tbl_24_31_plen[j] - 24);
} else {
i |= 0x00ffffff >> _tbl_24_31_plen[j];
break;
}
} else {
// plen > _tbl_24_31_plen[j] -> damn!
return
errh->error("BUG: _tbl_24_31[%08X] inconsistency", j);
}
}
// Check if we can prune the entire secondary table range?
for (j = sec_i ; j < sec_i + 255; j++)
if (_tbl_24_31_plen[j] != _tbl_24_31_plen[j+1])
break;
if (j == sec_i + 255) {
// Yup, adjust entries in primary tables...
_tbl_0_23[i] = _tbl_24_31[sec_i];
_tbl_0_23_plen[i] = _tbl_24_31_plen[sec_i];
// ... and free up the entry (adding it to free space list)
_tbl_24_31[sec_i] = _tbl_24_31_empty_head;
_tbl_24_31_empty_head = sec_i >> 8;
}
} else {
if (plen == _tbl_0_23_plen[i]) {
_tbl_0_23[i] = _rtable[newent].vport;
_tbl_0_23_plen[i] = newmask;
} else if (plen < _tbl_0_23_plen[i]) {
// Skip a sequence of more-specific entries
i |= 0x00ffffff >> _tbl_0_23_plen[i];
}
}
}
}
return 0;
}
// DIRECTIPLOOKUP
DirectIPLookup::DirectIPLookup()
{
#if HAVE_BATCH
// TODO: Remove this when push_batch() will actually be implemented
in_batch_mode = BATCH_MODE_NO;
#endif
}
DirectIPLookup::~DirectIPLookup()
{
}
int
DirectIPLookup::configure(Vector<String> &conf, ErrorHandler *errh)
{
int r;
if ((r = _t.initialize()) < 0)
return r;
_t.flush();
return IPRouteTable::configure(conf, errh);
}
void
DirectIPLookup::cleanup(CleanupStage)
{
_t.cleanup();
}
void
DirectIPLookup::push(int, Packet *p)
{
IPAddress gw;
int port = lookup_route(p->dst_ip_anno(), gw);
if (port >= 0) {
if (gw)
p->set_dst_ip_anno(gw);
output(port).push(p);
} else
p->kill();
}
int
DirectIPLookup::lookup_route(IPAddress dest, IPAddress &gw) const
{
uint32_t ip_addr = ntohl(dest.addr());
uint16_t vport_i = _t._tbl_0_23[ip_addr >> 8];
if (vport_i & 0x8000)
vport_i = _t._tbl_24_31[((vport_i & 0x7fff) << 8) | (ip_addr & 0xff)];
gw = _t._vport[vport_i].gw;
return _t._vport[vport_i].port;
}
int
DirectIPLookup::add_route(const IPRoute& route, bool allow_replace, IPRoute* old_route, ErrorHandler *errh)
{
return _t.add_route(route, allow_replace, old_route, errh);
}
int
DirectIPLookup::remove_route(const IPRoute& route, IPRoute* old_route, ErrorHandler *errh)
{
return _t.remove_route(route, old_route, errh);
}
int
DirectIPLookup::flush_handler(const String &, Element *e, void *,
ErrorHandler *)
{
DirectIPLookup *t = static_cast<DirectIPLookup *>(e);
t->_t.flush();
return 0;
}
String
DirectIPLookup::dump_routes()
{
return _t.dump();
}
void
DirectIPLookup::add_handlers()
{
IPRouteTable::add_handlers();
add_write_handler("flush", flush_handler, 0, Handler::BUTTON);
}
CLICK_ENDDECLS
ELEMENT_REQUIRES(IPRouteTable userlevel|bsdmodule)
EXPORT_ELEMENT(DirectIPLookup)
| 30.183849 | 132 | 0.65384 | BorisPis |
0bafd0a68d765f2a38a60e3633f40b9a452056f2 | 3,604 | cpp | C++ | Game/Source/Earth.cpp | oscarrep/ApolloMission | 4335dbbf19b1835bdd9c22e57ea71f6b66c08370 | [
"MIT"
] | null | null | null | Game/Source/Earth.cpp | oscarrep/ApolloMission | 4335dbbf19b1835bdd9c22e57ea71f6b66c08370 | [
"MIT"
] | null | null | null | Game/Source/Earth.cpp | oscarrep/ApolloMission | 4335dbbf19b1835bdd9c22e57ea71f6b66c08370 | [
"MIT"
] | null | null | null | #include "Defs.h"
#include "Earth.h"
#include "App.h"
#include "Render.h"
#include "Textures.h"
#include "Scene.h"
#include "Animation.h"
#include "Window.h"
#include "SString.h"
Earth::Earth() : Module()
{
LoadAnim();
}
bool Earth::Awake()
{
return true;
}
bool Earth::Start()
{
earthTex = app->tex->Load("Assets/textures/earth.png");
rect.x = 950;
rect.y = 5600;
rect.w = 300;
rect.h = 300;
colliderEarth = app->physicsEngine->AddCollider(rect, ColliderType::COLLIDER_EARTH, this);
//colliderEarth = app->physicsEngine->AddColliderCircle(900, 5600, 300, ColliderType::COLLIDER_EARTH, this);
return true;
}
bool Earth::PreUpdate()
{
currentAnim = &earthAnim;
return true;
}
bool Earth::Update(float dt)
{
return true;
}
bool Earth::PostUpdate()
{
app->render->DrawTexture(earthTex, (int)spawnPos.x, (int)spawnPos.y, ¤tAnim->GetCurrentFrame(), 1.0f);
//colliderEarth->SetPos(rect.x, rect.y);
return true;
}
bool Earth::CleanUp()
{
app->tex->UnLoad(earthTex);
/*if (colliderPlayer != nullptr)
colliderPlayer->toDelete = true;*/
return true;
}
iPoint Earth::GetPos() const
{
return spawnPos;
}
void Earth::OnCollision(Collider* col1, Collider* col2) { app->physicsEngine->doCollisions(col1, col2); }
void Earth::LoadAnim()
{
earthAnim.PushBack({ 0, 0, 300, 300 });
earthAnim.PushBack({ 300, 0, 300, 300 });
earthAnim.PushBack({ 600, 0, 300, 300 });
earthAnim.PushBack({ 900, 0, 300, 300 });
earthAnim.PushBack({ 1200, 0, 300, 300 });
earthAnim.PushBack({ 1500, 0, 300, 300 });
earthAnim.PushBack({ 1800, 0, 300, 300 });
earthAnim.PushBack({ 2100, 0, 300, 300 });
earthAnim.PushBack({ 2400, 0, 300, 300 });
earthAnim.PushBack({ 2700, 0, 300, 300 });
earthAnim.PushBack({ 3000, 0, 300, 300 });
earthAnim.PushBack({ 3300, 0, 300, 300 });
earthAnim.PushBack({ 3600, 0, 300, 300 });
earthAnim.PushBack({ 3900, 0, 300, 300 });
earthAnim.PushBack({ 4200, 0, 300, 300 });
earthAnim.PushBack({ 4500, 0, 300, 300 });
earthAnim.PushBack({ 4800, 0, 300, 300 });
earthAnim.PushBack({ 5100, 0, 300, 300 });
earthAnim.PushBack({ 5400, 0, 300, 300 });
earthAnim.PushBack({ 5700, 0, 300, 300 });
earthAnim.PushBack({ 6000, 0, 300, 300 });
earthAnim.PushBack({ 6300, 0, 300, 300 });
earthAnim.PushBack({ 6600, 0, 300, 300 });
earthAnim.PushBack({ 6900, 0, 300, 300 });
earthAnim.PushBack({ 7200, 0, 300, 300 });
earthAnim.PushBack({ 7500, 0, 300, 300 });
earthAnim.PushBack({ 7800, 0, 300, 300 });
earthAnim.PushBack({ 8100, 0, 300, 300 });
earthAnim.PushBack({ 8400, 0, 300, 300 });
earthAnim.PushBack({ 8700, 0, 300, 300 });
earthAnim.PushBack({ 9000, 0, 300, 300 });
earthAnim.PushBack({ 9300, 0, 300, 300 });
earthAnim.PushBack({ 9600, 0, 300, 300 });
earthAnim.PushBack({ 9900, 0, 300, 300 });
earthAnim.PushBack({ 10200, 0, 300, 300 });
earthAnim.PushBack({ 10500, 0, 300, 300 });
earthAnim.PushBack({ 10800, 0, 300, 300 });
earthAnim.PushBack({ 11100, 0, 300, 300 });
earthAnim.PushBack({ 11400, 0, 300, 300 });
earthAnim.PushBack({ 11700, 0, 300, 300 });
earthAnim.PushBack({ 12000, 0, 300, 300 });
earthAnim.PushBack({ 12300, 0, 300, 300 });
earthAnim.PushBack({ 12600, 0, 300, 300 });
earthAnim.PushBack({ 12900, 0, 300, 300 });
earthAnim.PushBack({ 13200, 0, 300, 300 });
earthAnim.PushBack({ 13500, 0, 300, 300 });
earthAnim.PushBack({ 13800, 0, 300, 300 });
earthAnim.PushBack({ 14100, 0, 300, 300 });
earthAnim.PushBack({ 14400, 0, 300, 300 });
earthAnim.PushBack({ 14700, 0, 300, 300 });
earthAnim.speed = 0.05f;
}
| 26.696296 | 109 | 0.639567 | oscarrep |
0bb3728202eb5f4143909fe0d369ec8bb29b8af2 | 789 | cpp | C++ | books/tech/cpp/qt/m_shlee-qt_5_10/ch_16-artificial_event_creating/02-mousepress_imitation/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | books/tech/cpp/qt/m_shlee-qt_5_10/ch_16-artificial_event_creating/02-mousepress_imitation/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | books/tech/cpp/qt/m_shlee-qt_5_10/ch_16-artificial_event_creating/02-mousepress_imitation/main.cpp | ordinary-developer/education | 1b1f40dacab873b28ee01dfa33a9bd3ec4cfed58 | [
"MIT"
] | null | null | null | #include "ExampleWidget.hpp"
#include <QApplication>
#include <QWidget>
#include <QMouseEvent>
namespace {
void local_mousePress(
QWidget *pWgt,
int x,
int y,
Qt::MouseButton bt = Qt::LeftButton,
Qt::MouseButtons bts = Qt::LeftButton)
{
if (not pWgt)
return;
QMouseEvent *pMousePressEvent =
new QMouseEvent(
QEvent::MouseButtonPress,
QPoint(x, y),
bt,
bts,
Qt::NoModifier);
QApplication::postEvent(pWgt, pMousePressEvent);
}
} // unonymous
int main(int argc, char **argv) {
QApplication app{ argc, argv };
ExampleWidget wgt{};
wgt.resize(250, 130);
wgt.show();
local_mousePress(&wgt, 125, 65);
return app.exec();
} | 18.348837 | 52 | 0.57161 | ordinary-developer |
0bbbfc67d67914a3522ef4cf89049db97ac5f82f | 401 | inl | C++ | src/ace/ACE_wrappers/ace/Token_Manager.inl | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | 8 | 2017-06-05T08:56:27.000Z | 2020-04-08T16:50:11.000Z | src/ace/ACE_wrappers/ace/Token_Manager.inl | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | null | null | null | src/ace/ACE_wrappers/ace/Token_Manager.inl | wfnex/OpenBRAS | b8c2cd836ae85d5307f7f5ca87573b964342bb49 | [
"BSD-3-Clause"
] | 17 | 2017-06-05T08:54:27.000Z | 2021-08-29T14:19:12.000Z | // -*- C++ -*-
#if defined (ACE_HAS_TOKENS_LIBRARY)
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_INLINE ACE_TOKEN_CONST::MUTEX &
ACE_Token_Manager::mutex (void)
{
ACE_TRACE ("ACE_Token_Manager::mutex");
return lock_;
}
ACE_INLINE void
ACE_Token_Manager::debug (bool d)
{
ACE_TRACE ("ACE_Token_Manager::debug");
debug_ = d;
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif /* ACE_HAS_TOKENS_LIBRARY */
| 17.434783 | 41 | 0.753117 | wfnex |
0bbe34b7b9a7544c1845a05e3975c9d1b5d51525 | 15,308 | cpp | C++ | dp/sg/core/src/Group.cpp | siddharthuniv/nv-propipeline | 1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef | [
"BSD-3-Clause"
] | null | null | null | dp/sg/core/src/Group.cpp | siddharthuniv/nv-propipeline | 1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef | [
"BSD-3-Clause"
] | null | null | null | dp/sg/core/src/Group.cpp | siddharthuniv/nv-propipeline | 1553a1aebdbef6cd5c7557574a7e4bdfcf17e0ef | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2002-2016, NVIDIA CORPORATION. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <dp/sg/core/Group.h>
#include <dp/sg/core/ClipPlane.h>
#include <dp/sg/core/LightSource.h>
using namespace dp::math;
namespace dp
{
namespace sg
{
namespace core
{
BEGIN_REFLECTION_INFO( Group )
DERIVE_STATIC_PROPERTIES( Group, Node )
END_REFLECTION_INFO
GroupSharedPtr Group::create()
{
return( std::shared_ptr<Group>( new Group() ) );
}
HandledObjectSharedPtr Group::clone() const
{
return( std::shared_ptr<Group>( new Group( *this ) ) );
}
Group::Group()
{
m_objectCode = ObjectCode::GROUP;
}
Group::Group(const Group& rhs)
: Node(rhs)
{
m_objectCode = ObjectCode::GROUP;
copyChildren(rhs.m_children);
copyClipPlanes(rhs.m_clipPlanes);
}
Group::~Group()
{
removeChildren();
removeClipPlanes();
}
void Group::preRemoveChild(unsigned int index)
{
notify( Event( this->getSharedPtr<Group>(), Event::Type::PRE_CHILD_REMOVE, m_children[index], index ) );
}
void Group::postRemoveChild(unsigned int index)
{
}
void Group::preAddChild(unsigned int index)
{
}
void Group::postAddChild(unsigned int index)
{
notify( Event( this->getSharedPtr<Group>(), Event::Type::POST_CHILD_ADD, m_children[index], index ) );
}
Group::ChildrenContainer::iterator Group::doInsertChild( const ChildrenContainer::iterator & gcci, const NodeSharedPtr & child )
{
DP_ASSERT( child );
unsigned int idx = dp::checked_cast<unsigned int>(std::distance( m_children.begin(), gcci ));
preAddChild( idx );
ChildrenContainer::iterator position = m_children.insert( gcci, child );
child->attach( this );
postAddChild( idx );
return( position );
}
Group::ChildrenContainer::iterator Group::doRemoveChild( const ChildrenContainer::iterator & cci )
{
unsigned int idx = dp::checked_cast<unsigned int>(std::distance<ChildrenContainer::iterator>( m_children.begin(), cci ));
preRemoveChild( idx );
(*cci)->detach( this );
ChildrenContainer::iterator ret = m_children.erase( cci );
postRemoveChild( idx );
return( ret );
}
Group::ChildrenContainer::iterator Group::doReplaceChild( ChildrenContainer::iterator & cci, const NodeSharedPtr & newChild )
{
DP_ASSERT( newChild );
newChild->attach( this );
(*cci)->detach( this );
unsigned int idx = dp::checked_cast<unsigned int>(std::distance<ChildrenContainer::iterator>( m_children.begin(), cci ));
notify( Event( this->getSharedPtr<Group>(), Event::Type::PRE_CHILD_REMOVE, m_children[idx], idx ) );
*cci = newChild;
notify( Event( this->getSharedPtr<Group>(), Event::Type::POST_CHILD_ADD, m_children[idx], idx ) );
return( cci );
}
Group::ChildrenIterator Group::insertChild( const ChildrenIterator & gci, const NodeSharedPtr & child )
{
return( ChildrenIterator( doInsertChild( gci.m_iter, child ) ) );
}
bool Group::removeChild( const NodeSharedPtr & child )
{
bool removed = false;
for ( ChildrenContainer::iterator cci = find( m_children.begin(), m_children.end(), child )
; cci != m_children.end()
; cci = find( cci, m_children.end(), child ) // continue searching to find all occurrences
)
{
cci = doRemoveChild( cci );
removed = true;
}
return( removed );
}
Group::ChildrenIterator Group::removeChild( const ChildrenIterator & ci )
{
return( ChildrenIterator( ci.m_iter != m_children.end() ? doRemoveChild( ci.m_iter ) : m_children.end() ) );
}
bool Group::replaceChild( const NodeSharedPtr & newChild, const NodeSharedPtr & oldChild )
{
if ( newChild != oldChild )
{
bool replaced = false;
for ( ChildrenContainer::iterator cci = find( m_children.begin(), m_children.end(), oldChild )
; cci != m_children.end()
; cci = find( cci, m_children.end(), oldChild ) // continue searching to find all occurrences
)
{
cci = doReplaceChild( cci, newChild );
replaced = true;
}
return( replaced );
}
return( false );
}
bool Group::replaceChild( const NodeSharedPtr & newChild, ChildrenIterator & oldChildIterator )
{
if ( ( oldChildIterator.m_iter != m_children.end() ) && ( newChild != *oldChildIterator ) )
{
doReplaceChild( oldChildIterator.m_iter, newChild );
return( true );
}
return( false );
}
void Group::clearChildren()
{
for ( ChildrenContainer::iterator cci = m_children.begin() ; cci != m_children.end() ; ++cci )
{
// this is nearly a nop if the bounding volumes are already dirty and cheap in comparison to what happens int he background
// if the observer calls getBounding*() it's necessary that the dirty flag has already been set.
notify( Event( this->getSharedPtr<Group>(), Event::Type::PRE_CHILD_REMOVE, m_children[0], 0 ) );
(*cci)->detach( this );
}
m_children.clear();
}
Box3f Group::calculateBoundingBox() const
{
Box3f bbox;
for ( ChildrenContainer::const_iterator it = m_children.begin() ; it!=m_children.end() ; ++it )
{
bbox = boundingBox(bbox, (*it)->getBoundingBox());
}
return( bbox );
}
Sphere3f Group::calculateBoundingSphere() const
{
Sphere3f sphere;
if ( ! m_children.empty() )
{
std::vector<dp::math::Sphere3f> spheres;
spheres.reserve( m_children.size() );
for ( ChildrenContainer::const_iterator it = m_children.begin() ; it!=m_children.end() ; ++it )
{
spheres.push_back( (*it)->getBoundingSphere() );
}
sphere = boundingSphere( &spheres[0], dp::checked_cast<unsigned int>(spheres.size()) );
}
return( sphere );
}
unsigned int Group::determineHintsContainment( unsigned int hints ) const
{
unsigned int containment = Node::determineHintsContainment( hints );
for ( size_t i=0 ; ( (containment & hints ) != hints ) && i<m_children.size() ; i++ )
{
containment |= m_children[i]->getContainedHints( hints );
}
return( containment );
}
void Group::copyChildren(const ChildrenContainer & children)
{
DP_ASSERT(m_children.empty());
// copy children from source object and add reference for each
m_children.resize(children.size()); // allocate destination range
for ( size_t i=0; i<children.size(); ++i )
{
m_children[i] = std::static_pointer_cast<dp::sg::core::Node>(children[i]->clone());
m_children[i]->attach( this );
}
}
void Group::copyClipPlanes(const ClipPlaneContainer & clipPlanes)
{
DP_ASSERT(m_clipPlanes.empty());
// copy clipping planes from source object and add reference for each
m_clipPlanes.resize(clipPlanes.size()); // allocate destination range
for ( size_t i=0 ; i<clipPlanes.size() ; i++ )
{
m_clipPlanes[i] = std::static_pointer_cast<dp::sg::core::ClipPlane>(clipPlanes[i]->clone());
m_clipPlanes[i]->attach( this );
}
}
Group & Group::operator=(const Group & rhs)
{
if (&rhs != this)
{
Node::operator=(rhs);
removeChildren();
removeClipPlanes();
copyChildren(rhs.m_children);
copyClipPlanes(rhs.m_clipPlanes);
notify( Event( this->getSharedPtr<Group>(), Event::Type::POST_GROUP_EXCHANGED ) );
}
return *this;
}
bool Group::isEquivalent( ObjectSharedPtr const& object, bool ignoreNames, bool deepCompare ) const
{
if ( object.get() == this )
{
return( true );
}
bool equi = std::dynamic_pointer_cast<Group>(object) && Node::isEquivalent( object, ignoreNames, deepCompare );
if ( equi )
{
GroupSharedPtr const& g = std::static_pointer_cast<Group>(object);
equi = ( m_children.size() == g->m_children.size() )
&& ( m_clipPlanes.size() == g->m_clipPlanes.size() );
if ( deepCompare )
{
for ( ChildrenContainer::const_iterator lhsit = m_children.begin() ; equi && lhsit != m_children.end() ; ++lhsit )
{
bool found = false;
for ( ChildrenContainer::const_iterator rhsit = g->m_children.begin() ; !found && rhsit != g->m_children.end() ; ++rhsit )
{
found = (*lhsit)->isEquivalent( *rhsit, ignoreNames, true );
}
equi = found;
}
for ( ClipPlaneContainer::const_iterator lhsit = m_clipPlanes.begin() ; equi && lhsit != m_clipPlanes.end() ; ++lhsit )
{
bool found = false;
for ( ClipPlaneContainer::const_iterator rhsit = g->m_clipPlanes.begin() ; !found && rhsit != g->m_clipPlanes.end() ; ++rhsit )
{
found = (*lhsit)->isEquivalent( *rhsit, ignoreNames, true );
}
equi = found;
}
}
else
{
for ( ChildrenContainer::const_iterator lhsit = m_children.begin() ; equi && lhsit != m_children.end() ; ++lhsit )
{
bool found = false;
for ( ChildrenContainer::const_iterator rhsit = g->m_children.begin() ; !found && rhsit != g->m_children.end() ; ++rhsit )
{
found = ( *lhsit == *rhsit );
}
equi = found;
}
for ( ClipPlaneContainer::const_iterator lhsit = m_clipPlanes.begin() ; equi && lhsit != m_clipPlanes.end() ; ++lhsit )
{
bool found = false;
for ( ClipPlaneContainer::const_iterator rhsit = g->m_clipPlanes.begin() ; !found && rhsit != g->m_clipPlanes.end() ; ++rhsit )
{
found = ( *lhsit == *rhsit );
}
equi = found;
}
}
}
return( equi );
}
unsigned int Group::getNumberOfActiveClipPlanes() const
{
unsigned int noacp = 0;
DP_ASSERT( m_clipPlanes.size() <= UINT_MAX );
for ( unsigned int i=0 ; i<m_clipPlanes.size() ; i++ )
{
if ( m_clipPlanes[i]->isEnabled() )
{
noacp++;
}
}
return( noacp );
}
Group::ClipPlaneIterator Group::addClipPlane( const ClipPlaneSharedPtr & plane )
{
ClipPlaneContainer::iterator cpci = find( m_clipPlanes.begin(), m_clipPlanes.end(), plane );
if ( cpci == m_clipPlanes.end() )
{
plane->attach( this );
m_clipPlanes.push_back( plane );
cpci = m_clipPlanes.end() - 1;
notify( Group::Event( this->getSharedPtr<Group>(), Group::Event::Type::CLIP_PLANES_CHANGED ) );
}
return( ClipPlaneIterator( cpci ) );
}
Group::ClipPlaneContainer::iterator Group::doRemoveClipPlane( const ClipPlaneContainer::iterator & cpci )
{
(*cpci)->detach( this );
Group::ClipPlaneContainer::iterator it = m_clipPlanes.erase( cpci );
notify( Group::Event( this->getSharedPtr<Group>(), Group::Event::Type::CLIP_PLANES_CHANGED ) );
return it;
}
bool Group::removeClipPlane( const ClipPlaneSharedPtr & plane )
{
DP_ASSERT( plane );
ClipPlaneContainer::iterator cpci = find( m_clipPlanes.begin(), m_clipPlanes.end(), plane );
if ( cpci != m_clipPlanes.end() )
{
doRemoveClipPlane( cpci );
return( true );
}
return( false );
}
Group::ClipPlaneIterator Group::removeClipPlane( const ClipPlaneIterator & cpi )
{
if ( cpi.m_iter != m_clipPlanes.end() )
{
return( ClipPlaneIterator( doRemoveClipPlane( cpi.m_iter ) ) );
}
return( cpi );
}
void Group::clearClipPlanes()
{
unsigned int dirtyBits = 0;
for ( ClipPlaneContainer::iterator cpci = m_clipPlanes.begin() ; cpci != m_clipPlanes.end() ; ++cpci )
{
(*cpci)->detach( this );
}
m_clipPlanes.clear();
notify( Group::Event( this->getSharedPtr<Group>(), Group::Event::Type::CLIP_PLANES_CHANGED ) );
}
void Group::removeChildren()
{
for ( ChildrenContainer::iterator it = m_children.begin(); it != m_children.end(); ++it )
{
(*it)->detach( this );
}
m_children.clear();
}
void Group::removeClipPlanes()
{
for ( ClipPlaneContainer::iterator it = m_clipPlanes.begin(); it != m_clipPlanes.end(); ++it )
{
(*it)->detach( this );
}
m_clipPlanes.clear();
}
void Group::feedHashGenerator( util::HashGenerator & hg ) const
{
Node::feedHashGenerator( hg );
for ( size_t i=0 ; i<m_children.size() ; ++i )
{
hg.update( m_children[i] );
}
for ( size_t i=0 ; i<m_clipPlanes.size() ; ++i )
{
hg.update( m_clipPlanes[i] );
}
}
} // namespace core
} // namespace sg
} // namespace dp
| 35.271889 | 141 | 0.580611 | siddharthuniv |
0bc051eb40fb091fb2efb19ecfc629f49dc6072a | 402 | hpp | C++ | ProxyServer/ServerConnection.hpp | pentaflops/MP.Proxy-server | 95e01f0af9bcda6d3b5973f60529940213e7426c | [
"MIT"
] | null | null | null | ProxyServer/ServerConnection.hpp | pentaflops/MP.Proxy-server | 95e01f0af9bcda6d3b5973f60529940213e7426c | [
"MIT"
] | null | null | null | ProxyServer/ServerConnection.hpp | pentaflops/MP.Proxy-server | 95e01f0af9bcda6d3b5973f60529940213e7426c | [
"MIT"
] | null | null | null | #pragma once
#include "IConnection.hpp"
class ServerConnection : public IConnection
{
public:
ServerConnection(sockaddr_in sock_addr) : IConnection(INVALID_SOCKET, sock_addr, false) {};
~ServerConnection() { closesocket(_socket); }
int Connecting();
int GetData(char *buffer, int size_of_buffer, Event *_Event = nullptr);
void SendData(const char *buffer, int len, Event *_Event = nullptr);
}; | 26.8 | 92 | 0.753731 | pentaflops |
0bc184976766e9d7faafab07a0a561918faa1994 | 1,185 | hpp | C++ | src/interfaces/blkInterfaces.hpp | lhb8125/HSF | f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999 | [
"Apache-2.0"
] | null | null | null | src/interfaces/blkInterfaces.hpp | lhb8125/HSF | f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999 | [
"Apache-2.0"
] | null | null | null | src/interfaces/blkInterfaces.hpp | lhb8125/HSF | f0cea44691a0e41bdeb5613a2d5a6cd7cda0a999 | [
"Apache-2.0"
] | null | null | null | /**
* @file: blkInterfaces.hpp
* @author: Liu Hongbin
* @brief: block topology interfaces
* @date: 2019-11-11 10:56:28
* @last Modified by: lhb8125
* @last Modified time: 2020-05-27 10:52:53
*/
#ifndef BLKINTERFACES_HPP
#define BLKINTERFACES_HPP
#include "interface.hpp"
#include "utilities.hpp"
#include "mesh.hpp"
extern "C"
{
void get_ele_blk_num_(label *ele_blk_num);
void get_ele_blk_pos_(label *ele_blk_pos);
void get_ele_blk_type_(label *ele_blk_type);
void get_ele_2_ele_blk_(label *ele_2_ele);
void get_ele_2_face_blk_(label *ele_2_face);
void get_ele_2_node_blk_(label *ele_2_node);
void get_inn_face_blk_num_(label *face_blk_num);
void get_inn_face_blk_pos_(label *face_blk_pos);
void get_inn_face_blk_type_(label *face_blk_type);
void get_inn_face_2_node_blk_(label *face_2_node);
void get_inn_face_2_ele_blk_(label *face_2_ele);
void get_bnd_face_blk_num_(label *bnd_face_blk_num);
void get_bnd_face_blk_pos_(label *bnd_face_blk_pos);
void get_bnd_face_blk_type_(label *bnd_face_blk_type);
void get_bnd_face_2_node_blk_(label *bnd_face_2_node);
void get_bnd_face_2_ele_blk_(label *bnd_face_2_ele);
void get_bnd_type_(label *bnd_type);
}
#endif | 20.084746 | 54 | 0.795781 | lhb8125 |
0bc201a2aaba3aff1ea49f34e1a6ef9e419a2fc3 | 5,691 | cpp | C++ | Tools/TestWebKitAPI/Tests/JavaScriptCore/PropertySlot.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Tools/TestWebKitAPI/Tests/JavaScriptCore/PropertySlot.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Tools/TestWebKitAPI/Tests/JavaScriptCore/PropertySlot.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2020 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include <JavaScriptCore/InitializeThreading.h>
#include <JavaScriptCore/JSCJSValueInlines.h>
#include <JavaScriptCore/PropertySlot.h>
#include <JavaScriptCore/VM.h>
namespace TestWebKitAPI {
using JSC::JSLockHolder;
using JSC::LargeHeap;
using JSC::PropertySlot;
using JSC::VM;
using JSC::jsUndefined;
TEST(JavaScriptCore_PropertySlot, DisallowVMEntryCountBasic)
{
WTF::initializeMainThread();
JSC::initialize();
VM& vm = VM::create(LargeHeap).leakRef();
{
JSLockHolder locker(vm);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
{
PropertySlot slot(jsUndefined(), PropertySlot::InternalMethodType::Get);
EXPECT_FALSE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
{
PropertySlot slot(jsUndefined(), PropertySlot::InternalMethodType::HasProperty);
EXPECT_FALSE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
{
PropertySlot slot(jsUndefined(), PropertySlot::InternalMethodType::GetOwnProperty);
EXPECT_FALSE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
{
PropertySlot slot(jsUndefined(), PropertySlot::InternalMethodType::VMInquiry, &vm);
EXPECT_TRUE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 1u);
}
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
}
TEST(JavaScriptCore_PropertySlot, VMInquiryReset)
{
WTF::initializeMainThread();
JSC::initialize();
VM& vm = VM::create(LargeHeap).leakRef();
{
JSLockHolder locker(vm);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
{
PropertySlot slot(jsUndefined(), PropertySlot::InternalMethodType::VMInquiry, &vm);
EXPECT_TRUE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 1u);
slot.disallowVMEntry.reset();
EXPECT_FALSE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
}
TEST(JavaScriptCore_PropertySlot, CopyAssignment)
{
WTF::initializeMainThread();
JSC::initialize();
VM& vm = VM::create(LargeHeap).leakRef();
{
JSLockHolder locker(vm);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
{
PropertySlot slot(jsUndefined(), PropertySlot::InternalMethodType::Get);
EXPECT_FALSE(slot.isVMInquiry());
EXPECT_FALSE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
{
PropertySlot slot2 = slot;
EXPECT_FALSE(slot.isVMInquiry());
EXPECT_FALSE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
slot = slot2;
EXPECT_FALSE(slot.isVMInquiry());
EXPECT_FALSE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
EXPECT_FALSE(slot.isVMInquiry());
EXPECT_FALSE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
{
PropertySlot slot(jsUndefined(), PropertySlot::InternalMethodType::VMInquiry, &vm);
EXPECT_TRUE(slot.isVMInquiry());
EXPECT_TRUE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 1u);
{
PropertySlot slot2 = slot;
EXPECT_TRUE(slot2.isVMInquiry());
EXPECT_TRUE(!!slot2.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 2u);
slot = slot2;
EXPECT_TRUE(slot.isVMInquiry());
EXPECT_TRUE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 2u);
}
EXPECT_TRUE(slot.isVMInquiry());
EXPECT_TRUE(!!slot.disallowVMEntry);
EXPECT_EQ(vm.disallowVMEntryCount, 1u);
}
EXPECT_EQ(vm.disallowVMEntryCount, 0u);
}
}
} // namespace TestWebKitAPI
| 34.91411 | 95 | 0.649622 | jacadcaps |
0bc56f7850f9328451792dc7772a87e25c650411 | 43,836 | hpp | C++ | lualite.hpp | user1095108/lualite | 17c2d07f1fa315129cdb32ad000ca305488fac39 | [
"Unlicense"
] | 58 | 2016-09-24T13:08:08.000Z | 2022-02-07T04:17:53.000Z | lualite.hpp | user1095108/lualite | 17c2d07f1fa315129cdb32ad000ca305488fac39 | [
"Unlicense"
] | 2 | 2015-05-27T03:39:53.000Z | 2016-06-15T10:07:32.000Z | lualite.hpp | user1095108/lualite | 17c2d07f1fa315129cdb32ad000ca305488fac39 | [
"Unlicense"
] | 4 | 2016-11-25T04:40:57.000Z | 2019-10-14T21:28:01.000Z | /*
** This is free and unencumbered software released into the public domain.
** Anyone is free to copy, modify, publish, use, compile, sell, or
** distribute this software, either in source code form or as a compiled
** binary, for any purpose, commercial or non-commercial, and by any
** means.
** In jurisdictions that recognize copyright laws, the author or authors
** of this software dedicate any and all copyright interest in the
** software to the public domain. We make this dedication for the benefit
** of the public at large and to the detriment of our heirs and
** successors. We intend this dedication to be an overt act of
** relinquishment in perpetuity of all present and future rights to this
** software under copyright law.
** 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 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.
** For more information, please refer to <http://unlicense.org/>
*/
#ifndef LUALITE_HPP
# define LUALITE_HPP
# pragma once
#if __cplusplus < 201402L
# error "You need a C++14 compiler to use lualite"
#endif // __cplusplus
#include <cassert>
#include <cstring>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#ifndef LUALITE_NO_STD_CONTAINERS
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#endif // LUALITE_NO_STD_CONTAINERS
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
namespace lualite
{
#ifndef LLFUNC
# define LLFUNC(f) decltype(&f),&f
#endif // LLFUNC
struct any { };
class scope;
template <class C> class class_;
static constexpr auto const default_nrec = 10;
namespace
{
template <typename T>
using is_function_pointer =
std::integral_constant<bool,
std::is_pointer<T>{} &&
std::is_function<std::remove_pointer_t<T>>{}
>;
template <typename T>
using is_nc_reference =
std::integral_constant<bool,
std::is_reference<T>{} &&
!std::is_const<std::remove_reference_t<T>>{}
>;
struct swallow
{
template <typename ...T>
constexpr explicit swallow(T&& ...) noexcept
{
}
};
// key is at the top of the stack
inline void rawgetfield(lua_State* const L, int const index,
char const* const key) noexcept
{
auto const i(lua_absindex(L, index));
lua_pushstring(L, key);
lua_rawget(L, i);
}
// value is at the top of the stack, key is shifted below the top
inline void rawsetfield(lua_State* const L, int const index,
char const* const key) noexcept
{
auto const i(lua_absindex(L, index));
lua_pushstring(L, key);
lua_insert(L, -2);
lua_rawset(L, i);
}
constexpr inline auto hash(char const* s, std::size_t h = {}) noexcept
{
while (*s)
{
h ^= (h << 5) + (h >> 2) + static_cast<unsigned char>(*s++);
}
return h;
}
struct str_eq
{
bool operator()(char const* const s1, char const* const s2) const noexcept
{
return !std::strcmp(s1, s2);
}
};
struct str_hash
{
constexpr std::size_t operator()(char const* s) const noexcept
{
return hash(s);
}
};
template <typename T>
class scope_exit
{
T const f_;
public:
explicit scope_exit(T&& f) noexcept : f_(std::forward<T>(f))
{
static_assert(noexcept(f_()), "throwing functors are unsupported");
}
~scope_exit() noexcept { f_(); }
};
template <typename T>
inline scope_exit<T> make_scope_exit(T&& f) noexcept
{
return scope_exit<T>(std::forward<T>(f));
}
}
enum property_type : unsigned
{
BOOLEAN,
INTEGER,
NUMBER,
STRING,
OTHER
};
struct constant_info_type
{
enum property_type type;
union
{
bool boolean;
lua_Integer integer;
lua_Number number;
char const* string;
} u;
};
using constants_type = std::vector<std::pair<char const* const,
struct constant_info_type> >;
struct func_info_type
{
char const* const name;
lua_CFunction const callback;
};
using map_member_info_type = lua_CFunction;
using member_info_type = func_info_type;
template <class C>
int getter(lua_State* const L)
{
assert(2 == lua_gettop(L));
auto const i(lualite::class_<C>::getters().find(lua_tostring(L, 2)));
if (lualite::class_<C>::getters().end() == i)
{
return {};
}
else
{
auto const uvi(lua_upvalueindex(2));
void* p(lua_touserdata(L, uvi));
auto const q(p);
for (auto const f: std::get<0>(i->second))
{
p = f(p);
}
lua_pushlightuserdata(L, p);
lua_replace(L, uvi);
auto const se(
make_scope_exit(
[&]() noexcept {
lua_pushlightuserdata(L, q); lua_replace(L, uvi);
}
)
);
return std::get<1>(i->second)(L);
}
}
template <class C>
int setter(lua_State* const L)
{
assert(3 == lua_gettop(L));
auto const i(lualite::class_<C>::setters().find(lua_tostring(L, 2)));
if (lualite::class_<C>::setters().end() != i)
{
auto const uvi(lua_upvalueindex(2));
void* p(lua_touserdata(L, uvi));
auto const q(p);
for (auto const f: std::get<0>(i->second))
{
p = f(p);
}
lua_pushlightuserdata(L, p);
lua_replace(L, uvi);
auto const se(make_scope_exit([&]() noexcept {
lua_pushlightuserdata(L, q); lua_replace(L, uvi);})
);
std::get<1>(i->second)(L);
}
// else do nothing
return {};
}
template <class C>
inline void create_wrapper_table(lua_State* const L, C* const instance)
{
auto const uvi(lua_upvalueindex(1));
lua_pushvalue(L, uvi);
if (lua_isnil(L, -1))
{
lua_createtable(L, 0, default_nrec);
for (auto& mi: lualite::class_<C>::defs())
{
assert(lua_istable(L, -1));
lua_pushnil(L);
void* p(instance);
for (auto const f: mi.first)
{
p = f(p);
}
lua_pushlightuserdata(L, p);
lua_pushcclosure(L, mi.second.callback, 2);
rawsetfield(L, -2, mi.second.name);
}
// metatable
assert(lua_istable(L, -1));
lua_createtable(L, 0, 2);
// getters
assert(lua_istable(L, -1));
lua_pushnil(L);
lua_pushlightuserdata(L, instance);
lua_pushcclosure(L, getter<C>, 2);
rawsetfield(L, -2, "__index");
// setters
assert(lua_istable(L, -1));
lua_pushnil(L);
lua_pushlightuserdata(L, instance);
lua_pushcclosure(L, setter<C>, 2);
rawsetfield(L, -2, "__newindex");
lua_setmetatable(L, -2);
lua_copy(L, -1, uvi);
}
// else do nothing
assert(lua_istable(L, uvi));
assert(lua_istable(L, -1));
}
template <typename T>
inline std::enable_if_t<
std::is_floating_point<std::decay_t<T>>{} &&
!is_nc_reference<T>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
lua_pushnumber(L, v);
return 1;
}
template <typename T>
inline std::enable_if_t<
std::is_integral<std::decay_t<T>>{} &&
!std::is_same<std::decay_t<T>, bool>{} &&
!is_nc_reference<T>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
lua_pushinteger(L, v);
return 1;
}
template <typename T>
inline std::enable_if_t<
std::is_same<std::decay_t<T>, bool>{} &&
!is_nc_reference<T>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
lua_pushboolean(L, v);
return 1;
}
template <typename T>
inline std::enable_if_t<
std::is_same<std::decay_t<T>, char const*>{} &&
!is_nc_reference<T>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
lua_pushstring(L, v);
return 1;
}
template <typename T>
inline std::enable_if_t<
std::is_same<std::decay_t<T>, void const*>{} &&
!is_nc_reference<T>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
lua_pushlightuserdata(L, const_cast<void*>(v));
return 1;
}
template <typename T>
inline std::enable_if_t<
std::is_pointer<T>{} &&
!std::is_const<std::remove_pointer_t<T>>{} &&
!std::is_class<std::remove_pointer_t<T>>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
lua_pushlightuserdata(L, v);
return 1;
}
template <typename T>
inline std::enable_if_t<
is_nc_reference<T>{} &&
!std::is_class<std::decay_t<T>>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
lua_pushlightuserdata(L, &v);
return 1;
}
template <typename T>
inline std::enable_if_t<
std::is_pointer<std::decay_t<T>>{} &&
!std::is_const<std::remove_pointer_t<T>>{} &&
std::is_class<std::remove_pointer_t<std::decay_t<T>>>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
create_wrapper_table(L, v);
return 1;
}
template <typename T>
inline std::enable_if_t<
is_nc_reference<T>{} &&
std::is_class<std::decay_t<T>>{},
int
>
set(lua_State* const L, T&& v) noexcept
{
create_wrapper_table(L, &v);
return 1;
}
template <typename T>
inline std::enable_if_t<
std::is_same<std::decay_t<T>, any>{} &&
!is_nc_reference<T>{},
int
>
set(lua_State* const, T&&) noexcept
{
return 1;
}
template <int I, typename T>
inline std::enable_if_t<
std::is_floating_point<std::decay_t<T>>{} &&
!is_nc_reference<T>{},
std::decay_t<T>
>
get(lua_State* const L) noexcept
{
assert(lua_isnumber(L, I));
return lua_tonumber(L, I);
}
template <int I, typename T>
inline std::enable_if_t<
std::is_integral<std::decay_t<T>>{} &&
!std::is_same<std::decay_t<T>, bool>{} &&
!is_nc_reference<T>{},
std::decay_t<T>
>
get(lua_State* const L) noexcept
{
assert(lua_isnumber(L, I));
return lua_tointeger(L, I);
}
template <int I, typename T>
inline std::enable_if_t<
std::is_same<std::decay_t<T>, bool>{} &&
!is_nc_reference<T>{},
std::decay_t<T>
>
get(lua_State* const L) noexcept
{
assert(lua_isboolean(L, I));
return lua_toboolean(L, I);
}
template <int I, typename T>
inline std::enable_if_t<
std::is_same<std::decay_t<T>, char const*>{} &&
!is_nc_reference<T>{},
std::decay_t<T>
>
get(lua_State* const L) noexcept
{
assert(lua_isstring(L, I));
return lua_tostring(L, I);
}
template <int I, typename T>
inline std::enable_if_t<
std::is_pointer<T>{} &&
!std::is_same<std::decay_t<T>, char const*>{},
std::decay_t<T>
>
get(lua_State* const L) noexcept
{
assert(lua_islightuserdata(L, I));
return static_cast<T>(lua_touserdata(L, I));
}
template <int I, typename T>
inline std::enable_if_t<
is_nc_reference<T>{},
T
>
get(lua_State* const L) noexcept
{
assert(lua_islightuserdata(L, I));
return *static_cast<std::decay_t<T>*>(lua_touserdata(L, I));
}
template <int I, typename T>
inline std::enable_if_t<
std::is_same<std::remove_const_t<T>, any>{},
T
>
get(lua_State* const) noexcept
{
return {};
}
#ifndef LUALITE_NO_STD_CONTAINERS
template <typename>
struct is_std_pair : std::false_type { };
template <class T1, class T2>
struct is_std_pair<std::pair<T1, T2> > : std::true_type { };
template <typename>
struct is_std_array : std::false_type { };
template <typename T, std::size_t N>
struct is_std_array<std::array<T, N> > : std::true_type { };
template <typename>
struct is_std_deque : std::false_type { };
template <typename T, class Alloc>
struct is_std_deque<std::deque<T, Alloc> > : std::true_type { };
template <typename>
struct is_std_forward_list : std::false_type { };
template <typename T, class Alloc>
struct is_std_forward_list<std::forward_list<T, Alloc> > : std::true_type { };
template <typename>
struct is_std_list : std::false_type { };
template <typename T, class Alloc>
struct is_std_list<std::list<T, Alloc> > : std::true_type { };
template <typename>
struct is_std_map : std::false_type { };
template <class Key, class T, class Compare, class Alloc>
struct is_std_map<std::map<Key, T, Compare, Alloc> > : std::true_type { };
template <typename>
struct is_std_set : std::false_type { };
template <class Key, class Compare, class Alloc>
struct is_std_set<std::set<Key, Compare, Alloc> > : std::true_type { };
template <typename>
struct is_std_unordered_map : std::false_type { };
template <class Key, class T, class Hash, class P, class Alloc>
struct is_std_unordered_map<std::unordered_map<Key, T, Hash, P, Alloc> > :
std::true_type { };
template <typename>
struct is_std_unordered_set : std::false_type { };
template <class Key, class Hash, class Equal, class Alloc>
struct is_std_unordered_set<std::unordered_set<Key, Hash, Equal, Alloc> > :
std::true_type { };
template <typename>
struct is_std_tuple : std::false_type { };
template <class ...Types>
struct is_std_tuple<std::tuple<Types...> > : std::true_type { };
template <typename>
struct is_std_vector : std::false_type { };
template <typename T, class Alloc>
struct is_std_vector<std::vector<T, Alloc> > : std::true_type { };
template <typename T>
inline std::enable_if_t<
std::is_same<std::decay_t<T>, std::string>{} &&
!is_nc_reference<T>{},
int
>
set(lua_State* const L, T&& s) noexcept
{
lua_pushlstring(L, s.c_str(), s.size());
return 1;
}
template <typename C>
inline std::enable_if_t<
is_std_pair<std::decay_t<C>>{} &&
!is_nc_reference<C>{},
int
>
set(lua_State* const L, C&& p) noexcept(
noexcept(set(L, p.first), set(L, p.second))
)
{
set(L, p.first);
set(L, p.second);
return 2;
}
template <typename ...Types, std::size_t ...I>
inline void set_tuple_result(lua_State* const L,
std::tuple<Types...> const& t, std::index_sequence<I...> const) noexcept(
noexcept(swallow{(set(L, std::get<I>(t)), 0)...})
)
{
swallow{(set(L, std::get<I>(t)), 0)...};
}
template <typename C>
inline std::enable_if_t<
is_std_tuple<std::decay_t<C>>{} &&
!is_nc_reference<C>{},
int
>
set(lua_State* const L, C&& t) noexcept(
noexcept(
set_tuple_result(L, t,
std::make_index_sequence<std::size_t(std::tuple_size<C>{})>()
)
)
)
{
using result_type = std::decay_t<C>;
set_tuple_result(L,
t,
std::make_index_sequence<std::tuple_size<C>{}>()
);
return std::tuple_size<result_type>{};
}
template <typename C>
inline std::enable_if_t<
(is_std_array<std::decay_t<C>>{} ||
is_std_deque<std::decay_t<C>>{} ||
is_std_forward_list<std::decay_t<C>>{} ||
is_std_list<std::decay_t<C>>{} ||
is_std_vector<std::decay_t<C>>{} ||
is_std_set<std::decay_t<C>>{} ||
is_std_unordered_set<std::decay_t<C>>{}) &&
!is_nc_reference<C>{},
int
>
set(lua_State* const L, C&& c)
{
lua_createtable(L, c.size(), 0);
int j{};
auto const cend(c.cend());
for (auto i(c.cbegin()); i != cend; ++i)
{
set(L, *i);
lua_rawseti(L, -2, ++j);
}
return 1;
}
template <typename C>
inline std::enable_if_t<
(is_std_map<std::decay_t<C>>{} ||
is_std_unordered_map<std::decay_t<C>>{}) &&
!is_nc_reference<C>{},
int
>
set(lua_State* const L, C&& m)
{
lua_createtable(L, 0, m.size());
auto const cend(m.cend());
for (auto i(m.cbegin()); i != cend; ++i)
{
set(L, i->first);
set(L, i->second);
lua_rawset(L, -3);
}
return 1;
}
template <int I, class C>
inline std::enable_if_t<
std::is_same<std::decay_t<C>, std::string>{} &&
!is_nc_reference<C>{},
std::decay_t<C>
>
get(lua_State* const L)
{
assert(lua_isstring(L, I));
std::size_t len;
auto const s(lua_tolstring(L, I, &len));
return {s, len};
}
template<int I, class C>
inline std::enable_if_t<
is_std_pair<std::decay_t<C>>{} &&
!is_nc_reference<C>{},
std::decay_t<C>
>
get(lua_State* const L)
{
assert(lua_istable(L, I));
using result_type = std::decay_t<C>;
lua_rawgeti(L, -1, 1);
lua_rawgeti(L, -2, 2);
result_type const result(
get<-2, typename result_type::first_type>(L),
get<-1, typename result_type::second_type>(L)
);
lua_pop(L, 2);
return result;
}
template <std::size_t O, class C, std::size_t ...I>
inline C get_tuple_arg(lua_State* const L,
std::index_sequence<I...> const) noexcept(
noexcept(std::make_tuple(get<int(I - sizeof...(I)),
std::tuple_element_t<I, C>>(L)...)
)
)
{
swallow{(lua_rawgeti(L, O, I + 1), 0)...};
C result(std::make_tuple(get<int(I - sizeof...(I)),
std::tuple_element_t<I, C>>(L)...));
lua_pop(L, int(sizeof...(I)));
return result;
}
template <int I, class C>
inline std::enable_if_t<
is_std_tuple<std::decay_t<C>>{} &&
!is_nc_reference<C>{},
std::decay_t<C>
>
get(lua_State* const L) noexcept(
noexcept(get_tuple_arg<I,
std::decay_t<C>>(L,
std::make_index_sequence<
std::size_t(std::tuple_size<std::decay_t<C>>{})
>()
)
)
)
{
assert(lua_istable(L, I));
using result_type = std::decay_t<C>;
return get_tuple_arg<I, result_type>(L,
std::make_index_sequence<std::tuple_size<result_type>{}>()
);
}
template<int I, class C>
inline std::enable_if_t<
is_std_array<std::decay_t<C>>{} &&
!is_nc_reference<C>{},
std::decay_t<C>
>
get(lua_State* const L)
{
assert(lua_istable(L, I));
using result_type = std::decay_t<C>;
result_type result;
auto const len(std::min(lua_rawlen(L, I), lua_Unsigned(result.size())));
for (decltype(lua_rawlen(L, I)) i{}; i != len; ++i)
{
lua_rawgeti(L, I, i + 1);
result[i] = get<-1, typename result_type::value_type>(L);
}
lua_pop(L, len);
return result;
}
template <int I, class C>
inline std::enable_if_t<
(is_std_deque<std::decay_t<C>>{} ||
is_std_forward_list<std::decay_t<C>>{} ||
is_std_list<std::decay_t<C>>{}) &&
!is_nc_reference<C>{},
std::decay_t<C>
>
get(lua_State* const L)
{
assert(lua_istable(L, I));
using result_type = std::decay_t<C>;
result_type result;
auto const len(lua_rawlen(L, I));
for (auto i(len); i; --i)
{
lua_rawgeti(L, I, i);
result.emplace_front(get<-1, typename result_type::value_type>(L));
}
lua_pop(L, len);
return result;
}
template <int I, class C>
inline std::enable_if_t<
is_std_vector<std::decay_t<C>>{} &&
!is_nc_reference<C>{},
std::decay_t<C>
>
get(lua_State* const L)
{
assert(lua_istable(L, I));
using result_type = std::decay_t<C>;
result_type result;
auto const cend(lua_rawlen(L, I) + 1);
result.reserve(cend - 1);
for (decltype(lua_rawlen(L, I)) i(1); i != cend; ++i)
{
lua_rawgeti(L, I, i);
result.emplace_back(get<-1, typename result_type::value_type>(L));
}
lua_pop(L, cend - 1);
return result;
}
template <int I, class C>
inline std::enable_if_t<
(is_std_map<std::decay_t<C>>{} ||
is_std_unordered_map<std::decay_t<C>>{}) &&
!is_nc_reference<C>{},
std::decay_t<C>
>
get(lua_State* const L)
{
assert(lua_istable(L, I));
using result_type = std::decay_t<C>;
result_type result;
lua_pushnil(L);
while (lua_next(L, I))
{
result.emplace(get<-2, typename result_type::key_type>(L),
get<-1, typename result_type::mapped_type>(L)
);
lua_pop(L, 1);
}
return result;
}
template <int I, class C>
inline std::enable_if_t<
(is_std_set<std::decay_t<C>>{} ||
is_std_unordered_set<std::decay_t<C>>{}) &&
!is_nc_reference<C>{},
std::decay_t<C>
>
get(lua_State* const L)
{
assert(lua_istable(L, I));
using result_type = std::decay_t<C>;
result_type result;
auto const end(lua_rawlen(L, I) + 1);
for (decltype(lua_rawlen(L, I)) i(1); i != end; ++i)
{
lua_rawgeti(L, I, i);
result.emplace(get<-1, typename result_type::value_type>(L));
}
lua_pop(L, end - 1);
return result;
}
#endif // LUALITE_NO_STD_CONTAINERS
template <class C>
int default_finalizer(lua_State* const L)
noexcept(noexcept(std::declval<C>().~C()))
{
delete static_cast<C*>(lua_touserdata(L, lua_upvalueindex(1)));
return {};
}
template <std::size_t O, typename C, typename ...A, std::size_t ...I>
inline std::enable_if_t<bool(!sizeof...(A)), C*>
forward(lua_State* const, std::index_sequence<I...> const) noexcept(
noexcept(C())
)
{
return new C();
}
template <std::size_t O, typename C, typename ...A, std::size_t ...I>
inline std::enable_if_t<bool(sizeof...(A)), C*>
forward(lua_State* const L, std::index_sequence<I...> const) noexcept(
noexcept(C(get<I + O, A>(L)...))
)
{
return new C(get<I + O, A>(L)...);
}
template <std::size_t O, class C, class ...A>
int constructor_stub(lua_State* const L)
noexcept(noexcept(
forward<O, C, A...>(L, std::make_index_sequence<sizeof...(A)>()))
)
{
assert(sizeof...(A) == lua_gettop(L));
auto const instance(forward<O, C, A...>(L,
std::make_index_sequence<sizeof...(A)>())
);
// table
lua_createtable(L, 0, default_nrec);
for (auto& mi: lualite::class_<C>::defs())
{
assert(lua_istable(L, -1));
void* p(instance);
for (auto const f: mi.first)
{
p = f(p);
}
lua_pushnil(L);
lua_pushlightuserdata(L, p);
lua_pushcclosure(L, mi.second.callback, 2);
rawsetfield(L, -2, mi.second.name);
}
// metatable
assert(lua_istable(L, -1));
lua_createtable(L, 0, 3);
// gc
assert(lua_istable(L, -1));
lua_pushlightuserdata(L, instance);
lua_pushcclosure(L, default_finalizer<C>, 1);
rawsetfield(L, -2, "__gc");
// getters
assert(lua_istable(L, -1));
lua_pushnil(L);
lua_pushlightuserdata(L, instance);
lua_pushcclosure(L, getter<C>, 2);
rawsetfield(L, -2, "__index");
// setters
assert(lua_istable(L, -1));
lua_pushnil(L);
lua_pushlightuserdata(L, instance);
lua_pushcclosure(L, setter<C>, 2);
rawsetfield(L, -2, "__newindex");
lua_setmetatable(L, -2);
assert(lua_istable(L, -1));
return 1;
}
template <std::size_t O, typename R, typename ...A, std::size_t ...I>
inline std::enable_if_t<bool(!sizeof...(A)), R>
forward(lua_State* const, R (* const f)(A...),
std::index_sequence<I...> const) noexcept(noexcept((*f)()))
{
return (*f)();
}
template <std::size_t O, typename R, typename ...A, std::size_t ...I>
inline std::enable_if_t<bool(sizeof...(A)), R>
forward(lua_State* const L, R (* const f)(A...),
std::index_sequence<I...> const) noexcept(
noexcept((*f)(get<I + O, A>(L)...))
)
{
return (*f)(get<I + O, A>(L)...);
}
template <typename FP, FP fp, std::size_t O, class R, class ...A>
inline std::enable_if_t<std::is_void<R>{}, int>
func_stub(lua_State* const L) noexcept(
noexcept(
forward<O, R, A...>(L, fp, std::make_index_sequence<sizeof...(A)>())
)
)
{
assert(sizeof...(A) == lua_gettop(L));
forward<O, R, A...>(L, fp, std::make_index_sequence<sizeof...(A)>());
return {};
}
template <typename FP, FP fp, std::size_t O, class R, class ...A>
inline std::enable_if_t<!std::is_void<R>{}, int>
func_stub(lua_State* const L) noexcept(
noexcept(
set(L, forward<O, R, A...>(L, fp,
std::make_index_sequence<sizeof...(A)>()))
)
)
{
return set(L, forward<O, R, A...>(L, fp,
std::make_index_sequence<sizeof...(A)>()));
}
template <typename FP, FP fp, class R>
inline std::enable_if_t<!std::is_void<R>{}, int>
vararg_func_stub(lua_State* const L) noexcept(noexcept(set(fp(L))))
{
return set(fp(L));
}
template <typename FP, FP fp, class R>
inline std::enable_if_t<std::is_void<R>{}, int>
vararg_func_stub(lua_State* const L) noexcept(noexcept(fp(L)))
{
fp(L);
return {};
}
template <std::size_t O, typename C, typename R, typename ...A,
std::size_t ...I>
inline std::enable_if_t<bool(!sizeof...(A)), R>
forward(lua_State* const, C* const c,
R (C::* const ptr_to_member)(A...) const,
std::index_sequence<I...> const) noexcept(
noexcept((c->*ptr_to_member)())
)
{
return (c->*ptr_to_member)();
}
template <std::size_t O, typename C, typename R, typename ...A,
std::size_t ...I>
inline std::enable_if_t<bool(!sizeof...(A)), R>
forward(lua_State* const, C* const c,
R (C::* const ptr_to_member)(A...),
std::index_sequence<I...> const) noexcept(
noexcept((c->*ptr_to_member)())
)
{
return (c->*ptr_to_member)();
}
template <std::size_t O, typename C, typename R, typename ...A,
std::size_t ...I>
inline std::enable_if_t<bool(sizeof...(A)), R>
forward(lua_State* const L, C* const c,
R (C::* const ptr_to_member)(A...) const,
std::index_sequence<I...> const) noexcept(
noexcept((c->*ptr_to_member)(get<I + O, A>(L)...))
)
{
return (c->*ptr_to_member)(get<I + O, A>(L)...);
}
template <std::size_t O, typename C, typename R,
typename ...A, std::size_t ...I>
inline std::enable_if_t<bool(sizeof...(A)), R>
forward(lua_State* const L, C* const c,
R (C::* const ptr_to_member)(A...), std::index_sequence<I...> const)
noexcept(noexcept((c->*ptr_to_member)(get<I + O, A>(L)...)))
{
return (c->*ptr_to_member)(get<I + O, A>(L)...);
}
template <typename FP, FP fp, std::size_t O, class C, class R, class ...A>
inline std::enable_if_t<!std::is_void<R>{}, int>
member_stub(lua_State* const L) noexcept(
noexcept(set(L,
forward<O, C, R, A...>(L,
static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2))),
fp,
std::make_index_sequence<sizeof...(A)>()))
)
)
{
//std::cout << lua_gettop(L) << " " << sizeof...(A) + O - 1 << std::endl;
assert(sizeof...(A) + O - 1 == lua_gettop(L));
return set(L,
forward<O, C, R, A...>(L,
static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2))),
fp,
std::make_index_sequence<sizeof...(A)>()));
}
template <typename FP, FP fp, std::size_t O, class C, class R, class ...A>
inline std::enable_if_t<std::is_void<R>{}, int>
member_stub(lua_State* const L) noexcept(
noexcept(forward<O, C, R, A...>(L,
static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2))),
fp,
std::make_index_sequence<sizeof...(A)>())
)
)
{
assert(sizeof...(A) + O - 1 == lua_gettop(L));
forward<O, C, R, A...>(L,
static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2))),
fp,
std::make_index_sequence<sizeof...(A)>());
return {};
}
template <typename FP, FP fp, class C, class R>
inline std::enable_if_t<!std::is_void<R>{}, int>
vararg_member_stub(lua_State* const L) noexcept(
noexcept(set(L, (static_cast<C*>(
lua_touserdata(L, lua_upvalueindex(2)))->*fp)(L))
)
)
{
return set(L,
(static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2)))->*fp)(L)
);
}
template <typename FP, FP fp, class C, class R>
inline std::enable_if_t<std::is_void<R>{}, int>
vararg_member_stub(lua_State* const L) noexcept(
noexcept(
(static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2)))->*fp)(L)
)
)
{
(static_cast<C*>(lua_touserdata(L, lua_upvalueindex(2)))->*fp)(L);
return {};
}
template <typename FP, FP fp, std::size_t O, class R, class ...A>
constexpr inline lua_CFunction func_stub(R (*)(A...)) noexcept
{
return &func_stub<FP, fp, O, R, A...>;
}
template <typename FP, FP fp, std::size_t O, class R, class C, class ...A>
constexpr inline lua_CFunction member_stub(R (C::*)(A...)) noexcept
{
return &member_stub<FP, fp, O, C, R, A...>;
}
template <typename FP, FP fp, std::size_t O, class R, class C, class ...A>
constexpr inline lua_CFunction member_stub(R (C::*)(A...) const) noexcept
{
return &member_stub<FP, fp, O, C, R, A...>;
}
template <typename FP, FP fp, class R, class C>
constexpr inline lua_CFunction vararg_member_stub(R (C::*)(lua_State*)) noexcept
{
return &vararg_member_stub<FP, fp, C, R>;
}
template <typename FP, FP fp, class R, class C>
constexpr inline lua_CFunction vararg_member_stub(R (C::*)(lua_State*) const) noexcept
{
return &vararg_member_stub<FP, fp, C, R>;
}
template <typename R>
constexpr inline enum property_type get_property_type() noexcept
{
if (std::is_same<std::decay_t<R>, bool>{})
{
return BOOLEAN;
}
else if (std::is_integral<R>{})
{
return INTEGER;
}
else if (std::is_floating_point<R>{})
{
return NUMBER;
}
else if (std::is_same<R, std::string const&>{} ||
std::is_same<std::decay_t<R>, char const*>{})
{
return STRING;
}
else
{
return OTHER;
}
}
template <typename FP, FP fp, class R, class C, class ...A>
constexpr inline auto get_property_type( R (C::* const)(A...)) noexcept
{
return get_property_type<R>();
}
template <typename FP, FP fp, class R, class C, class ...A>
constexpr inline auto get_property_type(R (C::* const)(A...) const) noexcept
{
return get_property_type<R>();
}
template <typename ...A>
inline void call(lua_State* const L, int const nresults, A&& ...args)
noexcept(noexcept(swallow{(set(L, std::forward<A>(args)))...}))
{
int ac{};
swallow{
(ac += set(L, std::forward<A>(args)))...
};
assert(ac >= int(sizeof...(A)));
lua_call(L, ac, nresults);
}
class scope
{
public:
scope(char const* const name) : name_(name) { }
template <typename ...A>
scope(char const* const name, A&&... args) : name_(name)
{
swallow((args.set_parent_scope(this), 0)...);
}
scope(scope const&) = delete;
scope& operator=(scope const&) = delete;
template <typename T>
std::enable_if_t<
std::is_same<std::decay_t<T>, bool>{},
scope&
>
constant(char const* const name, T const value)
{
struct constant_info_type const ci {
BOOLEAN,
{value}
};
constants_.emplace_back(name, ci);
return *this;
}
template <typename T>
std::enable_if_t<
std::is_floating_point<std::decay_t<T>>{},
scope&
>
constant(char const* const name, T const value)
{
struct constant_info_type ci;
ci.type = NUMBER;
ci.u.number = value;
constants_.emplace_back(name, ci);
return *this;
}
template <typename T>
std::enable_if_t<
std::is_integral<std::decay_t<T>>{} &&
!std::is_same<std::decay_t<T>, bool>{},
scope&
>
constant(char const* const name, T const value)
{
struct constant_info_type ci;
ci.type = INTEGER;
ci.u.integer = value;
constants_.emplace_back(name, ci);
return *this;
}
scope& constant(char const* const name, char const* const value)
{
struct constant_info_type ci;
ci.type = STRING;
ci.u.string = value;
constants_.emplace_back(name, ci);
return *this;
}
template <typename FP, FP fp>
scope& def(char const* const name)
{
push_function<FP, fp>(name, fp);
return *this;
}
scope& enum_(char const* const name, lua_Integer const value)
{
constant(name, value);
return *this;
}
template <typename FP, FP fp>
scope& vararg_def(char const* const name)
{
push_vararg_function<FP, fp>(name, fp);
return *this;
}
protected:
virtual void apply(lua_State* const L)
{
struct S
{
static void push_constant(lua_State* const L,
decltype(constants_)::const_reference i)
{
switch (i.second.type)
{
default:
assert(0);
case BOOLEAN:
lua_pushboolean(L, i.second.u.boolean);
break;
case INTEGER:
lua_pushinteger(L, i.second.u.integer);
break;
case NUMBER:
lua_pushnumber(L, i.second.u.number);
break;
case STRING:
lua_pushstring(L, i.second.u.string);
}
}
};
if (parent_scope_)
{
scope::get_scope(L);
assert(lua_istable(L, -1));
for (auto& i: constants_)
{
assert(lua_istable(L, -1));
S::push_constant(L, i);
rawsetfield(L, -2, i.first);
}
for (auto& i: functions_)
{
assert(lua_istable(L, -1));
lua_pushnil(L);
lua_pushcclosure(L, i.callback, 1);
rawsetfield(L, -2, i.name);
}
lua_pop(L, 1);
}
else
{
for (auto& i: constants_)
{
assert(lua_istable(L, -1));
S::push_constant(L, i);
lua_setglobal(L, i.first);
}
for (auto& i: functions_)
{
lua_pushnil(L);
lua_pushcclosure(L, i.callback, 1);
lua_setglobal(L, i.name);
}
auto next(next_);
while (next)
{
next->apply(L);
next = next->next_;
}
}
assert(!lua_gettop(L));
}
void append_child_scope(scope* const instance)
{
if (next_)
{
auto next(next_);
while (next->next_)
{
next = next->next_;
}
next->next_ = instance;
}
else
{
next_ = instance;
}
}
void set_parent_scope(scope* const parent_scope)
{
parent_scope->append_child_scope(this);
parent_scope_ = parent_scope;
}
void get_scope(lua_State* const L)
{
if (parent_scope_)
{
assert(name_);
parent_scope_->get_scope(L);
if (scope_create_)
{
scope_create_ = false;
if (lua_gettop(L))
{
assert(lua_istable(L, -1));
lua_createtable(L, 0, default_nrec);
rawsetfield(L, -2, name_);
}
else
{
lua_createtable(L, 0, default_nrec);
lua_setglobal(L, name_);
}
}
// else do nothing
if (lua_gettop(L) && lua_istable(L, -1))
{
luaL_getsubtable(L, -1, name_);
lua_remove(L, -2);
}
else
{
lua_getglobal(L, name_);
}
}
else if (name_)
{
if (scope_create_)
{
scope_create_ = false;
lua_createtable(L, 0, default_nrec);
lua_setglobal(L, name_);
}
// else do nothing
lua_getglobal(L, name_);
}
// else do nothing
}
protected:
char const* const name_;
scope* parent_scope_{};
std::vector<func_info_type> functions_;
private:
template <typename FP, FP fp, typename R, typename ...A>
void push_function(char const* const name, R (* const)(A...))
{
functions_.push_back({name, func_stub<FP, fp, 1, R, A...>});
}
template <typename FP, FP fp, typename R>
void push_vararg_function(char const* const name, R (* const)(lua_State*))
{
functions_.push_back({name, vararg_func_stub<FP, fp, R>});
}
private:
friend class module;
constants_type constants_;
scope* next_{};
bool scope_create_{true};
};
class module : public scope
{
lua_State* const L_;
public:
template <typename ...A>
module(lua_State* const L, A&&... args) :
scope(nullptr),
L_(L)
{
swallow((args.set_parent_scope(this), 0)...);
scope::apply(L);
}
template <typename ...A>
module(lua_State* const L, char const* const name, A&&... args) :
scope(name),
L_(L)
{
swallow((args.set_parent_scope(this), 0)...);
scope::apply(L);
}
template <typename T>
std::enable_if_t<
std::is_same<std::decay_t<T>, bool>{},
module&
>
constant(char const* const name, T const value)
{
if (name_)
{
scope::get_scope(L_);
assert(lua_istable(L_, -1));
lua_pushboolean(L_, value);
rawsetfield(L_, -2, name);
lua_pop(L_, 1);
}
else
{
lua_pushboolean(L_, value);
lua_setglobal(L_, name);
}
return *this;
}
template <typename T>
std::enable_if_t<
std::is_floating_point<std::decay_t<T>>{},
module&
>
constant(char const* const name, T const value)
{
if (name_)
{
scope::get_scope(L_);
assert(lua_istable(L_, -1));
lua_pushnumber(L_, value);
rawsetfield(L_, -2, name);
lua_pop(L_, 1);
}
else
{
lua_pushnumber(L_, value);
lua_setglobal(L_, name);
}
return *this;
}
template <typename T>
std::enable_if_t<
std::is_integral<std::decay_t<T>>{} &&
!std::is_same<std::decay_t<T>, bool>{},
module&
>
constant(char const* const name, T const value)
{
if (name_)
{
scope::get_scope(L_);
assert(lua_istable(L_, -1));
lua_pushinteger(L_, value);
rawsetfield(L_, -2, name);
lua_pop(L_, 1);
}
else
{
lua_pushinteger(L_, value);
lua_setglobal(L_, name);
}
return *this;
}
module& constant(char const* const name, char const* const value)
{
if (name_)
{
scope::get_scope(L_);
assert(lua_istable(L_, -1));
lua_pushstring(L_, value);
rawsetfield(L_, -2, name);
lua_pop(L_, 1);
}
else
{
lua_pushstring(L_, value);
lua_setglobal(L_, name);
}
return *this;
}
template <typename FP, FP fp>
module& def(char const* const name)
{
if (name_)
{
scope::get_scope(L_);
assert(lua_istable(L_, -1));
push_function<FP, fp>(fp);
rawsetfield(L_, -2, name);
lua_pop(L_, 1);
}
else
{
push_function<FP, fp>(fp);
lua_setglobal(L_, name);
}
return *this;
}
module& enum_(char const* const name, int const value)
{
return constant(name, lua_Number(value));
}
template <typename FP, FP fp>
module& vararg_def(char const* const name)
{
if (name_)
{
scope::get_scope(L_);
assert(lua_istable(L_, -1));
push_vararg_function<FP, fp>(fp);
rawsetfield(L_, -2, name);
lua_pop(L_, 1);
}
else
{
push_vararg_function<FP, fp>(fp);
lua_setglobal(L_, name);
}
return *this;
}
private:
template <typename FP, FP fp, typename R, typename ...A>
void push_function(R (* const)(A...))
{
lua_pushnil(L_);
lua_pushcclosure(L_, func_stub<FP, fp, 1, R, A...>, 1);
}
template <typename FP, FP fp, typename R>
void push_vararg_function(R (* const)(lua_State*))
{
lua_pushnil(L_);
lua_pushcclosure(L_, vararg_func_stub<FP, fp, R>, 1);
}
};
using accessor_type = std::tuple<
std::vector<void* (*)(void*) noexcept>,
map_member_info_type,
enum property_type
>;
using accessors_type = std::unordered_map<char const*,
accessor_type,
str_hash,
str_eq
>;
using accessors_info_type = std::unordered_map<char const*,
unsigned,
str_hash,
str_eq
>;
using defs_type = std::vector<
std::pair<
std::vector<void* (*)(void*) noexcept>,
member_info_type
>
>;
template <class C>
class class_ : public scope
{
static char const* class_name_;
static std::vector<bool(*)(char const*) noexcept> inherits_;
static std::vector<func_info_type> constructors_;
static defs_type defs_;
static accessors_type getters_;
static accessors_type setters_;
public:
class_(char const* const name) : scope(name)
{
class_name_ = name;
}
template <typename T>
class_& constant(char const* const name, T&& value)
{
scope::constant(name, std::forward<T>(value));
return *this;
}
class_& constructor(char const* const name = "new")
{
return constructor<>(name);
}
template <class ...A>
class_& constructor(char const* const name = "new")
{
constructors_.push_back({name, constructor_stub<1, C, A...>});
return *this;
}
template <class ...A>
class_& inherits()
{
swallow{
(S<A>::copy_accessors(class_<A>::getters(), getters_), 0)...
};
swallow{
(S<A>::copy_accessors(class_<A>::setters(), setters_), 0)...
};
swallow{
(S<A>::copy_defs(class_<A>::defs(), defs_), 0)...
};
assert(inherits_.empty());
inherits_.reserve(sizeof...(A));
swallow{
(inherits_.push_back(class_<A>::inherits), 0)...
};
return *this;
}
static auto class_name() noexcept { return class_name_; }
static auto const& defs() noexcept { return defs_; }
static auto const& getters() noexcept { return getters_; }
static auto const& setters() noexcept { return setters_; }
auto getters_info() const
{
accessors_info_type r;
for (auto& g: getters_)
{
r.emplace(g.first, std::get<2>(g.second));
}
return r;
}
auto setters_info() const
{
accessors_info_type r;
for (auto& s: setters_)
{
r.emplace(s.first, std::get<2>(s.second));
}
return r;
}
static bool inherits(char const* const name) noexcept
{
assert(class_name_ && name);
if (std::strcmp(name, class_name_))
{
for (auto const f: inherits_)
{
if (f(name))
{
return true;
}
// else do nothing
}
return false;
}
else
{
return true;
}
}
template <typename FP, FP fp>
std::enable_if_t<
is_function_pointer<FP>{},
class_&
>
def(char const* const name)
{
scope::def<FP, fp>(name);
return *this;
}
template <typename FP, FP fp>
std::enable_if_t<
!is_function_pointer<FP>{},
class_&
>
def(char const* const name)
{
defs_.push_back(
{
{},
member_info_type {
name,
member_stub<FP, fp, 2>(fp)
}
}
);
return *this;
}
template <typename FP, FP fp>
std::enable_if_t<
!is_function_pointer<FP>{},
class_&
>
def_func(char const* const name)
{
defs_.push_back(
{
{},
member_info_type {
name,
member_stub<FP, fp, 1>(fp)
}
}
);
return *this;
}
template <typename FP, FP fp>
std::enable_if_t<
is_function_pointer<FP>{},
class_&
>
def_func(char const* const name)
{
defs_.push_back(
{
{},
member_info_type {
name,
func_stub<FP, fp, 1>(fp)
}
}
);
return *this;
}
auto& enum_(char const* const name, lua_Integer const value)
{
scope::constant(name, value);
return *this;
}
template <class FP, FP fp>
auto& property(char const* const name)
{
getters_.emplace(name,
accessors_type::mapped_type {
{},
member_stub<FP, fp, 3>(fp),
get_property_type<FP, fp>(fp)
}
);
assert(std::get<1>(getters_[name]));
return *this;
}
template <typename FPA, FPA fpa, typename FPB, FPB fpb>
auto& property(char const* const name)
{
getters_.emplace(name,
accessors_type::mapped_type {
{},
member_stub<FPA, fpa, 3>(fpa),
get_property_type<FPA, fpa>(fpa)
}
);
assert(std::get<1>(getters_[name]));
setters_.emplace(name,
accessors_type::mapped_type {
{},
member_stub<FPB, fpb, 3>(fpb),
get_property_type<FPA, fpa>(fpa)
}
);
assert(std::get<1>(setters_[name]));
return *this;
}
template <typename FP, FP fp>
std::enable_if_t<
!is_function_pointer<FP>{},
class_&
>
vararg_def(char const* const name)
{
defs_.push_back(
{
{},
member_info_type {
name,
vararg_member_stub<FP, fp>(fp)
}
}
);
return *this;
}
private:
template <class A>
struct S
{
static void copy_accessors(accessors_type const& src,
accessors_type& dst)
{
for (auto& a: src)
{
auto& n(dst[a.first] = a.second);
std::get<0>(n).emplace_back(convert<A>);
std::get<0>(n).shrink_to_fit();
}
}
static void copy_defs(defs_type const& src, defs_type& dst)
{
dst.reserve(dst.size() + src.size());
for (auto& a: src)
{
dst.push_back(a);
dst.back().first.emplace_back(convert<A>);
dst.back().first.shrink_to_fit();
}
}
};
void apply(lua_State* const L)
{
assert(parent_scope_);
scope::apply(L);
scope::get_scope(L);
assert(lua_istable(L, -1));
for (auto& i: constructors_)
{
assert(lua_istable(L, -1));
lua_pushcfunction(L, i.callback);
rawsetfield(L, -2, i.name);
}
assert(inherits_.capacity() == inherits_.size());
constructors_.shrink_to_fit();
defs_.shrink_to_fit();
lua_pop(L, 1);
assert(!lua_gettop(L));
}
template <class A>
static void* convert(void* const a) noexcept
{
return static_cast<A*>(static_cast<C*>(a));
}
};
template <class C>
char const* class_<C>::class_name_;
template <class C>
std::vector<bool(*)(char const*) noexcept> class_<C>::inherits_;
template <class C>
std::vector<func_info_type> class_<C>::constructors_;
template <class C>
defs_type class_<C>::defs_;
template <class C>
accessors_type class_<C>::getters_;
template <class C>
accessors_type class_<C>::setters_;
} // lualite
#endif // LUALITE_HPP
| 19.952663 | 86 | 0.620358 | user1095108 |
0bc65c610251e169438e76ce0313901a45f79ad6 | 7,030 | hpp | C++ | include/utils/Utils.hpp | DarkWingMcQuack/GridGraphPathFinder | d8f9a237f17516141bf58c8c86d468f3559af5e3 | [
"Apache-2.0"
] | null | null | null | include/utils/Utils.hpp | DarkWingMcQuack/GridGraphPathFinder | d8f9a237f17516141bf58c8c86d468f3559af5e3 | [
"Apache-2.0"
] | null | null | null | include/utils/Utils.hpp | DarkWingMcQuack/GridGraphPathFinder | d8f9a237f17516141bf58c8c86d468f3559af5e3 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <algorithm>
#include <fmt/core.h>
#include <functional>
#include <future>
#include <iomanip>
#include <sstream>
#include <utility>
#include <vector>
namespace utils {
template<class T>
using Ref = std::reference_wrapper<T>;
template<class T>
using CRef = std::reference_wrapper<const T>;
template<class T>
using RefVec = std::vector<Ref<T>>;
template<class T>
using CRefVec = std::vector<CRef<T>>;
template<class T>
struct is_ref : std::false_type
{
};
template<class T>
struct is_ref<Ref<T>> : std::true_type
{
};
template<class T>
struct is_ref<CRef<T>> : std::true_type
{
};
template<class T>
constexpr auto is_ref_v = is_ref<T>::value;
template<class Head0, class Head1, class... Tail>
constexpr auto min(Head0&& head0, Head1&& head1, Tail&&... tail) noexcept
{
if constexpr(sizeof...(tail) == 0) {
return head0 < head1 ? head0 : head1;
} else {
return min(
min(std::forward<Head0>(head0),
std::forward<Head1>(head1)),
std::forward<Tail>(tail)...);
}
}
template<class Head0, class Head1, class... Tail>
constexpr auto max(Head0&& head0, Head1&& head1, Tail&&... tail) noexcept
{
if constexpr(sizeof...(tail) == 0) {
return head0 > head1 ? head0 : head1;
} else {
return max(
max(std::forward<Head0>(head0),
std::forward<Head1>(head1)),
std::forward<Tail>(tail)...);
}
}
template<class Head0, class Head1, class... Tail>
constexpr auto concat(Head0&& head0, Head1&& head1, Tail&&... tail) noexcept
{
if constexpr(sizeof...(tail) == 0) {
head0.insert(std::end(head0),
std::begin(head1),
std::end(head1));
return std::forward<Head0>(head0);
} else {
return concat(
concat(std::forward<Head0>(head0),
std::forward<Head1>(head1)),
std::forward<Tail>(tail)...);
}
}
template<class T>
auto collectFutures(std::vector<std::future<T>>&& futures) noexcept
-> std::vector<T>
{
std::vector<T> collected;
collected.reserve(futures.size());
std::transform(std::make_move_iterator(std::begin(futures)),
std::make_move_iterator(std::end(futures)),
std::back_inserter(collected),
[](auto future) {
return future.get();
});
return collected;
}
template<class Head0, class Head1, class... Tail>
auto await(std::future<Head0>&& head0,
std::future<Head1>&& head1,
std::future<Tail>&&... tail) noexcept
-> std::tuple<Head0, Head1, Tail...>
{
return std::tuple{head0.get(),
head1.get(),
tail.get()...};
}
template<class T, class... Tail>
auto intersect(std::vector<T>&& head0,
std::vector<T>&& head1,
Tail&&... tail) noexcept
-> std::vector<T>
{
if constexpr(sizeof...(tail) == 0) {
std::vector<T> intersection;
std::set_intersection(std::make_move_iterator(std::begin(head0)),
std::make_move_iterator(std::end(head0)),
std::make_move_iterator(std::begin(head1)),
std::make_move_iterator(std::end(head1)),
std::back_inserter(intersection));
return intersection;
} else {
return intersect(
intersect(std::move(head0),
std::move(head1)),
std::forward<Tail>(tail)...);
}
}
template<class T, class... Tail>
auto intersect(const std::vector<T>& head0,
const std::vector<T>& head1,
Tail&&... tail) noexcept
-> std::vector<T>
{
if constexpr(sizeof...(tail) == 0) {
std::vector<T> intersection;
std::set_intersection(std::begin(head0),
std::end(head0),
std::begin(head1),
std::end(head1),
std::back_inserter(intersection));
return intersection;
} else {
return intersect(
intersect(head0,
head1),
std::forward<Tail>(tail)...);
}
}
template<class T, class F, class... Tail>
auto intersect(std::vector<T>&& head0,
std::vector<T>&& head1,
Tail&&... tail,
F&& func) noexcept
-> std::vector<T>
{
if constexpr(sizeof...(tail) == 0) {
std::vector<T> intersection;
std::set_intersection(std::make_move_iterator(std::begin(head0)),
std::make_move_iterator(std::end(head0)),
std::make_move_iterator(std::begin(head1)),
std::make_move_iterator(std::end(head1)),
std::back_inserter(intersection),
std::forward<F>(func));
return intersection;
} else {
return intersect(
intersect(std::move(head0),
std::move(head1),
std::forward<F>(func)),
std::forward<Tail>(tail)...,
std::forward<F>(func));
}
}
template<class T, class F, class... Tail>
auto intersect(const std::vector<T>& head0,
const std::vector<T>& head1,
Tail&&... tail,
F&& func) noexcept
-> std::vector<T>
{
if constexpr(sizeof...(tail) == 0) {
std::vector<T> intersection;
std::set_intersection(std::begin(head0),
std::end(head0),
std::begin(head1),
std::end(head1),
std::back_inserter(intersection),
std::forward<F>(func));
return intersection;
} else {
return intersect(
intersect(head0,
head1,
std::forward<F>(func)),
std::forward<Tail>(tail)...,
std::forward<F>(func));
}
}
template<class Head0, class Head1, class... Tail>
auto hashCombine(Head0&& head0, Head1&& head1, Tail&&... tail)
{
if constexpr(sizeof...(tail) == 0) {
std::hash<std::remove_const_t<std::remove_reference_t<Head0>>> hasher0;
std::hash<std::remove_const_t<std::remove_reference_t<Head1>>> hasher1;
auto seed = hasher0(head0);
return seed xor (hasher1(head1) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
} else {
return hashCombine(
hashCombine(head0, head1),
std::forward<Tail>(tail)...);
}
}
inline auto unquote(const std::string& s)
-> std::string
{
std::string result;
std::istringstream ss(s);
ss >> std::quoted(result);
return result;
}
template<class... Ts>
struct Overloaded : Ts...
{
using Ts::operator()...;
};
template<class... Ts>
Overloaded(Ts...) -> Overloaded<Ts...>;
} // namespace utils
| 28.693878 | 82 | 0.526316 | DarkWingMcQuack |
0bc9d6fffbd6c918a0c680ee105052f90bcdf2bf | 1,941 | hpp | C++ | application/timely-matter/src/views/BaseView.hpp | davidbeermann/timely-matter | fca86fb5b48766c5371677a90ac5149c1b071149 | [
"MIT"
] | 2 | 2016-09-03T17:49:30.000Z | 2016-12-20T18:12:58.000Z | application/timely-matter/src/views/BaseView.hpp | davidbeermann/timely-matter | fca86fb5b48766c5371677a90ac5149c1b071149 | [
"MIT"
] | null | null | null | application/timely-matter/src/views/BaseView.hpp | davidbeermann/timely-matter | fca86fb5b48766c5371677a90ac5149c1b071149 | [
"MIT"
] | null | null | null | #pragma once
#include "ofMain.h"
#include "ofEvents.h"
#include "AppModel.hpp"
#include "KinectModel.hpp"
#include "ProjectorModel.hpp"
#include "ViewEvent.hpp"
namespace timelymatter
{
// Base view class to be extended by concrete views managed by ViewManager class.
// Implementation for NVI Non-Virtual Interface derived from here:
// http://stackoverflow.com/questions/14323595/best-way-to-declare-an-interface-in-c11#answer-14324500
class BaseView {
protected:
AppModel& m_app_model;
KinectModel& m_kinect_model;
ProjectorModel& m_projector_model;
ViewEvent& m_view_event;
// Methods to be implemented by concrete view.
virtual void m_onWindowResized(const int width, const int height) = 0;
virtual void m_onSetup() = 0;
virtual void m_onUpdate() = 0;
virtual void m_onDraw() = 0;
public:
// Setup model references for all views derived from this class.
BaseView() :
m_app_model(AppModel::get()),
m_kinect_model(KinectModel::get()),
m_projector_model(ProjectorModel::get()),
m_view_event(ViewEvent::get())
{
ofAddListener(ofEvents().windowResized, this, &BaseView::onWindowResized);
};
// always define virtual destructors for base classes
// http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors#461224
virtual ~BaseView() {
ofRemoveListener(ofEvents().windowResized, this, &BaseView::onWindowResized);
};
// event listener methods
void onWindowResized(ofResizeEventArgs& args) {
m_onWindowResized(args.width, args.height);
};
// Non-Virtual Interface methods
void setup() {
// call setup first...
m_onSetup();
// ...before triggering a virtual window resize.
m_onWindowResized(ofGetWindowWidth(), ofGetWindowHeight());
};
void update() { m_onUpdate(); };
void draw() { m_onDraw(); };
};
} | 30.809524 | 102 | 0.679547 | davidbeermann |
0bca25337e84c7bd598a52dd189ecc5e486e43f0 | 24 | cpp | C++ | 02-classes-constructors-destructors/2-makefile/Triangle.cpp | nofar88/cpp-5782 | 473c68627fc0908fdef8956caf1e1d2267c9417b | [
"MIT"
] | 14 | 2021-01-30T16:36:18.000Z | 2022-03-30T17:24:44.000Z | 02-classes-constructors-destructors/2-makefile/Triangle.cpp | dimastar2310/cpp-5781 | 615ba07e0841522df74384f380172557f5e305a7 | [
"MIT"
] | 1 | 2022-03-02T20:55:14.000Z | 2022-03-02T20:55:14.000Z | 02-classes-constructors-destructors/2-makefile/Triangle.cpp | dimastar2310/cpp-5781 | 615ba07e0841522df74384f380172557f5e305a7 | [
"MIT"
] | 23 | 2020-03-12T13:21:29.000Z | 2021-02-22T21:29:48.000Z | #include "Triangle.hpp"
| 12 | 23 | 0.75 | nofar88 |
0bcb1bb4438a2047624f8ec1ed46047bd24dc449 | 14,628 | cpp | C++ | tiger_ci/erkale/eri_digest.cpp | EACcodes/TigerCI | ac1311ea5e2b829b5507171afdbdd6c64e12e6fd | [
"BSD-3-Clause"
] | 3 | 2016-12-08T13:57:10.000Z | 2019-01-17T17:05:46.000Z | tiger_ci/erkale/eri_digest.cpp | EACcodes/TigerCI | ac1311ea5e2b829b5507171afdbdd6c64e12e6fd | [
"BSD-3-Clause"
] | null | null | null | tiger_ci/erkale/eri_digest.cpp | EACcodes/TigerCI | ac1311ea5e2b829b5507171afdbdd6c64e12e6fd | [
"BSD-3-Clause"
] | 2 | 2019-02-20T06:03:24.000Z | 2020-06-09T09:00:49.000Z | /*
* This source code is part of
*
* E R K A L E
* -
* DFT from Hel
*
* Written by Susi Lehtola, 2010-2015
* Copyright (c) 2010-2015, Susi Lehtola
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*/
#include "eri_digest.h"
#include "eriworker.h"
IntegralDigestor::IntegralDigestor() {
}
IntegralDigestor::~IntegralDigestor() {
}
JDigestor::JDigestor(const arma::mat & P_) : P(P_) {
J.zeros(P.n_rows,P.n_cols);
}
JDigestor::~JDigestor() {
}
void JDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, const std::vector<double> & ints, size_t ioff) {
// Shells in quartet are
size_t is=shpairs[ip].is;
size_t js=shpairs[ip].js;
size_t ks=shpairs[jp].is;
size_t ls=shpairs[jp].js;
// Amount of functions on the first pair is
size_t Ni=shpairs[ip].Ni;
size_t Nj=shpairs[ip].Nj;
// and on second pair is
size_t Nk=shpairs[jp].Ni;
size_t Nl=shpairs[jp].Nj;
// First functions on the first pair is
size_t i0=shpairs[ip].i0;
size_t j0=shpairs[ip].j0;
// Second pair is
size_t k0=shpairs[jp].i0;
size_t l0=shpairs[jp].j0;
// J_ij = (ij|kl) P_kl
{
// Work matrix
arma::mat Jij(Ni,Nj);
Jij.zeros();
arma::mat Pkl=P.submat(k0,l0,k0+Nk-1,l0+Nl-1);
// Degeneracy factor
double fac=1.0;
if(ks!=ls)
fac=2.0;
// Increment matrix
for(size_t ii=0;ii<Ni;ii++)
for(size_t jj=0;jj<Nj;jj++) {
// Matrix element
double el=0.0;
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++)
el+=Pkl(kk,ll)*ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll];
// Set the element
Jij(ii,jj)+=fac*el;
}
// Store the matrix element
J.submat(i0,j0,i0+Ni-1,j0+Nj-1)+=Jij;
if(is!=js)
J.submat(j0,i0,j0+Nj-1,i0+Ni-1)+=arma::trans(Jij);
}
// Permutation: J_kl = (ij|kl) P_ij
if(ip!=jp) {
// Work matrix
arma::mat Jkl(Nk,Nl);
Jkl.zeros();
arma::mat Pij=P.submat(i0,j0,i0+Ni-1,j0+Nj-1);
// Degeneracy factor
double fac=1.0;
if(is!=js)
fac=2.0;
// Increment matrix
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++) {
// Matrix element
double el=0.0;
for(size_t ii=0;ii<Ni;ii++) {
for(size_t jj=0;jj<Nj;jj++) {
el+=Pij(ii,jj)*ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll];
}
}
// Set the element
Jkl(kk,ll)+=fac*el;
}
// Store the matrix element
J.submat(k0,l0,k0+Nk-1,l0+Nl-1)+=Jkl;
if(ks!=ls)
J.submat(l0,k0,l0+Nl-1,k0+Nk-1)+=arma::trans(Jkl);
}
}
arma::mat JDigestor::get_J() const {
return J;
}
KDigestor::KDigestor(const arma::mat & P_) : P(P_) {
K.zeros(P.n_rows,P.n_cols);
}
KDigestor::~KDigestor() {
}
void KDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, const std::vector<double> & ints, size_t ioff) {
size_t is=shpairs[ip].is;
size_t js=shpairs[ip].js;
size_t ks=shpairs[jp].is;
size_t ls=shpairs[jp].js;
// Amount of functions on the first pair is
size_t Ni=shpairs[ip].Ni;
size_t Nj=shpairs[ip].Nj;
// and on second pair is
size_t Nk=shpairs[jp].Ni;
size_t Nl=shpairs[jp].Nj;
// First functions on the first pair is
size_t i0=shpairs[ip].i0;
size_t j0=shpairs[ip].j0;
// Second pair is
size_t k0=shpairs[jp].i0;
size_t l0=shpairs[jp].j0;
/*
When all indices are different, the
following integrals are equivalent:
(ij|kl) (ij|lk) (ji|kl) (ji|lk)
(kl|ij) (kl|ji) (lk|ij) (lk|ji)
This translates to
K(i,k) += (ij|kl) P(j,l) // always
K(j,k) += (ij|kl) P(i,l) // if (is!=js)
K(i,l) += (ij|kl) P(j,k) // if (ls!=ks)
K(j,l) += (ij|kl) P(i,k) // if (is!=js) and (ls!=ks)
and for ij != kl
K(k,i) += (ij|kl) P(j,l) // always
K(k,j) += (ij|kl) P(i,l) // if (is!=js)
K(l,i) += (ij|kl) P(j,k) // if (ks!=ls)
K(l,j) += (ij|kl) P(i,k) // if (is!=js) and (ks!=ls)
However, the latter four permutations just make the
exchange matrix symmetric. So the only thing we need to do
is do the first four permutations, and at the end we sum up
K_ij and K_ji for j>i and set K_ij and K_ji to this
value. This makes things a *lot* easier. So:
We just need to check if the shells are different, in which
case K will get extra increments.
*/
// First, do the ik part: K(i,k) += (ij|kl) P(j,l)
{
arma::mat Kik(Ni,Nk);
Kik.zeros();
arma::mat Pjl =P.submat(j0,l0,j0+Nj-1,l0+Nl-1);
// Increment Kik
for(size_t ii=0;ii<Ni;ii++)
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++)
for(size_t jj=0;jj<Nj;jj++)
Kik (ii,kk)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pjl (jj,ll);
// Set elements
K.submat(i0,k0,i0+Ni-1,k0+Nk-1)+=Kik;
// Symmetrize if necessary
if(ip!=jp)
K.submat(k0,i0,k0+Nk-1,i0+Ni-1)+=arma::trans(Kik);
}
// Then, the second part: K(j,k) += (ij|kl) P(i,l)
if(is!=js) {
arma::mat Kjk(Nj,Nk);
Kjk.zeros();
arma::mat Pil=P.submat(i0,l0,i0+Ni-1,l0+Nl-1);
// Increment Kjk
for(size_t jj=0;jj<Nj;jj++)
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++)
for(size_t ii=0;ii<Ni;ii++)
Kjk(jj,kk)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pil(ii,ll);
// Set elements
K.submat(j0,k0,j0+Nj-1,k0+Nk-1)+=Kjk;
// Symmetrize if necessary (take care about possible overlap with next routine)
if(ip!=jp) {
K.submat(k0,j0,k0+Nk-1,j0+Nj-1)+=arma::trans(Kjk);
}
}
// Third part: K(i,l) += (ij|kl) P(j,k)
if(ks!=ls) {
arma::mat Kil(Ni,Nl);
Kil.zeros();
arma::mat Pjk=P.submat(j0,k0,j0+Nj-1,k0+Nk-1);
// Increment Kil
for(size_t ii=0;ii<Ni;ii++)
for(size_t ll=0;ll<Nl;ll++)
for(size_t jj=0;jj<Nj;jj++)
for(size_t kk=0;kk<Nk;kk++) {
Kil(ii,ll)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pjk(jj,kk);
}
// Set elements
K.submat(i0,l0,i0+Ni-1,l0+Nl-1)+=Kil;
// Symmetrize if necessary
if(ip!=jp)
K.submat(l0,i0,l0+Nl-1,i0+Ni-1)+=arma::trans(Kil);
}
// Last permutation: K(j,l) += (ij|kl) P(i,k)
if(is!=js && ks!=ls) {
arma::mat Kjl(Nj,Nl);
Kjl.zeros();
arma::mat Pik=P.submat(i0,k0,i0+Ni-1,k0+Nk-1);
// Increment Kjl
for(size_t jj=0;jj<Nj;jj++)
for(size_t ll=0;ll<Nl;ll++)
for(size_t ii=0;ii<Ni;ii++)
for(size_t kk=0;kk<Nk;kk++) {
Kjl(jj,ll)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pik(ii,kk);
}
// Set elements
K.submat(j0,l0,j0+Nj-1,l0+Nl-1)+=Kjl;
// Symmetrize if necessary
if (ip!=jp)
K.submat(l0,j0,l0+Nl-1,j0+Nj-1)+=arma::trans(Kjl);
}
}
arma::mat KDigestor::get_K() const {
return K;
}
cxKDigestor::cxKDigestor(const arma::cx_mat & P_) : P(P_) {
K.zeros(P.n_rows,P.n_cols);
}
cxKDigestor::~cxKDigestor() {
}
void cxKDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, const std::vector<double> & ints, size_t ioff) {
size_t is=shpairs[ip].is;
size_t js=shpairs[ip].js;
size_t ks=shpairs[jp].is;
size_t ls=shpairs[jp].js;
// Amount of functions on the first pair is
size_t Ni=shpairs[ip].Ni;
size_t Nj=shpairs[ip].Nj;
// and on second pair is
size_t Nk=shpairs[jp].Ni;
size_t Nl=shpairs[jp].Nj;
// First functions on the first pair is
size_t i0=shpairs[ip].i0;
size_t j0=shpairs[ip].j0;
// Second pair is
size_t k0=shpairs[jp].i0;
size_t l0=shpairs[jp].j0;
/*
When all indices are different, the
following integrals are equivalent:
(ij|kl) (ij|lk) (ji|kl) (ji|lk)
(kl|ij) (kl|ji) (lk|ij) (lk|ji)
This translates to
K(i,k) += (ij|kl) P(j,l) // always
K(j,k) += (ij|kl) P(i,l) // if (is!=js)
K(i,l) += (ij|kl) P(j,k) // if (ls!=ks)
K(j,l) += (ij|kl) P(i,k) // if (is!=js) and (ls!=ks)
and for ij != kl
K(k,i) += (ij|kl) P(j,l) // always
K(k,j) += (ij|kl) P(i,l) // if (is!=js)
K(l,i) += (ij|kl) P(j,k) // if (ks!=ls)
K(l,j) += (ij|kl) P(i,k) // if (is!=js) and (ks!=ls)
However, the latter four permutations just make the
exchange matrix symmetric. So the only thing we need to do
is do the first four permutations, and at the end we sum up
K_ij and K_ji for j>i and set K_ij and K_ji to this
value. This makes things a *lot* easier. So:
We just need to check if the shells are different, in which
case K will get extra increments.
*/
// First, do the ik part: K(i,k) += (ij|kl) P(j,l)
{
arma::cx_mat Kik(Ni,Nk);
Kik.zeros();
arma::cx_mat Pjl =P.submat(j0,l0,j0+Nj-1,l0+Nl-1);
// Increment Kik
for(size_t ii=0;ii<Ni;ii++)
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++)
for(size_t jj=0;jj<Nj;jj++)
Kik (ii,kk)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pjl (jj,ll);
// Set elements
K.submat(i0,k0,i0+Ni-1,k0+Nk-1)+=Kik;
// Symmetrize if necessary
if(ip!=jp)
K.submat(k0,i0,k0+Nk-1,i0+Ni-1)+=arma::trans(Kik);
}
// Then, the second part: K(j,k) += (ij|kl) P(i,l)
if(is!=js) {
arma::cx_mat Kjk(Nj,Nk);
Kjk.zeros();
arma::cx_mat Pil=P.submat(i0,l0,i0+Ni-1,l0+Nl-1);
// Increment Kjk
for(size_t jj=0;jj<Nj;jj++)
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++)
for(size_t ii=0;ii<Ni;ii++)
Kjk(jj,kk)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pil(ii,ll);
// Set elements
K.submat(j0,k0,j0+Nj-1,k0+Nk-1)+=Kjk;
// Symmetrize if necessary (take care about possible overlap with next routine)
if(ip!=jp) {
K.submat(k0,j0,k0+Nk-1,j0+Nj-1)+=arma::trans(Kjk);
}
}
// Third part: K(i,l) += (ij|kl) P(j,k)
if(ks!=ls) {
arma::cx_mat Kil(Ni,Nl);
Kil.zeros();
arma::cx_mat Pjk=P.submat(j0,k0,j0+Nj-1,k0+Nk-1);
// Increment Kil
for(size_t ii=0;ii<Ni;ii++)
for(size_t ll=0;ll<Nl;ll++)
for(size_t jj=0;jj<Nj;jj++)
for(size_t kk=0;kk<Nk;kk++) {
Kil(ii,ll)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pjk(jj,kk);
}
// Set elements
K.submat(i0,l0,i0+Ni-1,l0+Nl-1)+=Kil;
// Symmetrize if necessary
if(ip!=jp)
K.submat(l0,i0,l0+Nl-1,i0+Ni-1)+=arma::trans(Kil);
}
// Last permutation: K(j,l) += (ij|kl) P(i,k)
if(is!=js && ks!=ls) {
arma::cx_mat Kjl(Nj,Nl);
Kjl.zeros();
arma::cx_mat Pik=P.submat(i0,k0,i0+Ni-1,k0+Nk-1);
// Increment Kjl
for(size_t jj=0;jj<Nj;jj++)
for(size_t ll=0;ll<Nl;ll++)
for(size_t ii=0;ii<Ni;ii++)
for(size_t kk=0;kk<Nk;kk++) {
Kjl(jj,ll)+=ints[ioff+((ii*Nj+jj)*Nk+kk)*Nl+ll]*Pik(ii,kk);
}
// Set elements
K.submat(j0,l0,j0+Nj-1,l0+Nl-1)+=Kjl;
// Symmetrize if necessary
if (ip!=jp)
K.submat(l0,j0,l0+Nl-1,j0+Nj-1)+=arma::trans(Kjl);
}
}
arma::cx_mat cxKDigestor::get_K() const {
return K;
}
ForceDigestor::ForceDigestor() {
}
ForceDigestor::~ForceDigestor() {
}
JFDigestor::JFDigestor(const arma::mat & P_) : P(P_) {
}
JFDigestor::~JFDigestor() {
}
void JFDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, dERIWorker & deriw, arma::vec & f) {
// Shells in question are
size_t is=shpairs[ip].is;
size_t js=shpairs[ip].js;
size_t ks=shpairs[jp].is;
size_t ls=shpairs[jp].js;
// Amount of functions on the first pair is
size_t Ni=shpairs[ip].Ni;
size_t Nj=shpairs[ip].Nj;
// and on second pair is
size_t Nk=shpairs[jp].Ni;
size_t Nl=shpairs[jp].Nj;
// First functions on the first pair is
size_t i0=shpairs[ip].i0;
size_t j0=shpairs[ip].j0;
// Second pair is
size_t k0=shpairs[jp].i0;
size_t l0=shpairs[jp].j0;
// E_J = P_ij (ij|kl) P_kl. Work matrices
arma::mat Pij=P.submat(i0,j0,i0+Ni-1,j0+Nj-1);
arma::mat Pkl=P.submat(k0,l0,k0+Nk-1,l0+Nl-1);
// Degeneracy factor
double Jfac=-0.5;
if(is!=js)
Jfac*=2.0;
if(ks!=ls)
Jfac*=2.0;
if(ip!=jp)
Jfac*=2.0;
// Increment the forces.
for(int idx=0;idx<12;idx++) {
// Get the integral derivatives
const std::vector<double> *erip=deriw.getp(idx);
// E_J = P_ij (ij|kl) P_kl
double el=0.0;
for(size_t ii=0;ii<Ni;ii++)
for(size_t jj=0;jj<Nj;jj++)
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++)
el+=Pij(ii,jj)*Pkl(kk,ll)*(*erip)[((ii*Nj+jj)*Nk+kk)*Nl+ll];
// Increment the element
f(idx)+=Jfac*el;
}
}
KFDigestor::KFDigestor(const arma::mat & P_, double kfrac_, bool restr) : P(P_), kfrac(kfrac_) {
fac = restr ? 0.5 : 1.0;
}
KFDigestor::~KFDigestor() {
}
void KFDigestor::digest(const std::vector<eripair_t> & shpairs, size_t ip, size_t jp, dERIWorker & deriw, arma::vec & f) {
// Shells on quartet are
size_t is=shpairs[ip].is;
size_t js=shpairs[ip].js;
size_t ks=shpairs[jp].is;
size_t ls=shpairs[jp].js;
// Amount of functions on the first pair is
size_t Ni=shpairs[ip].Ni;
size_t Nj=shpairs[ip].Nj;
// and on second pair is
size_t Nk=shpairs[jp].Ni;
size_t Nl=shpairs[jp].Nj;
// First functions on the first pair is
size_t i0=shpairs[ip].i0;
size_t j0=shpairs[ip].j0;
// Second pair is
size_t k0=shpairs[jp].i0;
size_t l0=shpairs[jp].j0;
// E_K = P_ik (ij|kl) P_jl
arma::mat Pik=P.submat(i0,k0,i0+Ni-1,k0+Nk-1);
arma::mat Pjl=P.submat(j0,l0,j0+Nj-1,l0+Nl-1);
// + P_jk (ij|kl) P_il
arma::mat Pjk=P.submat(j0,k0,j0+Nj-1,k0+Nk-1);
arma::mat Pil=P.submat(i0,l0,i0+Ni-1,l0+Nl-1);
double K1fac, K2fac;
if(is!=js && ks!=ls) {
// Get both twice.
K1fac=1.0;
K2fac=1.0;
} else if(is==js && ks==ls) {
// Only get the first one, once.
K1fac=0.5;
K2fac=0.0;
} else {
// Get both once.
K1fac=0.5;
K2fac=0.5;
}
// Switch symmetry
if(ip!=jp) {
K1fac*=2.0;
K2fac*=2.0;
}
// Restricted calculation?
K1fac*=fac*kfrac;
K2fac*=fac*kfrac;
// Increment the forces.
for(int idx=0;idx<12;idx++) {
// Get the integral derivatives
const std::vector<double> * erip=deriw.getp(idx);
// E_K = P_ik (ij|kl) P_jl
double el=0.0;
// Increment matrix
for(size_t ii=0;ii<Ni;ii++)
for(size_t jj=0;jj<Nj;jj++)
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++)
el+=Pik(ii,kk)*Pjl(jj,ll)*(*erip)[((ii*Nj+jj)*Nk+kk)*Nl+ll];
// Increment the element
f(idx)+=K1fac*el;
// Second contribution
if(K2fac!=0.0) {
el=0.0;
// Increment matrix
for(size_t ii=0;ii<Ni;ii++)
for(size_t jj=0;jj<Nj;jj++)
for(size_t kk=0;kk<Nk;kk++)
for(size_t ll=0;ll<Nl;ll++)
el+=Pjk(jj,kk)*Pil(ii,ll)*(*erip)[((ii*Nj+jj)*Nk+kk)*Nl+ll];
// Increment the element
f(idx)+=K2fac*el;
}
}
}
| 25.844523 | 135 | 0.588392 | EACcodes |
0bccb03870df63701020e1e9c37d4af5e025f6d2 | 21,776 | cpp | C++ | app/rec/rec_gui/src/qecalrec.cpp | NewProggie/ecal | b779f09c302ba63e23b4378fa09d79f6259b2e64 | [
"Apache-2.0"
] | null | null | null | app/rec/rec_gui/src/qecalrec.cpp | NewProggie/ecal | b779f09c302ba63e23b4378fa09d79f6259b2e64 | [
"Apache-2.0"
] | null | null | null | app/rec/rec_gui/src/qecalrec.cpp | NewProggie/ecal | b779f09c302ba63e23b4378fa09d79f6259b2e64 | [
"Apache-2.0"
] | null | null | null | /* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental 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.
*
* ========================= eCAL LICENSE =================================
*/
#include "qecalrec.h"
#include <rec_server_core/rec_server.h>
#include "monitoring_thread.h"
#include <functional>
#include <QMessageBox>
#include <ecal/ecal.h>
QEcalRec::QEcalRec(QObject* parent)
: QObject(parent)
, rec_server_(std::make_unique<eCAL::rec::RecServer>())
{
addRecorderInstance(eCAL::Process::GetHostName(), {}, true);
setMeasRootDir("$TARGET{OSSELECT WIN \"C:\" LINUX \"$TARGET{ENV HOME}\"}/ecal_meas");
setMeasName("${TIME}_measurement");
setDescription(
R"(---------------------- description -------------------------
Car:
Scenario:
Location:
Driver:
Date: ${TIME %F %R}
---------------------- comment -----------------------------
)"
);
setMaxFileSizeMib(100);
state_update_timer_ = new QTimer(this);
connect(state_update_timer_, &QTimer::timeout, this, &QEcalRec::sendStateUpdate);
state_update_timer_->start(state_update_timer_ms_);
qRegisterMetaType<std::map<std::string, eCAL::rec::TopicInfo>>("std::map<std::string,eCAL::rec::TopicInfo>");
monitoring_thread_ = std::make_unique<MonitoringThread>();
connect(monitoring_thread_.get(), &MonitoringThread::monitorUpdatedSignal, this, &QEcalRec::monitorUpdatedSignal, Qt::ConnectionType::QueuedConnection);
monitoring_thread_->Start();
}
QEcalRec::~QEcalRec()
{
monitoring_thread_->Interrupt();
monitoring_thread_->Join();
}
QEcalRec* QEcalRec::instance()
{
static QEcalRec* instance = new QEcalRec();
return instance;
}
////////////////////////////////////
// Instance management //
////////////////////////////////////
bool QEcalRec::addRecorderInstance(const std::string& hostname, const std::set<std::string>& host_filter, bool omit_dialogs)
{
auto recorder_instances = recorderInstances();
recorder_instances.push_back(std::make_pair(hostname, host_filter));
return setRecorderInstances(recorder_instances, omit_dialogs);
}
bool QEcalRec::removeRecorderInstance(const std::string& hostname, bool omit_dialogs)
{
auto recorder_instances = recorderInstances();
auto recorder_to_remove_it = std::find_if(recorder_instances.begin(), recorder_instances.end(), [&hostname](const auto& host_hostfilter_pair) { return host_hostfilter_pair.first == hostname; });
if (recorder_to_remove_it == recorder_instances.end())
{
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Cannot remove recorder \"" + QString::fromStdString(hostname) + "\"");
error_message.exec();
}
return false;
}
else
{
recorder_instances.erase(recorder_to_remove_it);
return setRecorderInstances(recorder_instances, omit_dialogs);
}
}
bool QEcalRec::setRecorderInstances(const std::vector<std::pair<std::string, std::set<std::string>>>& host_hostfilter_list, bool omit_dialogs)
{
bool success = executeBlockingMethod<bool>([this, &host_hostfilter_list]() { return rec_server_->SetRecorderInstances(host_hostfilter_list); }, widgetOf(sender()), omit_dialogs);
if (success)
{
emit recorderInstancesChangedSignal(host_hostfilter_list);
}
else
{
emit recorderInstancesChangedSignal(rec_server_->GetRecorderInstances());
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error setting recorder instances");
error_message.exec();
}
}
return success;
}
std::vector<std::pair<std::string, std::set<std::string>>> QEcalRec::recorderInstances() const { return rec_server_->GetRecorderInstances(); }
bool QEcalRec::setClientConnectionsEnabled(bool enabled, bool omit_dialogs)
{
bool success = rec_server_->SetClientConnectionsEnabled(enabled);
if (!success && !omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText(tr("Unable to ") + (enabled ? "connect to clients" : "disconnect from clients" ) + ". Stop the recording and try again.");
error_message.exec();
}
emit clientConnectionsEnabledSignal(clientConnectionsEnabled());
return success;
}
void QEcalRec::initiateConnectionShutdown()
{
rec_server_->InitiateConnectionShutdown();
emit clientConnectionsEnabledSignal (false);
emit recordingStateChangedSignal (false);
emit connectedToEcalStateChangedSignal(false);
}
bool QEcalRec::clientConnectionsEnabled() const
{
return rec_server_->AreClientConnectionsEnabled();
}
////////////////////////////////////
// Requests //
////////////////////////////////////
std::map<std::string, std::pair<bool, std::string>> QEcalRec::lastResponses() { return rec_server_->GetLastResponses(); }
void QEcalRec::waitForPendingRequests() const { rec_server_->WaitForPendingRequests(); }
std::map<std::string, bool> QEcalRec::areRequestsPending() const { return rec_server_->AreRequestsPending(); }
bool QEcalRec::anyRequestPending() const { return rec_server_->IsAnyRequestPending(); }
////////////////////////////////////
// Settings //
////////////////////////////////////
bool QEcalRec::setMaxPreBufferLength(std::chrono::steady_clock::duration max_pre_buffer_length, bool omit_dialogs)
{
std::function<bool()> method = std::bind(&eCAL::rec::RecServer::SetMaxPreBufferLength, rec_server_.get(), max_pre_buffer_length);
bool success = executeBlockingMethod(method, widgetOf(sender()), omit_dialogs);
if (success)
{
emit maxPreBufferLengthChangedSignal(max_pre_buffer_length);
}
else
{
emit maxPreBufferLengthChangedSignal(rec_server_->GetMaxPreBufferLength());
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error setting pre-buffer length");
error_message.exec();
}
}
return success;
}
bool QEcalRec::setPreBufferingEnabled(bool pre_buffering_enabled, bool omit_dialogs)
{
std::function<bool()> method = std::bind(&eCAL::rec::RecServer::SetPreBufferingEnabled, rec_server_.get(), pre_buffering_enabled);
bool success = executeBlockingMethod(method, widgetOf(sender()), omit_dialogs);
if (success)
{
emit preBufferingEnabledChangedSignal(pre_buffering_enabled);
}
else
{
emit preBufferingEnabledChangedSignal(rec_server_->GetPreBufferingEnabled());
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error enabling / disabling pre-buffering");
error_message.exec();
}
}
return true;
}
bool QEcalRec::setRecordMode(eCAL::rec::RecordMode record_mode, bool omit_dialogs)
{
bool success;
switch (record_mode)
{
case eCAL::rec::RecordMode::Blacklist:
success = executeBlockingMethod<bool>([this, record_mode]() { return rec_server_->SetRecordMode(record_mode, topic_blacklist_); }, widgetOf(sender()), omit_dialogs);
break;
case eCAL::rec::RecordMode::Whitelist:
success = executeBlockingMethod<bool>([this, record_mode]() { return rec_server_->SetRecordMode(record_mode, topic_whitelist_); }, widgetOf(sender()), omit_dialogs);
break;
default:
success = executeBlockingMethod<bool>([this, record_mode]() { return rec_server_->SetRecordMode(record_mode); }, widgetOf(sender()), omit_dialogs);
break;
}
if (success)
{
emit recordModeChangedSignal(record_mode);
}
else
{
emit recordModeChangedSignal(rec_server_->GetRecordMode());
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error setting record mode");
error_message.exec();
}
}
return success;
}
bool QEcalRec::setTopicBlacklist(const std::set<std::string>& topic_blacklist, bool omit_dialogs)
{
if (rec_server_->GetRecordMode() == eCAL::rec::RecordMode::Blacklist)
{
bool success = false;
success = executeBlockingMethod<bool>([this, &topic_blacklist]() { return rec_server_->SetRecordMode(rec_server_->GetRecordMode(), topic_blacklist); }, widgetOf(sender()), omit_dialogs);
if (success)
{
topic_blacklist_ = topic_blacklist;
emit topicBlacklistChangedSignal(topic_blacklist_);
}
else
{
emit topicBlacklistChangedSignal(topic_blacklist_);
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error setting topic blacklist");
error_message.exec();
}
}
return success;
}
else
{
topic_blacklist_ = topic_blacklist;
emit topicBlacklistChangedSignal(topic_blacklist_);
return true;
}
}
bool QEcalRec::setTopicWhitelist(const std::set<std::string>& topic_whitelist, bool omit_dialogs)
{
if (rec_server_->GetRecordMode() == eCAL::rec::RecordMode::Whitelist)
{
bool success = false;
success = executeBlockingMethod<bool>([this, &topic_whitelist]() { return rec_server_->SetRecordMode(rec_server_->GetRecordMode(), topic_whitelist); }, widgetOf(sender()), omit_dialogs);
if (success)
{
topic_whitelist_ = topic_whitelist;
emit topicWhitelistChangedSignal(topic_whitelist_);
}
else
{
emit topicWhitelistChangedSignal(topic_whitelist_);
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error setting topic whitelist");
error_message.exec();
}
}
return success;
}
else
{
topic_whitelist_ = topic_whitelist;
emit topicWhitelistChangedSignal(topic_whitelist_);
return true;
}
}
bool QEcalRec::setHostFilter(const std::string& hostname, const std::set<std::string>& host_filter, bool omit_dialogs)
{
bool success = rec_server_->SetHostFilter(hostname, host_filter);
success = executeBlockingMethod<bool>([this, &hostname, &host_filter]() { return rec_server_->SetHostFilter(hostname, host_filter); }, widgetOf(sender()), omit_dialogs);
if (success)
{
emit hostFilterChangedSignal(hostname, host_filter);
}
else
{
emit hostFilterChangedSignal(hostname, rec_server_->GetHostFilter(hostname));
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error setting host filter list");
error_message.exec();
}
}
return success;
}
void QEcalRec::setMeasRootDir(std::string meas_root_dir)
{
rec_server_->SetMeasRootDir(meas_root_dir);
emit measRootDirChangedSignal(meas_root_dir);
}
void QEcalRec::setMeasName(std::string meas_name)
{
rec_server_->SetMeasName(meas_name);
emit measNameChangedSignal(meas_name);
}
void QEcalRec::setMaxFileSizeMib(int max_file_size_mib)
{
rec_server_->SetMaxFileSizeMib(max_file_size_mib);
emit maxFileSizeMibChangedSignal(max_file_size_mib);
}
void QEcalRec::setDescription(std::string description)
{
rec_server_->SetDescription(description);
emit descriptionChangedSignal(description);
}
std::chrono::steady_clock::duration QEcalRec::maxPreBufferLength () const { return rec_server_->GetMaxPreBufferLength(); };
bool QEcalRec::preBufferingEnabled() const { return rec_server_->GetPreBufferingEnabled(); };
eCAL::rec::RecordMode QEcalRec::recordMode () const { return rec_server_->GetRecordMode(); };
std::set<std::string> QEcalRec::topicBlacklist () const { return topic_blacklist_; };
std::set<std::string> QEcalRec::topicWhitelist () const { return topic_whitelist_; };
std::set<std::string> QEcalRec::hostFilter (const std::string& hostname) const { return rec_server_->GetHostFilter(hostname); };
std::string QEcalRec::measRootDir () const { return rec_server_->GetMeasRootDir(); };
std::string QEcalRec::measName () const { return rec_server_->GetMeasName(); };
size_t QEcalRec::maxFileSizeMib () const { return rec_server_->GetMaxFileSizeMib(); };
std::string QEcalRec::description () const { return rec_server_->GetDescription(); };
////////////////////////////////////
// Commands //
////////////////////////////////////
bool QEcalRec::sendRequestConnectToEcal(bool omit_dialogs)
{
std::function<bool()> method = std::bind(&eCAL::rec::RecServer::SendRequestConnectToEcal, rec_server_.get());
bool success = executeBlockingMethod(method, widgetOf(sender()), omit_dialogs);
if (success)
{
emit clientConnectionsEnabledSignal(true);
emit connectedToEcalStateChangedSignal(true);
}
else
{
emit connectedToEcalStateChangedSignal(rec_server_->RecordersConnectedToEcal());
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error connecting to eCAL");
error_message.exec();
}
}
return success;
}
bool QEcalRec::sendRequestDisconnectFromEcal(bool omit_dialogs)
{
std::function<bool()> method = std::bind(&eCAL::rec::RecServer::SendRequestDisconnectFromEcal, rec_server_.get());
bool success = executeBlockingMethod(method, widgetOf(sender()), omit_dialogs);
if (success)
{
emit connectedToEcalStateChangedSignal(false);
}
else
{
emit connectedToEcalStateChangedSignal(rec_server_->RecordersConnectedToEcal());
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error disconnecting from eCAL");
error_message.exec();
}
}
return success;
}
bool QEcalRec::sendRequestSavePreBufferedData(bool omit_dialogs)
{
if (measRootDir().empty() && measName().empty())
{
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Unable to save buffer. Please enter a measurement root directory and name and try again.");
error_message.exec();
}
return false;
}
std::function<bool()> method = std::bind(&eCAL::rec::RecServer::SendRequestSavePreBufferedData, rec_server_.get());
bool success = executeBlockingMethod(method, widgetOf(sender()), omit_dialogs);
if (!success)
{
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error saving pre-buffered data");
error_message.exec();
}
}
return success;
}
bool QEcalRec::sendRequestStartRecording(bool omit_dialogs)
{
if (measRootDir().empty() && measName().empty())
{
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Unable to start recording. Please enter a measurement root directory and name and try again.");
error_message.exec();
}
emit recordingStateChangedSignal(rec_server_->RecordersRecording());
return false;
}
std::function<bool()> method = std::bind(&eCAL::rec::RecServer::SendRequestStartRecording, rec_server_.get());
bool success = executeBlockingMethod(method, widgetOf(sender()), omit_dialogs);
if (success)
{
emit clientConnectionsEnabledSignal(true);
emit connectedToEcalStateChangedSignal(true);
emit recordingStateChangedSignal(true);
}
else
{
emit recordingStateChangedSignal(rec_server_->RecordersRecording());
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error starting recording");
error_message.exec();
}
}
return success;
}
bool QEcalRec::sendRequestStopRecording(bool omit_dialogs)
{
std::function<bool()> method = std::bind(&eCAL::rec::RecServer::SendRequestStopRecording, rec_server_.get());
bool success = executeBlockingMethod(method, widgetOf(sender()), omit_dialogs);
if (success)
{
emit recordingStateChangedSignal(false);
}
else
{
emit recordingStateChangedSignal(rec_server_->RecordersRecording());
if (!omit_dialogs)
{
QMessageBox error_message;
error_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
error_message.setIcon(QMessageBox::Icon::Critical);
error_message.setWindowTitle("Error");
error_message.setText("Error stopping recording");
error_message.exec();
}
}
return success;
}
////////////////////////////////////
// State //
////////////////////////////////////
bool QEcalRec::recordersConnectedToEcal() const { return rec_server_->RecordersConnectedToEcal(); };
bool QEcalRec::recordersRecording() const { return rec_server_->RecordersRecording(); };
std::map<std::string, eCAL::rec::RecorderState> QEcalRec::recorderStates() const { return rec_server_->GetRecorderStates(); };
bool QEcalRec::localRecorderInstanceBusy() const { return rec_server_->IsLocalRecorderInstanceBusy(); };
eCAL::rec::RecorderState QEcalRec::localRecorderInstanceState() const { return rec_server_->GetLocalRecorderInstanceState(); };
////////////////////////////////////
// Options //
////////////////////////////////////
void QEcalRec::setUsingBuiltInRecorderEnabled(bool enabled)
{
rec_server_->SetUsingBuiltInRecorderEnabled(enabled);
emit usingBuiltInRecorderEnabledChangedSignal(enabled);
QMessageBox info_message;
info_message.setWindowIcon(QIcon(":/ecalrec/APP_ICON"));
info_message.setIcon(QMessageBox::Icon::Information);
info_message.setWindowTitle("Info");
info_message.setText("Please uncheck & check the local recorder in the recorder manager again to effectively change it!");
info_message.exec();
}
bool QEcalRec::usingBuiltInRecorderEnabled() const
{
return rec_server_->IsUsingBuiltInRecorderEnabled();
}
////////////////////////////////////
// Additional methods //
////////////////////////////////////
std::map<std::string, eCAL::rec::TopicInfo> QEcalRec::monitorTopicInfo() const
{
return monitoring_thread_->topicInfoMap();
}
std::map<std::string, bool> QEcalRec::hostsRunningEcalRec() const
{
return monitoring_thread_->hostsRunningEcalRec();
}
void QEcalRec::sendStateUpdate()
{
emit stateUpdateSignal(rec_server_->GetRecorderStates());
}
QWidget* QEcalRec::widgetOf(QObject* q_object)
{
QWidget* widget = nullptr;
QObject* object = q_object;
while (object != nullptr)
{
widget = qobject_cast<QWidget*>(object);
if (widget != nullptr)
{
break;
}
else
{
object = object->parent();
}
if (object == q_object)
{
break;
}
}
return widget;
}
| 32.993939 | 196 | 0.672208 | NewProggie |
0bcccb877eee61c1da092529970437fd4bf0d898 | 5,080 | cpp | C++ | sources/source/tierlibs.cpp | vocweb/cso2-launcher | abc144acaa3dfb5b0c9acd61cd75970cac012617 | [
"MIT"
] | 55 | 2018-09-01T17:52:17.000Z | 2019-09-23T10:30:49.000Z | sources/source/tierlibs.cpp | RedheatWei/cso2-launcher | 4cebbb98d51d33bd24c9a86a1d3fc311686d5011 | [
"MIT"
] | 70 | 2018-08-22T05:53:34.000Z | 2019-09-23T15:11:39.000Z | sources/source/tierlibs.cpp | RedheatWei/cso2-launcher | 4cebbb98d51d33bd24c9a86a1d3fc311686d5011 | [
"MIT"
] | 39 | 2018-09-01T21:42:50.000Z | 2019-09-23T18:38:07.000Z | #include "source/tierlibs.hpp"
#include <stdexcept>
#include "platform.hpp"
#include <engine/cdll_int.hpp>
#include <engine/cso2/icso2msgmanager.hpp>
#include <filesystem/filesystem.hpp>
#include <icvar.hpp>
#include <ienginevgui.hpp>
#include <inputsystem/iinputsystem.hpp>
#include <materialsystem/imaterialsystem.hpp>
#include <tier0/cso2/iloadingsplash.hpp>
#include <tier0/cso2/iprecommandlineparser.hpp>
#include <tier0/dbg.hpp>
#include <tier0/icommandline.hpp>
#include <tier0/platform.hpp>
#include <vgui/ilocalize.hpp>
template <class T>
inline T* FactoryCast( CreateInterfaceFn f, const char* szName, int* retCode )
{
return reinterpret_cast<T*>( f( szName, retCode ) );
}
//
// tier1 libraries
//
ICvar* g_pCVar = nullptr;
void ConnectTier1Libraries( CreateInterfaceFn factory )
{
g_pCVar = FactoryCast<ICvar>( factory, CVAR_INTERFACE_VERSION, NULL );
}
//
// tier2 libraries
//
IFileSystem* g_pFullFileSystem = nullptr;
IMaterialSystem* g_pMaterialSystem = nullptr;
IInputSystem* g_pInputSystem = nullptr;
void ConnectTier2Libraries( CreateInterfaceFn factory )
{
g_pFullFileSystem =
FactoryCast<IFileSystem>( factory, FILESYSTEM_INTERFACE_VERSION, NULL );
g_pMaterialSystem = FactoryCast<IMaterialSystem>(
factory, MATERIAL_SYSTEM_INTERFACE_VERSION, NULL );
g_pInputSystem = FactoryCast<IInputSystem>(
factory, INPUTSYSTEM_INTERFACE_VERSION, NULL );
}
//
// tier3 libraries
//
vgui::ILocalize* g_pVGuiLocalize = nullptr;
void ConnectTier3Libraries( CreateInterfaceFn factory )
{
g_pVGuiLocalize = FactoryCast<vgui::ILocalize>(
factory, VGUI_LOCALIZE_INTERFACE_VERSION, NULL );
}
//
// aditional libraries
//
IVEngineClient* g_pEngineClient = nullptr;
ICSO2MsgHandlerEngine* g_pCSO2MsgHandler = nullptr;
IEngineVGui* g_pEngineVGui = nullptr;
void ConnectNonTierLibraries( CreateInterfaceFn factory )
{
g_pEngineClient = FactoryCast<IVEngineClient>(
factory, VENGINE_CLIENT_INTERFACE_VERSION, NULL );
g_pCSO2MsgHandler = FactoryCast<ICSO2MsgHandlerEngine>(
factory, CSO2_MSGHANDLER_ENGINE_VERSION, NULL );
g_pEngineVGui =
FactoryCast<IEngineVGui>( factory, VENGINE_VGUI_VERSION, NULL );
}
void ConnectAllLibraries( CreateInterfaceFn factory )
{
ConnectTier1Libraries( factory );
ConnectTier2Libraries( factory );
ConnectTier3Libraries( factory );
ConnectNonTierLibraries( factory );
}
//
// tier0 imports
//
void* GetTierZeroModule()
{
static void* zeroModuleBase = nullptr;
if ( zeroModuleBase == nullptr )
{
zeroModuleBase = Sys_LoadLibrary( "tier0.dll" );
if ( zeroModuleBase == nullptr )
{
throw std::runtime_error(
"Could not find/load tier0.dll.\n"
"Make sure the launcher is in the correct directory." );
}
}
return zeroModuleBase;
}
template <typename FuncType>
inline FuncType GetTierZeroExport( const char* exportName )
{
auto res = reinterpret_cast<FuncType>(
Sys_GetModuleExport( GetTierZeroModule(), exportName ) );
if ( res == nullptr )
{
std::string errMsg = "Could not get tier0 export ";
errMsg += exportName;
throw std::runtime_error( errMsg );
}
return res;
}
ICommandLine* CommandLine()
{
using fn_t = ICommandLine* (*)();
static fn_t pFunc = nullptr;
if ( pFunc == nullptr )
{
pFunc = GetTierZeroExport<fn_t>( "CommandLine_Tier0" );
}
return pFunc();
}
ICSO2LoadingSplash* GetCSO2LoadingSplash()
{
using fn_t = ICSO2LoadingSplash* (*)();
static fn_t pFunc = nullptr;
if ( pFunc == nullptr )
{
pFunc = GetTierZeroExport<fn_t>( "GetCSO2LoadingSplash" );
}
return pFunc();
}
void SpewOutputFunc( SpewOutputFunc_t func )
{
using fn_t = void ( * )( SpewOutputFunc_t );
static fn_t pFunc = nullptr;
if ( pFunc == nullptr )
{
pFunc = GetTierZeroExport<fn_t>( "SpewOutputFunc" );
}
pFunc( func );
}
ICSO2PreCommandLineParser* GetCSO2PreCommandLineParser()
{
using fn_t = ICSO2PreCommandLineParser* (*)();
static fn_t pFunc = nullptr;
if ( pFunc == nullptr )
{
pFunc = GetTierZeroExport<fn_t>( "GetCSO2PreCommandLineParser" );
}
return pFunc();
}
const char* GetSpewOutputGroup()
{
using fn_t = const char* (*)();
static fn_t pFunc = nullptr;
if ( pFunc == nullptr )
{
pFunc = GetTierZeroExport<fn_t>( "GetSpewOutputGroup" );
}
return pFunc();
}
bool ShouldUseNewAssertDialog()
{
using fn_t = bool ( * )();
static fn_t pFunc = nullptr;
if ( pFunc == nullptr )
{
pFunc = GetTierZeroExport<fn_t>( "ShouldUseNewAssertDialog" );
}
return pFunc();
}
double Plat_FloatTime()
{
using fn_t = double ( * )();
static fn_t pFunc = nullptr;
if ( pFunc == nullptr )
{
pFunc = GetTierZeroExport<fn_t>( "Plat_FloatTime" );
}
return pFunc();
}
IEngineVGuiInternal* EngineVGui()
{
return static_cast<IEngineVGuiInternal*>( g_pEngineVGui );
}
| 22.280702 | 80 | 0.679528 | vocweb |
0bccddf213e19d92d23231e5ae552bcb6995d072 | 4,581 | cpp | C++ | openframeworks/Web/src/ofApp.cpp | isabella232/CreativeCoding | e62acaea9ecf527b0b72c1881ece1d7c03d56e5b | [
"MIT"
] | 23 | 2018-04-08T17:46:01.000Z | 2022-03-12T21:00:52.000Z | openframeworks/Web/src/ofApp.cpp | DalavanCloud/CreativeCoding | e62acaea9ecf527b0b72c1881ece1d7c03d56e5b | [
"MIT"
] | 1 | 2021-06-09T06:53:48.000Z | 2021-06-09T08:04:27.000Z | openframeworks/Web/src/ofApp.cpp | DalavanCloud/CreativeCoding | e62acaea9ecf527b0b72c1881ece1d7c03d56e5b | [
"MIT"
] | 3 | 2018-06-03T22:20:36.000Z | 2021-06-09T06:38:16.000Z | #include "ofApp.h"
#include "ofxSyphonClient.h"
#include "MeshUtils.h"
#include "PointFollower.h"
#include "Follower.h"
#include "ImageLoader.h"
MeshUtils utils;
ofxSyphonServer syphon;
const string APP_NAME = "Web";
bool paused = true;
const int OPACITY = 2;
const int CONNECT_DISTANCE = 30;
const float VELOCITY = 10;
const int POINT_COUNT = 30;
const bool RANDOM_POINTS = true;
const int BOUNDS_PADDING = 100;
const bool DRAW_GUIDES = false;
const int PATH_JITTER = 50;
const string IMG_PATH = "../../../images/masks/tree.gif";
vector <ofPoint> drawnPoints;
ofVboMesh lineMesh;
ofVboMesh pointMesh;
vector<ofVec3f> points;
ofRectangle bounds;
//Mover mover;
Follower follower;
PointFollower pointFollower;
ImageLoader image;
//change movement algorithm to move between points
//change to ofVboMesh
//--------------------------------------------------------------
void ofApp::setup(){
utils.enableScreenshot(APP_NAME);
syphon.setName(APP_NAME);
ofSetBackgroundAuto(true);
ofSetBackgroundColor(ofColor::white);
bounds = ofGetWindowRect();
image.load(IMG_PATH);
image.resize(640, 640);
lineMesh.setMode(OF_PRIMITIVE_LINES);
lineMesh.enableColors();
pointFollower.setToRandomLocation();
pointFollower.setToRandomVelocity(VELOCITY);
pointFollower.randomOrder = RANDOM_POINTS;
pointFollower.pathJitter = PATH_JITTER;
points = mGetRandomPointsInBounds(mGetBoundsWithPadding(bounds, BOUNDS_PADDING), POINT_COUNT);
pointFollower.setPoints(points);
pointMesh.setMode(OF_PRIMITIVE_POINTS);
pointMesh.enableColors();
for(auto point : points ){
pointMesh.addColor(ofColor::black);
pointMesh.addVertex(point);
}
follower.setTarget(&pointFollower);
follower.setToRandomLocation();
follower.attractionCoefficient = 0.2;
}
//--------------------------------------------------------------
void ofApp::update(){
if(paused) {
return;
}
//mover.checkBounds();
//mover.update();
follower.update();
pointFollower.update();
ofPoint mouse = follower.location;
for(auto point : drawnPoints) {
float dist = (mouse - point).length();
if(dist < CONNECT_DISTANCE) {
lineMesh.addColor(ofColor(image.getColor(mouse), OPACITY));
lineMesh.addVertex(mouse);
lineMesh.addColor(ofColor(image.getColor(point), OPACITY));
lineMesh.addVertex(point);
}
}
drawnPoints.push_back(mouse);
}
//--------------------------------------------------------------
void ofApp::draw(){
if(paused) {
syphon.publishScreen();
return;
}
//ofEnableAlphaBlending();
if(DRAW_GUIDES) {
pointMesh.draw();
ofNoFill();
ofSetColor(ofColor::red);
ofDrawCircle(pointFollower.getCurrentPoint(), 12);
ofFill();
ofSetColor(ofColor::black);
ofSetColor(ofColor::red);
ofDrawLine(follower.location, pointFollower.location);
ofDrawCircle(pointFollower.location, 2);
ofDrawCircle(follower.location, 2);
}
lineMesh.draw();
syphon.publishScreen();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if(key == ' ') {
paused = !paused;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 22.678218 | 98 | 0.519756 | isabella232 |
0bcd809ea0d4ed685272d2bd6d7080129cc2ea7d | 91,177 | cpp | C++ | src/shell/shell.cpp | mediaexplorer74/dosbox-x | be9f94b740234f7813bf5a063a558cef9dc7f9a6 | [
"MIT"
] | 3 | 2022-02-20T11:06:29.000Z | 2022-03-11T08:16:55.000Z | src/shell/shell.cpp | mediaexplorer74/dosbox-x | be9f94b740234f7813bf5a063a558cef9dc7f9a6 | [
"MIT"
] | null | null | null | src/shell/shell.cpp | mediaexplorer74/dosbox-x | be9f94b740234f7813bf5a063a558cef9dc7f9a6 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2002-2021 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <assert.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <sys/stat.h>
#include <gtest/gtest.h>
#include "dosbox.h"
#include "logging.h"
#include "regs.h"
#include "control.h"
#include "shell.h"
#include "menu.h"
#include "cpu.h"
#include "callback.h"
#include "dos_inc.h"
#include "support.h"
#include "mapper.h"
#include "render.h"
#include "jfont.h"
#include "../dos/drives.h"
#include "../ints/int10.h"
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include <vector>
#if defined(WIN32)
#include <windows.h>
#else
#include <dirent.h>
#endif
#include "build_timestamp.h"
extern bool startcmd, startwait, startquiet, winautorun;
extern bool halfwidthkana, force_conversion, showdbcs;
extern bool dos_shell_running_program, mountwarning;
extern bool addovl, addipx, addne2k, enableime, gbk;
extern const char* RunningProgram;
extern int enablelfn, msgcodepage;
extern uint16_t countryNo;
extern unsigned int dosbox_shell_env_size;
bool outcon = true, usecon = true;
bool shellrun = false, prepared = false;
uint16_t shell_psp = 0;
Bitu call_int2e = 0;
std::string GetDOSBoxXPath(bool withexe=false);
int Reflect_Menu(void);
void SetIMPosition(void);
void initRand();
void initcodepagefont(void);
void runMount(const char *str);
void ResolvePath(std::string& in);
void DOS_SetCountry(uint16_t countryNo);
void CALLBACK_DeAllocate(Bitu in), DOSBox_ConsolePauseWait();
void GFX_SetTitle(int32_t cycles, int frameskip, Bits timing, bool paused);
bool isDBCSCP(), InitCodePage(), isKanji1(uint8_t chr), shiftjis_lead_byte(int c);
Bitu call_shellstop = 0;
/* Larger scope so shell_del autoexec can use it to
* remove things from the environment */
DOS_Shell * first_shell = 0;
static Bitu shellstop_handler(void) {
return CBRET_STOP;
}
void SHELL_ProgramStart(Program * * make) {
*make = new DOS_Shell;
}
//Repeat it with the correct type, could do it in the function below, but this way it should be
//clear that if the above function is changed, this function might need a change as well.
static void SHELL_ProgramStart_First_shell(DOS_Shell * * make) {
*make = new DOS_Shell;
}
bool i4dos=false;
char i4dos_data[CONFIG_SIZE] = { 0 };
char config_data[CONFIG_SIZE] = { 0 };
char autoexec_data[AUTOEXEC_SIZE] = { 0 };
static std::list<std::string> autoexec_strings;
typedef std::list<std::string>::iterator auto_it;
void VFILE_Remove(const char *name,const char *dir="");
void runRescan(const char *str), DOSBox_SetSysMenu(void);
void toSetCodePage(DOS_Shell *shell, int newCP, int opt);
#if defined(WIN32)
void MountAllDrives(bool quiet) {
char str[100];
uint16_t n = 0;
uint32_t drives = GetLogicalDrives();
char name[4]="A:\\";
for (int i=0; i<25; i++) {
if ((drives & (1<<i)) && !Drives[i])
{
name[0]='A'+i;
int type=GetDriveType(name);
if (type!=DRIVE_NO_ROOT_DIR) {
if (!quiet) {
sprintf(str, "Mounting %c: => %s..\r\n", name[0], name);
n = (uint16_t)strlen(str);
DOS_WriteFile(STDOUT,(uint8_t *)str,&n);
}
char mountstring[DOS_PATHLENGTH+CROSS_LEN+20];
name[2]=' ';
strcpy(mountstring,name);
name[2]='\\';
strcat(mountstring,name);
strcat(mountstring," -Q");
runMount(mountstring);
if (!Drives[i] && !quiet) {
sprintf(str, "Drive %c: failed to mount.\r\n",name[0]);
n = (uint16_t)strlen(str);
DOS_WriteFile(STDOUT,(uint8_t *)str,&n);
} else if(mountwarning && !quiet && type==DRIVE_FIXED && (strcasecmp(name,"C:\\")==0)) {
strcpy(str, MSG_Get("PROGRAM_MOUNT_WARNING_WIN"));
if (strlen(str)>2&&str[strlen(str)-1]=='\n'&&str[strlen(str)-2]!='\r') {
str[strlen(str)-1]=0;
strcat(str, "\r\n");
}
n = (uint16_t)strlen(str);
DOS_WriteFile(STDOUT,(uint8_t *)str,&n);
}
}
}
}
}
#endif
void AutoexecObject::Install(const std::string &in) {
if(GCC_UNLIKELY(installed)) E_Exit("autoexec: already created %s",buf.c_str());
installed = true;
buf = in;
autoexec_strings.push_back(buf);
this->CreateAutoexec();
//autoexec.bat is normally created AUTOEXEC_Init.
//But if we are already running (first_shell)
//we have to update the envirionment to display changes
if(first_shell) {
//create a copy as the string will be modified
std::string::size_type n = buf.size();
char* buf2 = new char[n + 1];
safe_strncpy(buf2, buf.c_str(), n + 1);
if((strncasecmp(buf2,"set ",4) == 0) && (strlen(buf2) > 4)){
char* after_set = buf2 + 4;//move to variable that is being set
char* test2 = strpbrk(after_set,"=");
if(!test2) {first_shell->SetEnv(after_set,"");return;}
*test2++ = 0;
//If the shell is running/exists update the environment
first_shell->SetEnv(after_set,test2);
}
delete [] buf2;
}
}
void AutoexecObject::InstallBefore(const std::string &in) {
if(GCC_UNLIKELY(installed)) E_Exit("autoexec: already created %s",buf.c_str());
installed = true;
buf = in;
autoexec_strings.push_front(buf);
this->CreateAutoexec();
}
void AutoexecObject::CreateAutoexec(void) {
/* Remove old autoexec.bat if the shell exists */
if(first_shell) VFILE_Remove("AUTOEXEC.BAT");
//Create a new autoexec.bat
autoexec_data[0] = 0;
size_t auto_len;
for(auto_it it = autoexec_strings.begin(); it != autoexec_strings.end(); ++it) {
std::string linecopy = *it;
std::string::size_type offset = 0;
//Lets have \r\n as line ends in autoexec.bat.
while(offset < linecopy.length()) {
std::string::size_type n = linecopy.find("\n",offset);
if ( n == std::string::npos ) break;
std::string::size_type rn = linecopy.find("\r\n",offset);
if ( rn != std::string::npos && rn + 1 == n) {offset = n + 1; continue;}
// \n found without matching \r
linecopy.replace(n,1,"\r\n");
offset = n + 2;
}
auto_len = strlen(autoexec_data);
if ((auto_len+linecopy.length() + 3) > AUTOEXEC_SIZE) {
E_Exit("SYSTEM:Autoexec.bat file overflow");
}
sprintf((autoexec_data + auto_len),"%s\r\n",linecopy.c_str());
}
if (first_shell) VFILE_Register("AUTOEXEC.BAT",(uint8_t *)autoexec_data,(uint32_t)strlen(autoexec_data));
}
void AutoexecObject::Uninstall() {
if(!installed) return;
// Remove the line from the autoexecbuffer and update environment
for(auto_it it = autoexec_strings.begin(); it != autoexec_strings.end(); ) {
if ((*it) == buf) {
std::string::size_type n = buf.size();
char* buf2 = new char[n + 1];
safe_strncpy(buf2, buf.c_str(), n + 1);
bool stringset = false;
// If it's a environment variable remove it from there as well
if ((strncasecmp(buf2,"set ",4) == 0) && (strlen(buf2) > 4)){
char* after_set = buf2 + 4;//move to variable that is being set
char* test2 = strpbrk(after_set,"=");
if (!test2) {
delete [] buf2;
continue;
}
*test2 = 0;
stringset = true;
//If the shell is running/exists update the environment
if (first_shell) first_shell->SetEnv(after_set,"");
}
delete [] buf2;
if (stringset && first_shell && first_shell->bf && first_shell->bf->filename.find("AUTOEXEC.BAT") != std::string::npos) {
//Replace entry with spaces if it is a set and from autoexec.bat, as else the location counter will be off.
*it = buf.assign(buf.size(),' ');
++it;
} else {
it = autoexec_strings.erase(it);
}
} else ++it;
}
installed=false;
this->CreateAutoexec();
}
AutoexecObject::~AutoexecObject(){
Uninstall();
}
DOS_Shell::~DOS_Shell() {
if (bf != NULL) delete bf; /* free batch file */
}
DOS_Shell::DOS_Shell():Program(){
input_handle=STDIN;
echo=true;
exit=false;
perm = false;
bf=0;
call=false;
exec=false;
lfnfor = uselfn;
input_eof=false;
completion_index = 0;
}
Bitu DOS_Shell::GetRedirection(char *s, char **ifn, char **ofn, char **toc,bool * append) {
char * lr=s;
char * lw=s;
char ch;
Bitu num=0;
bool quote = false;
bool lead1 = false, lead2 = false;
char* t;
int q;
while ( (ch=*lr++) ) {
if(quote && ch != '"') { /* don't parse redirection within quotes. Not perfect yet. Escaped quotes will mess the count up */
*lw++ = ch;
continue;
}
if (lead1) {
lead1=false;
if (ch=='|') {
*lw++=ch;
continue;
}
} else if ((IS_PC98_ARCH && shiftjis_lead_byte(ch)) || (isDBCSCP() && !((dos.loaded_codepage == 936 || IS_PDOSV) && !gbk) && isKanji1(ch))) lead1 = true;
switch (ch) {
case '"':
quote = !quote;
break;
case '>':
*append = ((*lr) == '>');
if (*append)
lr++;
lr = ltrim(lr);
if (*ofn)
free(*ofn);
*ofn = lr;
q = 0;
lead2 = false;
while (*lr && (q/2*2!=q || *lr != ' ') && *lr != '<' && !(!lead2 && *lr == '|')) {
if (lead2)
lead2 = false;
else if ((IS_PC98_ARCH && shiftjis_lead_byte(*lr&0xff)) || (isDBCSCP() && !((dos.loaded_codepage == 936 || IS_PDOSV) && !gbk) && isKanji1(*lr&0xff)))
lead2 = true;
if (*lr=='"')
q++;
lr++;
}
// if it ends on a : => remove it.
if ((*ofn != lr) && (lr[-1] == ':'))
lr[-1] = 0;
t = (char*)malloc(lr-*ofn+1);
safe_strncpy(t, *ofn, lr-*ofn+1);
*ofn = t;
continue;
case '<':
if (*ifn)
free(*ifn);
lr = ltrim(lr);
*ifn = lr;
q = 0;
lead2 = false;
while (*lr && (q/2*2!=q || *lr != ' ') && *lr != '>' && !(!lead2 && *lr == '|')) {
if (lead2)
lead2 = false;
else if ((IS_PC98_ARCH && shiftjis_lead_byte(*lr&0xff)) || (isDBCSCP() && !((dos.loaded_codepage == 936 || IS_PDOSV) && !gbk) && isKanji1(*lr&0xff)))
lead2 = true;
if (*lr=='"')
q++;
lr++;
}
if ((*ifn != lr) && (lr[-1] == ':'))
lr[-1] = 0;
t = (char*)malloc(lr-*ifn+1);
safe_strncpy(t, *ifn, lr-*ifn+1);
*ifn = t;
continue;
case '|':
num++;
if (*toc)
free(*toc);
lr = ltrim(lr);
*toc = lr;
while (*lr)
lr++;
t = (char*)malloc(lr-*toc+1);
safe_strncpy(t, *toc, lr-*toc+1);
*toc = t;
continue;
}
*lw++=ch;
}
*lw=0;
return num;
}
void DOS_Shell::ParseLine(char * line) {
LOG(LOG_EXEC,LOG_DEBUG)("Parsing command line: %s",line);
/* Check for a leading @ */
if (line[0] == '@') line[0] = ' ';
line = trim(line);
/* Do redirection and pipe checks */
char * in = 0;
char * out = 0;
char * toc = 0;
uint16_t dummy,dummy2;
uint32_t bigdummy = 0;
bool append;
bool normalstdin = false; /* whether stdin/out are open on start. */
bool normalstdout = false; /* Bug: Assumed is they are "con" */
GetRedirection(line, &in, &out, &toc, &append);
if (in || out || toc) {
normalstdin = (psp->GetFileHandle(0) != 0xff);
normalstdout = (psp->GetFileHandle(1) != 0xff);
}
if (in) {
if(DOS_OpenFile(in,OPEN_READ,&dummy)) { //Test if file exists
DOS_CloseFile(dummy);
LOG_MSG("SHELL:Redirect input from %s",in);
if(normalstdin) DOS_CloseFile(0); //Close stdin
DOS_OpenFile(in,OPEN_READ,&dummy); //Open new stdin
} else {
WriteOut(!*in?"File open error\n":(dos.errorcode==DOSERR_ACCESS_DENIED?MSG_Get("SHELL_CMD_FILE_ACCESS_DENIED"):"File open error - %s\n"), in);
in = 0;
return;
}
}
bool fail=false;
char pipetmp[270];
uint16_t fattr;
if (toc) {
initRand();
std::string line;
if (!GetEnvStr("TEMP",line)&&!GetEnvStr("TMP",line))
sprintf(pipetmp, "pipe%d.tmp", rand()%10000);
else {
std::string::size_type idx = line.find('=');
std::string temp=line.substr(idx +1 , std::string::npos);
if (DOS_GetFileAttr(temp.c_str(), &fattr) && fattr&DOS_ATTR_DIRECTORY)
sprintf(pipetmp, "%s\\pipe%d.tmp", temp.c_str(), rand()%10000);
else
sprintf(pipetmp, "pipe%d.tmp", rand()%10000);
}
}
if (out||toc) {
if (out&&toc)
WriteOut(!*out?"Duplicate redirection\n":"Duplicate redirection - %s\n", out);
LOG_MSG("SHELL:Redirect output to %s",toc?pipetmp:out);
if(normalstdout) DOS_CloseFile(1);
if(!normalstdin && !in) DOS_OpenFile("con",OPEN_READWRITE,&dummy);
bool status = true;
/* Create if not exist. Open if exist. Both in read/write mode */
if(!toc&&append) {
if (DOS_GetFileAttr(out, &fattr) && fattr&DOS_ATTR_READ_ONLY) {
DOS_SetError(DOSERR_ACCESS_DENIED);
status = false;
} else if( (status = DOS_OpenFile(out,OPEN_READWRITE,&dummy)) ) {
DOS_SeekFile(1,&bigdummy,DOS_SEEK_END);
} else {
status = DOS_CreateFile(out,DOS_ATTR_ARCHIVE,&dummy); //Create if not exists.
}
} else if (!toc&&DOS_GetFileAttr(out, &fattr) && fattr&DOS_ATTR_READ_ONLY) {
DOS_SetError(DOSERR_ACCESS_DENIED);
status = false;
} else {
if (toc&&DOS_FindFirst(pipetmp, ~DOS_ATTR_VOLUME)&&!DOS_UnlinkFile(pipetmp))
fail=true;
status = DOS_OpenFileExtended(toc&&!fail?pipetmp:out,OPEN_READWRITE,DOS_ATTR_ARCHIVE,0x12,&dummy,&dummy2);
if (toc&&(fail||!status)&&!strchr(pipetmp,'\\')&&(Drives[0]||Drives[2])) {
int len = (int)strlen(pipetmp);
if (len > 266) {
len = 266;
pipetmp[len] = 0;
}
for (int i = len; i >= 0; i--)
pipetmp[i + 3] = pipetmp[i];
pipetmp[0] = Drives[2]?'c':'a';
pipetmp[1] = ':';
pipetmp[2] = '\\';
fail=false;
if (DOS_FindFirst(pipetmp, ~DOS_ATTR_VOLUME) && !DOS_UnlinkFile(pipetmp))
fail=true;
else
status = DOS_OpenFileExtended(pipetmp, OPEN_READWRITE, DOS_ATTR_ARCHIVE, 0x12, &dummy, &dummy2);
}
}
if(!status && normalstdout) {
DOS_OpenFile("con", OPEN_READWRITE, &dummy); // Read only file, open con again
if (!toc) {
WriteOut(!*out?"File creation error\n":(dos.errorcode==DOSERR_ACCESS_DENIED?MSG_Get("SHELL_CMD_FILE_ACCESS_DENIED"):"File creation error - %s\n"), out);
DOS_CloseFile(1);
DOS_OpenFile("nul", OPEN_READWRITE, &dummy);
}
}
if(!normalstdin && !in) DOS_CloseFile(0);
}
/* Run the actual command */
if (this == first_shell) dos_shell_running_program = true;
#if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU
Reflect_Menu();
#endif
if (toc||(!toc&&((out&&DOS_FindDevice(out)!=DOS_FindDevice("con"))))) outcon=false;
if (toc||(!toc&&((out&&DOS_FindDevice(out)!=DOS_FindDevice("con"))||(in&&DOS_FindDevice(in)!=DOS_FindDevice("con"))))) usecon=false;
DoCommand(line);
if (this == first_shell) dos_shell_running_program = false;
#if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU
Reflect_Menu();
#endif
/* Restore handles */
if(in) {
DOS_CloseFile(0);
if(normalstdin) DOS_OpenFile("con",OPEN_READWRITE,&dummy);
free(in);
}
if(out||toc) {
DOS_CloseFile(1);
if(!normalstdin) DOS_OpenFile("con",OPEN_READWRITE,&dummy);
if(normalstdout) DOS_OpenFile("con",OPEN_READWRITE,&dummy);
if(!normalstdin) DOS_CloseFile(0);
if (out) free(out);
}
if (toc)
{
if (!fail&&DOS_OpenFile(pipetmp, OPEN_READ, &dummy)) // Test if file can be opened for reading
{
DOS_CloseFile(dummy);
if (normalstdin)
DOS_CloseFile(0); // Close stdin
DOS_OpenFile(pipetmp, OPEN_READ, &dummy); // Open new stdin
ParseLine(toc);
DOS_CloseFile(0);
if (normalstdin)
DOS_OpenFile("con", OPEN_READWRITE, &dummy);
}
else
WriteOut("\nFailed to create/open a temporary file for piping. Check the %%TEMP%% variable.\n");
free(toc);
if (DOS_FindFirst(pipetmp, ~DOS_ATTR_VOLUME)) DOS_UnlinkFile(pipetmp);
}
outcon=usecon=true;
}
void DOS_Shell::RunInternal(void) {
char input_line[CMD_MAXLINE] = {0};
while (bf) {
if (bf->ReadLine(input_line)) {
if (echo) {
if (input_line[0] != '@') {
ShowPrompt();
WriteOut_NoParsing(input_line);
WriteOut_NoParsing("\n");
}
}
ParseLine(input_line);
if (echo) WriteOut_NoParsing("\n");
}
}
}
char *str_replace(char *orig, char *rep, char *with);
std::string GetPlatform(bool save);
bool ANSI_SYS_installed();
const char *ParseMsg(const char *msg) {
char str[13];
strncpy(str, UPDATED_STR, 12);
str[12]=0;
if (machine != MCH_PC98) {
if (!ANSI_SYS_installed() || J3_IsJapanese()) {
msg = str_replace(str_replace((char *)msg, (char*)"\033[0m", (char*)""), (char*)"\033[1m", (char*)"");
for (int i=1; i<8; i++) {
sprintf(str, "\033[3%dm", i);
msg = str_replace((char *)msg, str, (char*)"");
sprintf(str, "\033[4%d;1m", i);
msg = str_replace((char *)msg, str, (char*)"");
}
}
Section_prop *section = static_cast<Section_prop *>(control->GetSection("dosbox"));
std::string theme = section->Get_string("bannercolortheme");
if (theme == "black")
msg = str_replace((char *)msg, (char*)"\033[44;1m", (char*)"\033[40;1m");
else if (theme == "red")
msg = str_replace(str_replace((char *)msg, (char*)"\033[31m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[41;1m");
else if (theme == "green")
msg = str_replace(str_replace(str_replace((char *)msg, (char*)"\033[36m", (char*)"\033[34m"), (char*)"\033[32m", (char*)"\033[36m"), (char*)"\033[44;1m", (char*)"\033[42;1m");
else if (theme == "yellow")
msg = str_replace(str_replace((char *)msg, (char*)"\033[31m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[43;1m");
else if (theme == "blue")
msg = str_replace((char *)msg, (char*)"\033[44;1m", (char*)"\033[44;1m");
else if (theme == "magenta")
msg = str_replace(str_replace((char *)msg, (char*)"\033[31m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[45;1m");
else if (theme == "cyan")
msg = str_replace(str_replace((char *)msg, (char*)"\033[36m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[46;1m");
else if (theme == "white")
msg = str_replace(str_replace((char *)msg, (char*)"\033[36m", (char*)"\033[34m"), (char*)"\033[44;1m", (char*)"\033[47;1m");
}
if (machine == MCH_PC98)
return msg;
else {
if (real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS)>80)
msg = str_replace(str_replace(str_replace((char *)msg, (char*)"\xBA\033[0m", (char*)"\xBA\033[0m\n"), (char*)"\xBB\033[0m", (char*)"\xBB\033[0m\n"), (char*)"\xBC\033[0m", (char*)"\xBC\033[0m\n");
bool uselowbox = false;
force_conversion = true;
int cp=dos.loaded_codepage;
if ((showdbcs
#if defined(USE_TTF)
|| ttf.inUse
#endif
)
#if defined(USE_TTF)
&& halfwidthkana
#endif
&& InitCodePage() && dos.loaded_codepage==932) uselowbox = true;
force_conversion = false;
dos.loaded_codepage=cp;
if (uselowbox || IS_JEGA_ARCH || IS_JDOSV) {
std::string m=msg;
if (strstr(msg, "\xCD\xCD\xCD\xCD") != NULL) {
if (IS_JEGA_ARCH) {
msg = str_replace((char *)msg, (char*)"\xC9", (char *)std::string(1, 0x15).c_str());
msg = str_replace((char *)msg, (char*)"\xBB", (char *)std::string(1, 0x16).c_str());
msg = str_replace((char *)msg, (char*)"\xC8", (char *)std::string(1, 0x18).c_str());
msg = str_replace((char *)msg, (char*)"\xBC", (char *)std::string(1, 0x17).c_str());
msg = str_replace((char *)msg, (char*)"\xCD", (char *)std::string(1, 0x13).c_str());
} else {
msg = str_replace((char *)msg, (char*)"\xC9", (char *)std::string(1, 1).c_str());
msg = str_replace((char *)msg, (char*)"\xBB", (char *)std::string(1, 2).c_str());
msg = str_replace((char *)msg, (char*)"\xC8", (char *)std::string(1, 3).c_str());
msg = str_replace((char *)msg, (char*)"\xBC", (char *)std::string(1, 4).c_str());
msg = str_replace((char *)msg, (char*)"\xCD", (char *)std::string(1, 6).c_str());
}
} else {
if (IS_JEGA_ARCH) {
msg = str_replace((char *)msg, (char*)"\xBA ", (char *)(std::string(1, 0x14)+" ").c_str());
msg = str_replace((char *)msg, (char*)" \xBA", (char *)(" "+std::string(1, 0x14)).c_str());
} else {
msg = str_replace((char *)msg, (char*)"\xBA ", (char *)(std::string(1, 5)+" ").c_str());
msg = str_replace((char *)msg, (char*)" \xBA", (char *)(" "+std::string(1, 5)).c_str());
}
}
}
return msg;
}
}
static char const * const path_string="PATH=Z:\\;Z:\\SYSTEM;Z:\\BIN;Z:\\DOS;Z:\\4DOS;Z:\\DEBUG;Z:\\TEXTUTIL";
static char const * const comspec_string="COMSPEC=Z:\\COMMAND.COM";
static char const * const prompt_string="PROMPT=$P$G";
static char const * const full_name="Z:\\COMMAND.COM";
static char const * const init_line="/INIT AUTOEXEC.BAT";
extern uint8_t ZDRIVE_NUM;
char *str_replace(char *orig, char *rep, char *with);
void GetExpandedPath(std::string &path) {
std::string udrive = std::string(1,ZDRIVE_NUM+'A'), ldrive = std::string(1,ZDRIVE_NUM+'a');
char pathstr[100];
strcpy(pathstr, path_string+5);
if (path==udrive+":\\"||path==ldrive+":\\")
path=ZDRIVE_NUM==25?pathstr:str_replace(pathstr, (char*)"Z:\\", (char *)(udrive+":\\").c_str());
else if (path.size()>3&&(path.substr(0, 4)==udrive+":\\;"||path.substr(0, 4)==ldrive+":\\;")&&path.substr(4).find(udrive+":\\")==std::string::npos&&path.substr(4).find(ldrive+":\\")==std::string::npos)
path=std::string(ZDRIVE_NUM==25?pathstr:str_replace(pathstr, (char*)"Z:\\", (char *)(udrive+":\\").c_str()))+path.substr(3);
else if (path.size()>3) {
size_t pos = path.find(";"+udrive+":\\");
if (pos == std::string::npos) pos = path.find(";"+ldrive+":\\");
if (pos != std::string::npos && (!path.substr(pos+4).size() || (path[pos+4]==';'&&path.substr(pos+4).find(udrive+":\\")==std::string::npos&&path.substr(pos+4).find(ldrive+":\\")==std::string::npos)))
path=path.substr(0, pos+1)+std::string(ZDRIVE_NUM==25?pathstr:str_replace(pathstr, (char*)"Z:\\", (char *)(udrive+":\\").c_str()))+path.substr(pos+4);
}
}
void DOS_Shell::Prepare(void) {
if (this == first_shell) {
Section_prop *section = static_cast<Section_prop *>(control->GetSection("dosbox"));
if (section->Get_bool("startbanner")&&!control->opt_fastlaunch) {
/* Start a normal shell and check for a first command init */
std::string verstr = "v"+std::string(VERSION)+", "+GetPlatform(false);
if (machine == MCH_PC98) {
WriteOut(ParseMsg("\x86\x52\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x56\n"));
WriteOut(ParseMsg((std::string("\x86\x46 \033[32m")+(MSG_Get("SHELL_STARTUP_TITLE")+std::string(" ")).substr(0,30)+std::string(" \033[33m%*s\033[37m \x86\x46\n")).c_str()),34,verstr.c_str());
WriteOut(ParseMsg("\x86\x46 \x86\x46\n"));
WriteOut(ParseMsg((std::string("\x86\x46 ")+MSG_Get("SHELL_STARTUP_HEAD1_PC98")+std::string(" \x86\x46\n")).c_str()));
WriteOut(ParseMsg("\x86\x46 \x86\x46\n"));
WriteOut(ParseMsg((std::string("\x86\x46 ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT1_PC98"), (char*)"\n", (char*)" \x86\x46\n\x86\x46 ")+std::string(" \x86\x46\n")).c_str()));
WriteOut(ParseMsg((std::string("\x86\x46 ")+MSG_Get("SHELL_STARTUP_EXAMPLE_PC98")+std::string(" \x86\x46\n")).c_str()));
WriteOut(ParseMsg("\x86\x46 \x86\x46\n"));
WriteOut(ParseMsg((std::string("\x86\x46 ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT2_PC98"), (char*)"\n", (char*)" \x86\x46\n\x86\x46 ")+std::string(" \x86\x46\n")).c_str()));
WriteOut(ParseMsg("\x86\x46 \x86\x46\n"));
WriteOut(ParseMsg((std::string("\x86\x46 ")+str_replace((char *)MSG_Get("SHELL_STARTUP_INFO_PC98"), (char*)"\n", (char*)" \x86\x46\n\x86\x46 ")+std::string(" \x86\x46\n")).c_str()));
WriteOut(ParseMsg("\x86\x46 \x86\x46\n"));
WriteOut(ParseMsg((std::string("\x86\x46 ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT3_PC98"), (char*)"\n", (char*)" \x86\x46\n\x86\x46 ")+std::string(" \x86\x46\n")).c_str()));
WriteOut(ParseMsg("\x86\x5A\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44"
"\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x44\x86\x5E\033[0m\n"));
WriteOut(ParseMsg((std::string("\033[1m\033[32m")+MSG_Get("SHELL_STARTUP_LAST")+"\033[0m\n").c_str()));
} else {
WriteOut(ParseMsg("\033[44;1m\xC9\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD"
"\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD"
"\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBB\033[0m"));
WriteOut(ParseMsg((std::string("\033[44;1m\xBA \033[32m")+(MSG_Get("SHELL_STARTUP_TITLE")+std::string(" ")).substr(0,30)+std::string(" \033[33m%*s\033[37m \xBA\033[0m")).c_str()),45,verstr.c_str());
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+MSG_Get("SHELL_STARTUP_HEAD1")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT1"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str()));
if (IS_VGA_ARCH) WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+MSG_Get("SHELL_STARTUP_EXAMPLE")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+MSG_Get("SHELL_STARTUP_HEAD2")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT2"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
if (IS_DOSV) {
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_DOSV"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
} else if (machine == MCH_CGA || machine == MCH_PCJR || machine == MCH_AMSTRAD) {
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get(mono_cga?"SHELL_STARTUP_CGA_MONO":"SHELL_STARTUP_CGA"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
} else if (machine == MCH_HERC || machine == MCH_MDA) {
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_HERC"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
}
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+MSG_Get("SHELL_STARTUP_HEAD3")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xBA \xBA\033[0m"));
WriteOut(ParseMsg((std::string("\033[44;1m\xBA ")+str_replace((char *)MSG_Get("SHELL_STARTUP_TEXT3"), (char*)"\n", (char*)" \xBA\033[0m\033[44;1m\xBA ")+std::string(" \xBA\033[0m")).c_str()));
WriteOut(ParseMsg("\033[44;1m\xC8\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD"
"\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD"
"\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xBC\033[0m"));
WriteOut(ParseMsg((std::string("\033[32m")+(MSG_Get("SHELL_STARTUP_LAST")+std::string(" ")).substr(0,79)+std::string("\033[0m\n")).c_str()));
}
} else if (CurMode->type==M_TEXT || IS_PC98_ARCH)
WriteOut("\033[2J");
if (!countryNo) {
#if defined(WIN32)
char buffer[128];
#endif
if (IS_PC98_ARCH || IS_JEGA_ARCH)
countryNo = 81;
else if (IS_DOSV)
countryNo = IS_PDOSV?86:(IS_TDOSV?886:(IS_KDOSV?82:81));
#if defined(WIN32)
else if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ICOUNTRY, buffer, 128)) {
countryNo = uint16_t(atoi(buffer));
DOS_SetCountry(countryNo);
}
#endif
else
countryNo = 1;
}
section = static_cast<Section_prop *>(control->GetSection("dos"));
bool zdirpath = section->Get_bool("drive z expand path");
strcpy(config_data, "");
section = static_cast<Section_prop *>(control->GetSection("config"));
if ((section!=NULL&&!control->opt_noconfig)||control->opt_langcp) {
char *countrystr = (char *)section->Get_string("country"), *r=strchr(countrystr, ',');
int country = 0;
if ((r==NULL || !*(r+1)) && !control->opt_langcp)
country = atoi(trim(countrystr));
else {
if (r!=NULL) *r=0;
country = atoi(trim(countrystr));
int newCP = r==NULL||IS_PC98_ARCH||IS_JEGA_ARCH||IS_DOSV?dos.loaded_codepage:atoi(trim(r+1));
if (control->opt_langcp && msgcodepage>0 && isSupportedCP(msgcodepage) && msgcodepage != newCP)
newCP = msgcodepage;
if (r!=NULL) *r=',';
if (!IS_PC98_ARCH&&!IS_JEGA_ARCH) {
#if defined(USE_TTF)
if (ttf.inUse) {
if (newCP) toSetCodePage(this, newCP, control->opt_fastlaunch?1:0);
else if (r!=NULL) WriteOut(MSG_Get("SHELL_CMD_CHCP_INVALID"), trim(r+1));
} else
#endif
if (!newCP && IS_DOSV) {
if (IS_JDOSV) newCP=932;
else if (IS_PDOSV) newCP=936;
else if (IS_KDOSV) newCP=949;
else if (IS_TDOSV) newCP=950;
}
if (newCP==932||newCP==936||newCP==949||newCP==950||newCP==951) {
dos.loaded_codepage=newCP;
SetupDBCSTable();
runRescan("-A -Q");
DOSBox_SetSysMenu();
}
}
}
if (country>0&&!control->opt_noconfig) {
countryNo = country;
DOS_SetCountry(countryNo);
}
const char * extra = section->data.c_str();
if (extra&&!control->opt_securemode&&!control->SecureMode()&&!control->opt_noconfig) {
std::string vstr;
std::istringstream in(extra);
char linestr[CROSS_LEN+1], cmdstr[CROSS_LEN], valstr[CROSS_LEN], tmpstr[CROSS_LEN];
char *cmd=cmdstr, *val=valstr, *tmp=tmpstr, *p;
if (in) for (std::string line; std::getline(in, line); ) {
if (line.length()>CROSS_LEN) {
strncpy(linestr, line.c_str(), CROSS_LEN);
linestr[CROSS_LEN]=0;
} else
strcpy(linestr, line.c_str());
p=strchr(linestr, '=');
if (p!=NULL) {
*p=0;
strcpy(cmd, linestr);
strcpy(val, p+1);
cmd=trim(cmd);
val=trim(val);
if (strlen(config_data)+strlen(cmd)+strlen(val)+3<CONFIG_SIZE) {
strcat(config_data, cmd);
strcat(config_data, "=");
strcat(config_data, val);
strcat(config_data, "\r\n");
}
if (!strncasecmp(cmd, "set ", 4)) {
vstr=std::string(val);
ResolvePath(vstr);
if (zdirpath && !strcmp(cmd, "set path")) GetExpandedPath(vstr);
DoCommand((char *)(std::string(cmd)+"="+vstr).c_str());
} else if (!strcasecmp(cmd, "install")||!strcasecmp(cmd, "installhigh")||!strcasecmp(cmd, "device")||!strcasecmp(cmd, "devicehigh")) {
vstr=std::string(val);
ResolvePath(vstr);
strcpy(tmp, vstr.c_str());
char *name=StripArg(tmp);
if (!*name) continue;
if (!DOS_FileExists(name)&&!DOS_FileExists((std::string("Z:\\SYSTEM\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\BIN\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\DOS\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\4DOS\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\DEBUG\\")+name).c_str())&&!DOS_FileExists((std::string("Z:\\TEXTUTIL\\")+name).c_str())) {
WriteOut(MSG_Get("SHELL_MISSING_FILE"), name);
continue;
}
if (!strcasecmp(cmd, "install"))
DoCommand((char *)vstr.c_str());
else if (!strcasecmp(cmd, "installhigh"))
DoCommand((char *)("lh "+vstr).c_str());
else if (!strcasecmp(cmd, "device"))
DoCommand((char *)("device "+vstr).c_str());
else if (!strcasecmp(cmd, "devicehigh"))
DoCommand((char *)("lh device "+vstr).c_str());
}
} else if (!strncasecmp(line.c_str(), "rem ", 4)) {
strcat(config_data, line.c_str());
strcat(config_data, "\r\n");
}
}
}
}
std::string line;
GetEnvStr("PATH",line);
if (!strlen(config_data)) {
strcat(config_data, "rem=");
strcat(config_data, section->Get_string("rem"));
strcat(config_data, "\r\n");
}
VFILE_Register("CONFIG.SYS",(uint8_t *)config_data,(uint32_t)strlen(config_data));
#if defined(WIN32)
if (!control->opt_securemode&&!control->SecureMode())
{
const Section_prop* sec = static_cast<Section_prop*>(control->GetSection("dos"));
const char *automountstr = sec->Get_string("automountall");
if (strcmp(automountstr, "0") && strcmp(automountstr, "false")) MountAllDrives(!strcmp(automountstr, "quiet")||control->opt_fastlaunch);
}
#endif
strcpy(i4dos_data, "");
section = static_cast<Section_prop *>(control->GetSection("4dos"));
if (section!=NULL) {
const char * extra = section->data.c_str();
if (extra) {
std::istringstream in(extra);
if (in) for (std::string line; std::getline(in, line); ) {
if (strncasecmp(line.c_str(), "rem=", 4)&&strncasecmp(line.c_str(), "rem ", 4)) {
strcat(i4dos_data, line.c_str());
strcat(i4dos_data, "\r\n");
}
}
}
}
VFILE_Register("4DOS.INI",(uint8_t *)i4dos_data,(uint32_t)strlen(i4dos_data), "/4DOS/");
int cp=dos.loaded_codepage;
if (!dos.loaded_codepage) InitCodePage();
initcodepagefont();
dos.loaded_codepage=cp;
}
#if (defined(WIN32) && !defined(HX_DOS) || defined(LINUX) && C_X11) && (defined(C_SDL2) || defined(SDL_DOSBOX_X_SPECIAL))
if (enableime) SetIMPosition();
#endif
}
void DOS_Shell::Run(void) {
shellrun=true;
char input_line[CMD_MAXLINE] = {0};
std::string line;
bool optP=cmd->FindStringRemain("/P",line), optC=cmd->FindStringRemainBegin("/C",line), optK=false;
if (!optC) optK=cmd->FindStringRemainBegin("/K",line);
if (optP) perm=true;
if (optC||optK) {
input_line[CMD_MAXLINE-1u] = 0;
strncpy(input_line,line.c_str(),CMD_MAXLINE-1u);
char* sep = strpbrk(input_line,"\r\n"); //GTA installer
if (sep) *sep = 0;
DOS_Shell temp;
temp.echo = echo;
temp.exec=true;
temp.ParseLine(input_line); //for *.exe *.com |*.bat creates the bf needed by runinternal;
temp.RunInternal(); // exits when no bf is found.
temp.exec=false;
if (!optK||(!perm&&temp.exit)) {
shellrun=false;
return;
}
} else if (cmd->FindStringRemain("/?",line)) {
WriteOut(MSG_Get("SHELL_CMD_COMMAND_HELP"));
shellrun=false;
return;
}
bool optInit=cmd->FindString("/INIT",line,true);
if (this != first_shell && !optInit)
WriteOut(optK?"\n":"DOSBox-X command shell [Version %s %s]\nCopyright DOSBox-X Team. All rights reserved.\n\n",VERSION,SDL_STRING);
if(optInit) {
input_line[CMD_MAXLINE - 1u] = 0;
strncpy(input_line, line.c_str(), CMD_MAXLINE - 1u);
line.erase();
ParseLine(input_line);
}
if (!exit) {
RunningProgram = "COMMAND";
GFX_SetTitle(-1,-1,-1,false);
}
do {
/* Get command once a line */
if (bf) {
if (bf->ReadLine(input_line)) {
if (echo) {
if (input_line[0]!='@') {
ShowPrompt();
WriteOut_NoParsing(input_line);
WriteOut_NoParsing("\n");
}
}
} else input_line[0]='\0';
} else {
if (optInit && control->opt_exit) break;
if (echo) ShowPrompt();
InputCommand(input_line);
if (echo && !input_eof) WriteOut("\n");
/* Bugfix: CTTY NUL will return immediately, the shell input will return
* immediately, and if we don't consume CPU cycles to compensate,
* will leave DOSBox-X running in an endless loop, hung. */
if (input_eof) CALLBACK_Idle();
}
/* do it */
if(strlen(input_line)!=0) {
ParseLine(input_line);
if (echo && !bf) WriteOut_NoParsing("\n");
}
} while (perm||!exit);
shellrun=false;
}
void DOS_Shell::SyntaxError(void) {
WriteOut(MSG_Get("SHELL_SYNTAXERROR"));
}
bool filename_not_8x3(const char *n), isDBCSCP(), isKanji1(uint8_t chr), shiftjis_lead_byte(int c);
class AUTOEXEC:public Module_base {
private:
AutoexecObject autoexec[17];
AutoexecObject autoexec_echo;
AutoexecObject autoexec_auto_bat;
public:
void RunAdditional() {
force_conversion = true;
int cp=dos.loaded_codepage;
InitCodePage();
force_conversion = false;
int ind=0;
/* The user may have given .BAT files to run on the command line */
if (!control->auto_bat_additional.empty()) {
std::string cmd = "@echo off\n";
for (unsigned int i=0;i<control->auto_bat_additional.size();i++) {
if (!control->opt_prerun) cmd += "\n";
if (!strncmp(control->auto_bat_additional[i].c_str(), "@mount c: ", 10)) {
cmd += control->auto_bat_additional[i]+"\n";
cmd += "@config -get lastmount>nul\n";
cmd += "@if not '%CONFIG%'=='' %CONFIG%";
} else {
std::string batname;
//LOG_MSG("auto_bat_additional %s\n", control->auto_bat_additional[i].c_str());
std::replace(control->auto_bat_additional[i].begin(),control->auto_bat_additional[i].end(),'/','\\');
size_t pos = std::string::npos;
bool lead = false;
for (unsigned int j=0; j<control->auto_bat_additional[i].size(); j++) {
if (lead) lead = false;
else if ((IS_PC98_ARCH && shiftjis_lead_byte(control->auto_bat_additional[i][j])) || (isDBCSCP() && isKanji1(control->auto_bat_additional[i][j]))) lead = true;
else if (control->auto_bat_additional[i][j]=='\\') pos = j;
}
if(pos == std::string::npos) { //Only a filename, mount current directory
batname = control->auto_bat_additional[i];
cmd += "@mount c: . -nl -q\n";
} else { //Parse the path of .BAT file
std::string batpath = control->auto_bat_additional[i].substr(0,pos+1);
if (batpath==".\\") batpath=".";
else if (batpath=="..\\") batpath="..";
batname = control->auto_bat_additional[i].substr(pos+1);
cmd += "@mount c: \"" + batpath + "\" -nl -q\n";
}
std::string opt = control->opt_o.size() > ind && control->opt_o[ind].size() ? " "+control->opt_o[ind] : "";
ind++;
bool templfn=!uselfn&&filename_not_8x3(batname.c_str())&&(enablelfn==-1||enablelfn==-2);
cmd += "@config -get lastmount>nul\n";
cmd += "@set LASTMOUNT=%CONFIG%\n";
cmd += "@if not '%LASTMOUNT%'=='' %LASTMOUNT%\n";
cmd += "@cd \\\n";
if (templfn) cmd += "@config -set lfn=true\n";
#if defined(WIN32) && !defined(HX_DOS)
if (!winautorun) cmd += "@config -set startcmd=true\n";
#endif
cmd += "@CALL \"";
cmd += batname;
cmd += "\"" + opt + "\n";
if (templfn) cmd += "@config -set lfn=" + std::string(enablelfn==-1?"auto":"autostart") + "\n";
#if defined(WIN32) && !defined(HX_DOS)
if (!winautorun) cmd += "@config -set startcmd=false\n";
#endif
cmd += "@if not '%LASTMOUNT%'=='' mount %LASTMOUNT% -q -u\n";
cmd += "@set LASTMOUNT=";
}
if (control->opt_prerun) cmd += "\n";
}
autoexec_auto_bat.Install(cmd);
}
dos.loaded_codepage = cp;
}
AUTOEXEC(Section* configuration):Module_base(configuration) {
/* Register a virtual AUTOEXEC.BAT file */
const Section_line * section=static_cast<Section_line *>(configuration);
/* Check -securemode switch to disable mount/imgmount/boot after running autoexec.bat */
bool secure = control->opt_securemode;
if (control->opt_prerun) RunAdditional();
/* add stuff from the configfile unless -noautexec or -securemode is specified. */
const char * extra = section->data.c_str();
if (extra && !secure && !control->opt_noautoexec) {
/* detect if "echo off" is the first line */
size_t firstline_length = strcspn(extra,"\r\n");
bool echo_off = !strncasecmp(extra,"echo off",8);
if (echo_off && firstline_length == 8) extra += 8;
else {
echo_off = !strncasecmp(extra,"@echo off",9);
if (echo_off && firstline_length == 9) extra += 9;
else echo_off = false;
}
/* if "echo off" move it to the front of autoexec.bat */
if (echo_off) {
autoexec_echo.InstallBefore("@echo off");
if (*extra == '\r') extra++; //It can point to \0
if (*extra == '\n') extra++; //same
}
/* Install the stuff from the configfile if anything left after moving echo off */
if (*extra) autoexec[0].Install(std::string(extra));
}
/* Check to see for extra command line options to be added (before the command specified on commandline) */
/* Maximum of extra commands: 10 */
Bitu i = 1;
for (auto it=control->opt_c.begin();i <= 11 && it!=control->opt_c.end();it++) /* -c switches */
autoexec[i++].Install(*it);
/* Check for the -exit switch which causes dosbox to when the command on the commandline has finished */
bool addexit = control->opt_exit;
if (!control->opt_prerun) RunAdditional();
#if 0/*FIXME: This is ugly. I don't care to follow through on this nonsense for now. When needed, port to new command line switching. */
/* Check for first command being a directory or file */
char buffer[CROSS_LEN+1];
char orig[CROSS_LEN+1];
char cross_filesplit[2] = {CROSS_FILESPLIT , 0};
Bitu dummy = 1;
bool command_found = false;
while (control->cmdline->FindCommand(dummy++,line) && !command_found) {
struct stat test;
if (line.length() > CROSS_LEN) continue;
strcpy(buffer,line.c_str());
if (stat(buffer,&test)) {
if (getcwd(buffer,CROSS_LEN) == NULL) continue;
if (strlen(buffer) + line.length() + 1 > CROSS_LEN) continue;
strcat(buffer,cross_filesplit);
strcat(buffer,line.c_str());
if (stat(buffer,&test)) continue;
}
if (test.st_mode & S_IFDIR) {
autoexec[12].Install(std::string("MOUNT C \"") + buffer + "\"");
autoexec[13].Install("C:");
if(secure) autoexec[14].Install("z:\\system\\config.com -securemode");
command_found = true;
} else {
char* name = strrchr(buffer,CROSS_FILESPLIT);
if (!name) { //Only a filename
line = buffer;
if (getcwd(buffer,CROSS_LEN) == NULL) continue;
if (strlen(buffer) + line.length() + 1 > CROSS_LEN) continue;
strcat(buffer,cross_filesplit);
strcat(buffer,line.c_str());
if(stat(buffer,&test)) continue;
name = strrchr(buffer,CROSS_FILESPLIT);
if(!name) continue;
}
*name++ = 0;
if (access(buffer,F_OK)) continue;
autoexec[12].Install(std::string("MOUNT C \"") + buffer + "\"");
autoexec[13].Install("C:");
/* Save the non-modified filename (so boot and imgmount can use it (long filenames, case sensivitive)) */
strcpy(orig,name);
upcase(name);
if(strstr(name,".BAT") != 0) {
if(secure) autoexec[14].Install("z:\\system\\config.com -securemode");
/* BATch files are called else exit will not work */
autoexec[15].Install(std::string("CALL ") + name);
if(addexit) autoexec[16].Install("exit");
} else if((strstr(name,".IMG") != 0) || (strstr(name,".IMA") !=0 )) {
//No secure mode here as boot is destructive and enabling securemode disables boot
/* Boot image files */
autoexec[15].Install(std::string("BOOT ") + orig);
} else if((strstr(name,".ISO") != 0) || (strstr(name,".CUE") !=0 )) {
/* imgmount CD image files */
/* securemode gets a different number from the previous branches! */
autoexec[14].Install(std::string("IMGMOUNT D \"") + orig + std::string("\" -t iso"));
//autoexec[16].Install("D:");
if(secure) autoexec[15].Install("z:\\system\\config.com -securemode");
/* Makes no sense to exit here */
} else {
if(secure) autoexec[14].Install("z:\\system\\config.com -securemode");
autoexec[15].Install(name);
if(addexit) autoexec[16].Install("exit");
}
command_found = true;
}
}
/* Combining -securemode, noautoexec and no parameters leaves you with a lovely Z:\. */
if ( !command_found ) {
if ( secure ) autoexec[12].Install("z:\\system\\config.com -securemode");
}
#else
if (secure) autoexec[i++].Install("z:\\system\\config.com -securemode");
#endif
if (addexit) autoexec[i++].Install("exit");
assert(i <= 17); /* FIXME: autoexec[] should not be fixed size */
VFILE_Register("AUTOEXEC.BAT",(uint8_t *)autoexec_data,(uint32_t)strlen(autoexec_data));
}
};
static AUTOEXEC* test = NULL;
static void AUTOEXEC_ShutDown(Section * sec) {
(void)sec;//UNUSED
if (test != NULL) {
delete test;
test = NULL;
}
if (first_shell != NULL) {
delete first_shell;
first_shell = 0;//Make clear that it shouldn't be used anymore
}
if (call_shellstop != 0) {
CALLBACK_DeAllocate(call_shellstop);
call_shellstop = 0;
}
}
void AUTOEXEC_Startup(Section *sec) {
(void)sec;//UNUSED
if (test == NULL) {
LOG(LOG_MISC,LOG_DEBUG)("Allocating AUTOEXEC.BAT emulation");
test = new AUTOEXEC(control->GetSection("autoexec"));
}
}
void AUTOEXEC_Init() {
LOG(LOG_MISC,LOG_DEBUG)("Initializing AUTOEXEC.BAT emulation");
AddExitFunction(AddExitFunctionFuncPair(AUTOEXEC_ShutDown));
AddVMEventFunction(VM_EVENT_RESET,AddVMEventFunctionFuncPair(AUTOEXEC_ShutDown));
AddVMEventFunction(VM_EVENT_DOS_EXIT_BEGIN,AddVMEventFunctionFuncPair(AUTOEXEC_ShutDown));
AddVMEventFunction(VM_EVENT_DOS_EXIT_REBOOT_BEGIN,AddVMEventFunctionFuncPair(AUTOEXEC_ShutDown));
AddVMEventFunction(VM_EVENT_DOS_SURPRISE_REBOOT,AddVMEventFunctionFuncPair(AUTOEXEC_ShutDown));
}
static Bitu INT2E_Handler(void) {
/* Save return address and current process */
RealPt save_ret=real_readd(SegValue(ss),reg_sp);
uint16_t save_psp=dos.psp();
/* Set first shell as process and copy command */
dos.psp(shell_psp);//DOS_FIRST_SHELL);
DOS_PSP psp(shell_psp);//DOS_FIRST_SHELL);
psp.SetCommandTail(RealMakeSeg(ds,reg_si));
SegSet16(ss,RealSeg(psp.GetStack()));
reg_sp=2046;
/* Read and fix up command string */
CommandTail tail;
MEM_BlockRead(PhysMake(dos.psp(),CTBUF+1),&tail,CTBUF+1);
if (tail.count<CTBUF) tail.buffer[tail.count]=0;
else tail.buffer[CTBUF-1]=0;
char* crlf=strpbrk(tail.buffer,"\r\n");
if (crlf) *crlf=0;
/* Execute command */
if (strlen(tail.buffer)) {
DOS_Shell temp;
temp.ParseLine(tail.buffer);
temp.RunInternal();
}
/* Restore process and "return" to caller */
dos.psp(save_psp);
SegSet16(cs,RealSeg(save_ret));
reg_ip=RealOff(save_ret);
reg_ax=0;
return CBRET_NONE;
}
/* TODO: Why is all this DOS kernel and VFILE registration here in SHELL_Init()?
* That's like claiming that DOS memory and device initialization happens from COMMAND.COM!
* We need to move the DOS kernel initialization into another function, and the VFILE
* registration to another function, and then message initialization to another function,
* and then those functions need to be called before SHELL_Init() -J.C. */
void SHELL_Init() {
LOG(LOG_MISC,LOG_DEBUG)("Initializing DOS shell");
/* Add messages */
MSG_Add("SHELL_CMD_TREE_ERROR", "No subdirectories exist\n");
MSG_Add("SHELL_CMD_VOL_TREE", "Directory PATH listing for Volume %s\n");
MSG_Add("SHELL_CMD_VOL_DRIVE","\n Volume in drive %c ");
MSG_Add("SHELL_CMD_VOL_SERIAL"," Volume Serial Number is ");
MSG_Add("SHELL_CMD_VOL_SERIAL_NOLABEL","has no label\n");
MSG_Add("SHELL_CMD_VOL_SERIAL_LABEL","is %s\n");
MSG_Add("SHELL_ILLEGAL_PATH","Path not found\n");
MSG_Add("SHELL_ILLEGAL_DRIVE","Invalid drive specification\n");
MSG_Add("SHELL_CMD_HELP","If you want a list of all supported internal commands type \033[33;1mHELP /ALL\033[0m.\nYou can also find external commands on the Z: drive as programs.\nA short list of the most often used commands:\n");
MSG_Add("SHELL_CMD_HELP_END1","External commands such as \033[33;1mMOUNT\033[0m and \033[33;1mIMGMOUNT\033[0m can be found on the Z: drive.\n");
MSG_Add("SHELL_CMD_HELP_END2","Type \033[33;1mHELP command\033[0m or \033[33;1mcommand /?\033[0m for help information for the specified command.\n");
MSG_Add("SHELL_CMD_ECHO_ON","ECHO is on.\n");
MSG_Add("SHELL_CMD_ECHO_OFF","ECHO is off.\n");
MSG_Add("SHELL_ILLEGAL_SWITCH","Invalid switch - %s\n");
MSG_Add("SHELL_INVALID_PARAMETER","Invalid parameter - %s\n");
MSG_Add("SHELL_MISSING_PARAMETER","Required parameter missing.\n");
MSG_Add("SHELL_MISSING_FILE","The following file is missing or corrupted: %s\n");
MSG_Add("SHELL_CMD_CHDIR_ERROR","Invalid directory - %s\n");
MSG_Add("SHELL_CMD_CHDIR_HINT","Hint: To change to different drive type \033[31m%c:\033[0m\n");
MSG_Add("SHELL_CMD_CHDIR_HINT_2","directoryname contains unquoted spaces.\nTry \033[31mcd %s\033[0m or properly quote them with quotation marks.\n");
MSG_Add("SHELL_CMD_CHDIR_HINT_3","You are still on drive Z:, and the specified directory cannot be found.\nFor accessing a mounted drive, change to the drive with a syntax like \033[31mC:\033[0m.\n");
MSG_Add("SHELL_CMD_DATE_HELP","Displays or changes the internal date.\n");
MSG_Add("SHELL_CMD_DATE_ERROR","The specified date is not correct.\n");
MSG_Add("SHELL_CMD_DATE_DAYS","3SunMonTueWedThuFriSat"); // "2SoMoDiMiDoFrSa"
MSG_Add("SHELL_CMD_DATE_NOW","Current date: ");
MSG_Add("SHELL_CMD_DATE_SETHLP","Type 'date %s' to change.\n");
MSG_Add("SHELL_CMD_DATE_HELP_LONG","DATE [[/T] [/H] [/S] | date]\n"\
" date: New date to set\n"\
" /S: Permanently use host time and date as DOS time\n"\
" /F: Switch back to DOSBox-X internal time (opposite of /S)\n"\
" /T: Only display date\n"\
" /H: Synchronize with host\n");
MSG_Add("SHELL_CMD_TIME_HELP","Displays or changes the internal time.\n");
MSG_Add("SHELL_CMD_TIME_ERROR","The specified time is not correct.\n");
MSG_Add("SHELL_CMD_TIME_NOW","Current time: ");
MSG_Add("SHELL_CMD_TIME_SETHLP","Type 'time %s' to change.\n");
MSG_Add("SHELL_CMD_TIME_HELP_LONG","TIME [[/T] [/H] | time]\n"\
" time: New time to set\n"\
" /T: Display simple time\n"\
" /H: Synchronize with host\n");
MSG_Add("SHELL_CMD_MKDIR_EXIST","Directory already exists - %s\n");
MSG_Add("SHELL_CMD_MKDIR_ERROR","Unable to create directory - %s\n");
MSG_Add("SHELL_CMD_RMDIR_ERROR","Invalid path, not directory, or directory not empty - %s\n");
MSG_Add("SHELL_CMD_RENAME_ERROR","Unable to rename - %s\n");
MSG_Add("SHELL_CMD_ATTRIB_GET_ERROR","Unable to get attributes: %s\n");
MSG_Add("SHELL_CMD_ATTRIB_SET_ERROR","Unable to set attributes: %s\n");
MSG_Add("SHELL_CMD_DEL_ERROR","Unable to delete - %s\n");
MSG_Add("SHELL_CMD_DEL_SURE","All files in directory will be deleted!\nAre you sure [Y/N]?");
MSG_Add("SHELL_SYNTAXERROR","Syntax error\n");
MSG_Add("SHELL_CMD_SET_NOT_SET","Environment variable %s not defined.\n");
MSG_Add("SHELL_CMD_SET_OUT_OF_SPACE","Not enough environment space left.\n");
MSG_Add("SHELL_CMD_IF_EXIST_MISSING_FILENAME","IF EXIST: Missing filename.\n");
MSG_Add("SHELL_CMD_IF_ERRORLEVEL_MISSING_NUMBER","IF ERRORLEVEL: Missing number.\n");
MSG_Add("SHELL_CMD_IF_ERRORLEVEL_INVALID_NUMBER","IF ERRORLEVEL: Invalid number.\n");
MSG_Add("SHELL_CMD_GOTO_MISSING_LABEL","No label supplied to GOTO command.\n");
MSG_Add("SHELL_CMD_GOTO_LABEL_NOT_FOUND","GOTO: Label %s not found.\n");
MSG_Add("SHELL_CMD_FILE_ACCESS_DENIED","Access denied - %s\n");
MSG_Add("SHELL_CMD_FILE_NOT_FOUND","File not found - %s\n");
MSG_Add("SHELL_CMD_FILE_EXISTS","File %s already exists.\n");
MSG_Add("SHELL_CMD_DIR_INTRO"," Directory of %s\n\n");
MSG_Add("SHELL_CMD_DIR_BYTES_USED","%5d File(s) %17s Bytes\n");
MSG_Add("SHELL_CMD_DIR_BYTES_FREE","%5d Dir(s) %17s Bytes free\n");
MSG_Add("SHELL_CMD_DIR_FILES_LISTED","Total files listed:\n");
MSG_Add("SHELL_EXECUTE_DRIVE_NOT_FOUND","Drive %c does not exist!\nYou must \033[31mmount\033[0m it first. Type \033[1;33mintro\033[0m or \033[1;33mintro mount\033[0m for more information.\n");
MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_CDROM","Do you want to give DOSBox-X access to your real CD-ROM drive %c [Y/N]?");
MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_FLOPPY","Do you want to give DOSBox-X access to your real floppy drive %c [Y/N]?");
MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_REMOVABLE","Do you want to give DOSBox-X access to your real removable drive %c [Y/N]?");
MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_NETWORK","Do you want to give DOSBox-X access to your real network drive %c [Y/N]?");
MSG_Add("SHELL_EXECUTE_DRIVE_ACCESS_FIXED","Do you really want to give DOSBox-X access to your real hard drive %c [Y/N]?");
MSG_Add("SHELL_EXECUTE_ILLEGAL_COMMAND","Bad command or filename - \"%s\"\n");
MSG_Add("SHELL_CMD_PAUSE","Press any key to continue . . .\n");
MSG_Add("SHELL_CMD_PAUSE_HELP","Waits for one keystroke to continue.\n");
MSG_Add("SHELL_CMD_PAUSE_HELP_LONG","PAUSE\n");
MSG_Add("SHELL_CMD_COPY_FAILURE","Copy failure - %s\n");
MSG_Add("SHELL_CMD_COPY_SUCCESS"," %d File(s) copied.\n");
MSG_Add("SHELL_CMD_COPY_CONFIRM","Overwrite %s (Yes/No/All)?");
MSG_Add("SHELL_CMD_COPY_NOSPACE","Insufficient disk space - %s\n");
MSG_Add("SHELL_CMD_COPY_ERROR","Copy error - %s\n");
MSG_Add("SHELL_CMD_SUBST_DRIVE_LIST","The currently mounted local drives are:\n");
MSG_Add("SHELL_CMD_SUBST_NO_REMOVE","Unable to remove, drive not in use.\n");
MSG_Add("SHELL_CMD_SUBST_IN_USE","Target drive is already in use.\n");
MSG_Add("SHELL_CMD_SUBST_NOT_LOCAL","It is only possible to use SUBST on local drives.\n");
MSG_Add("SHELL_CMD_SUBST_INVALID_PATH","The specified drive or path is invalid.\n");
MSG_Add("SHELL_CMD_SUBST_FAILURE","SUBST: There is an error in your command line.\n");
MSG_Add("SHELL_CMD_VTEXT_ON","DOS/V V-text is currently enabled.\n");
MSG_Add("SHELL_CMD_VTEXT_OFF","DOS/V V-text is currently disabled.\n");
std::string mapper_keybind = mapper_event_keybind_string("host");
if (mapper_keybind.empty()) mapper_keybind = "unbound";
/* Capitalize the binding */
if (mapper_keybind.size() > 0)
mapper_keybind[0] = toupper(mapper_keybind[0]);
std::string default_host =
#if defined(WIN32) && !defined(HX_DOS)
"F11"
#else
"F12"
#endif
;
/* Punctuation is important too. */
//mapper_keybind += ".";
/* NTS: MSG_Add() takes the string as const char * but it does make a copy of the string when entering into the message map,
* so there is no problem here of causing use-after-free crashes when we exit. */
std::string host_key_help; // SHELL_STARTUP_BEGIN2
if (machine == MCH_PC98) {
// "\x86\x46 To activate the keymapper \033[31mhost+M\033[37m. Host key is F12. \x86\x46\n"
}
else {
// "\xBA To activate the keymapper \033[31mhost+M\033[37m. Host key is F12. \xBA\n"
}
MSG_Add("SHELL_STARTUP_TITLE", "Welcome to DOSBox-X !");
MSG_Add("SHELL_STARTUP_HEAD1_PC98", "\033[36mGetting Started with DOSBox-X:\033[37m ");
MSG_Add("SHELL_STARTUP_TEXT1_PC98", "Type \033[32mHELP\033[37m for shell commands, and \033[32mINTRO\033[37m for a short introduction. \nYou could also complete various tasks through the \033[33mdrop-down menus\033[37m.");
MSG_Add("SHELL_STARTUP_EXAMPLE_PC98", "\033[32mExample\033[37m: Try select \033[33mTrueType font\033[37m or \033[33mOpenGL perfect\033[37m output option.");
MSG_Add("SHELL_STARTUP_TEXT2_PC98", (std::string("To launch the \033[33mConfiguration Tool\033[37m, use \033[31mhost+C\033[37m. Host key is \033[32m") + (mapper_keybind + "\033[37m. ").substr(0,13) + std::string("\nTo activate the \033[33mMapper Editor\033[37m for key assignments, use \033[31mhost+M\033[37m. \nTo switch between windowed and full-screen mode, use \033[31mhost+F\033[37m. \nTo adjust the emulated CPU speed, use \033[31mhost+Plus\033[37m and \033[31mhost+Minus\033[37m. ")).c_str());
MSG_Add("SHELL_STARTUP_INFO_PC98","\033[36mDOSBox-X is now running in \033[32mJapanese NEC PC-98\033[36m emulation mode.\033[37m ");
MSG_Add("SHELL_STARTUP_TEXT3_PC98", "\033[32mDOSBox-X project \033[33mhttps://dosbox-x.com/ \033[36mComplete DOS emulations\033[37m\n\033[32mDOSBox-X guide \033[33mhttps://dosbox-x.com/wiki\033[37m \033[36mDOS, Windows 3.x and 9x\033[37m\n\033[32mDOSBox-X support \033[33mhttps://github.com/joncampbell123/dosbox-x/issues\033[37m");
MSG_Add("SHELL_STARTUP_HEAD1", "\033[36mGetting started with DOSBox-X: \033[37m");
MSG_Add("SHELL_STARTUP_TEXT1", "Type \033[32mHELP\033[37m to see the list of shell commands, \033[32mINTRO\033[37m for a brief introduction.\nYou can also complete various tasks in DOSBox-X through the \033[33mdrop-down menus\033[37m.");
MSG_Add("SHELL_STARTUP_EXAMPLE", "\033[32mExample\033[37m: Try select the \033[33mTrueType font\033[37m or \033[33mOpenGL pixel-perfect\033[37m output option.");
MSG_Add("SHELL_STARTUP_HEAD2", "\033[36mUseful default shortcuts: \033[37m");
MSG_Add("SHELL_STARTUP_TEXT2", (std::string("- switch between windowed and full-screen mode with key combination \033[31m")+(default_host+" \033[37m+ \033[31mF\033[37m ").substr(0,23)+std::string("\033[37m\n") +
std::string("- launch \033[33mConfiguration Tool\033[37m using \033[31m")+(default_host+" \033[37m+ \033[31mC\033[37m ").substr(0,22)+std::string("\033[37m, and \033[33mMapper Editor\033[37m using \033[31m")+(default_host+" \033[37m+ \033[31mM\033[37m ").substr(0,24)+std::string("\033[37m\n") +
std::string("- increase or decrease the emulation speed with \033[31m")+(default_host+" \033[37m+ \033[31mPlus\033[37m ").substr(0,25)+std::string("\033[37m or \033[31m") +
(default_host+" \033[37m+ \033[31mMinus\033[37m ").substr(0,29)+std::string("\033[37m")).c_str());
MSG_Add("SHELL_STARTUP_DOSV","\033[32mDOS/V mode\033[37m is now active. Try also \033[32mTTF CJK mode\033[37m for a general DOS emulation.");
MSG_Add("SHELL_STARTUP_CGA", "Composite CGA mode is supported. Use \033[31mCtrl+F8\033[37m to set composite output ON/OFF.\nUse \033[31mCtrl+Shift+[F7/F8]\033[37m to change hue; \033[31mCtrl+F7\033[37m selects early/late CGA model. ");
MSG_Add("SHELL_STARTUP_CGA_MONO","Use \033[31mCtrl+F7\033[37m to cycle through green, amber, and white monochrome color, \nand \033[31mCtrl+F8\033[37m to change contrast/brightness settings. ");
MSG_Add("SHELL_STARTUP_HERC","Use \033[31mCtrl+F7\033[37m to cycle through white, amber, and green monochrome color. \nUse \033[31mCtrl+F8\033[37m to toggle horizontal blending (only in graphics mode). ");
MSG_Add("SHELL_STARTUP_HEAD3", "\033[36mDOSBox-X project on the web: \033[37m");
MSG_Add("SHELL_STARTUP_TEXT3", "\033[32mHomepage of project\033[37m: \033[33mhttps://dosbox-x.com/ \033[36mComplete DOS emulations\033[37m\n\033[32mUser guides on Wiki\033[37m: \033[33mhttps://dosbox-x.com/wiki\033[32m \033[36mDOS, Windows 3.x and 9x\033[37m\n\033[32mIssue or suggestion\033[37m: \033[33mhttps://github.com/joncampbell123/dosbox-x/issues \033[37m");
MSG_Add("SHELL_STARTUP_LAST", "HAVE FUN WITH DOSBox-X !");
MSG_Add("SHELL_CMD_BREAK_HELP","Sets or clears extended CTRL+C checking.\n");
MSG_Add("SHELL_CMD_BREAK_HELP_LONG","BREAK [ON | OFF]\n\nType BREAK without a parameter to display the current BREAK setting.\n");
MSG_Add("SHELL_CMD_CHDIR_HELP","Displays or changes the current directory.\n");
MSG_Add("SHELL_CMD_CHDIR_HELP_LONG","CHDIR [drive:][path]\n"
"CHDIR [..]\n"
"CD [drive:][path]\n"
"CD [..]\n\n"
" .. Specifies that you want to change to the parent directory.\n\n"
"Type CD drive: to display the current directory in the specified drive.\n"
"Type CD without parameters to display the current drive and directory.\n");
MSG_Add("SHELL_CMD_CLS_HELP","Clears screen.\n");
MSG_Add("SHELL_CMD_CLS_HELP_LONG","CLS\n");
MSG_Add("SHELL_CMD_DIR_HELP","Displays a list of files and subdirectories in a directory.\n");
MSG_Add("SHELL_CMD_DIR_HELP_LONG","DIR [drive:][path][filename] [/[W|B]] [/S] [/P] [/A[D|H|S|R|A]] [/O[N|E|G|S|D]]\n\n"
" [drive:][path][filename]\n"
" Specifies drive, directory, and/or files to list.\n"
" /W Uses wide list format.\n"
" /B Uses bare format (no heading information or summary).\n"
" /S Displays files in specified directory and all subdirectories.\n"
" /P Pauses after each screenful of information.\n"
" /A Displays files with specified attributes.\n"
" attributes D Directories R Read-only files\n"
" H Hidden files A Files ready for archiving\n"
" S System files - Prefix meaning not\n"
" /O List by files in sorted order.\n"
" sortorder N By name (alphabetic) S By size (smallest first)\n"
" E By extension (alphabetic) D By date & time (earliest first)\n"
" G Group directories first - Prefix to reverse order\n\n"
"Switches may be preset in the DIRCMD environment variable. Override\n"
"preset switches by prefixing any switch with - (hyphen)--for example, /-W.\n"
);
MSG_Add("SHELL_CMD_ECHO_HELP","Displays messages, or turns command-echoing on or off.\n");
MSG_Add("SHELL_CMD_ECHO_HELP_LONG"," ECHO [ON | OFF]\n ECHO [message]\n\nType ECHO without parameters to display the current echo setting.\n");
MSG_Add("SHELL_CMD_EXIT_HELP","Exits from the command shell.\n");
MSG_Add("SHELL_CMD_EXIT_HELP_LONG","EXIT\n");
MSG_Add("SHELL_CMD_HELP_HELP","Shows DOSBox-X command help.\n");
MSG_Add("SHELL_CMD_HELP_HELP_LONG","HELP [/A or /ALL]\nHELP [command]\n\n"
" /A or /ALL Lists all supported internal commands.\n"
" [command] Shows help for the specified command.\n\n"
"\033[0mE.g., \033[37;1mHELP COPY\033[0m or \033[37;1mCOPY /?\033[0m shows help information for COPY command.\n\n"
"Note: External commands like \033[33;1mMOUNT\033[0m and \033[33;1mIMGMOUNT\033[0m are not listed by HELP [/A].\n"
" These commands can be found on the Z: drive as programs (e.g. MOUNT.COM).\n"
" Type \033[33;1mcommand /?\033[0m or \033[33;1mHELP command\033[0m for help information for that command.\n");
MSG_Add("SHELL_CMD_LS_HELP","Lists directory contents.\n");
MSG_Add("SHELL_CMD_LS_HELP_LONG","LS [drive:][path][filename] [/A] [/L] [/P] [/Z]\n\n"
" /A Lists hidden and system files also.\n"
" /L Lists names one per line.\n"
" /P Pauses after each screenful of information.\n"
" /Z Displays short names even if LFN support is available.\n");
MSG_Add("SHELL_CMD_MKDIR_HELP","Creates a directory.\n");
MSG_Add("SHELL_CMD_MKDIR_HELP_LONG","MKDIR [drive:][path]\n"
"MD [drive:][path]\n");
MSG_Add("SHELL_CMD_RMDIR_HELP","Removes a directory.\n");
MSG_Add("SHELL_CMD_RMDIR_HELP_LONG","RMDIR [drive:][path]\n"
"RD [drive:][path]\n");
MSG_Add("SHELL_CMD_SET_HELP","Displays or changes environment variables.\n");
MSG_Add("SHELL_CMD_SET_HELP_LONG","SET [variable=[string]]\n\n"
" variable Specifies the environment-variable name.\n"
" string Specifies a series of characters to assign to the variable.\n\n"
"* If no string is specified, the variable is removed from the environment.\n\n"
"Type SET without parameters to display the current environment variables.\n");
MSG_Add("SHELL_CMD_IF_HELP","Performs conditional processing in batch programs.\n");
MSG_Add("SHELL_CMD_IF_HELP_LONG","IF [NOT] ERRORLEVEL number command\n"
"IF [NOT] string1==string2 command\n"
"IF [NOT] EXIST filename command\n\n"
" NOT Specifies that DOS should carry out\n"
" the command only if the condition is false.\n\n"
" ERRORLEVEL number Specifies a true condition if the last program run\n"
" returned an exit code equal to or greater than the number\n"
" specified.\n\n"
" string1==string2 Specifies a true condition if the specified text strings\n"
" match.\n\n"
" EXIST filename Specifies a true condition if the specified filename\n"
" exists.\n\n"
" command Specifies the command to carry out if the condition is\n"
" met. Command can be followed by ELSE command which\n"
" will execute the command after the ELSE keyword if the\n"
" specified condition is FALSE\n");
MSG_Add("SHELL_CMD_GOTO_HELP","Jumps to a labeled line in a batch program.\n");
MSG_Add("SHELL_CMD_GOTO_HELP_LONG","GOTO label\n\n"
" label Specifies a text string used in the batch program as a label.\n\n"
"You type a label on a line by itself, beginning with a colon.\n");
MSG_Add("SHELL_CMD_HISTORY_HELP","Displays or clears the command history list.\n");
MSG_Add("SHELL_CMD_HISTORY_HELP_LONG","HISTORY [/C]\n\n /C Clears the command history list.\n");
MSG_Add("SHELL_CMD_SHIFT_HELP","Changes the position of replaceable parameters in a batch file.\n");
MSG_Add("SHELL_CMD_SHIFT_HELP_LONG","SHIFT\n");
MSG_Add("SHELL_CMD_FOR_HELP","Runs a specified command for each file in a set of files.\n");
MSG_Add("SHELL_CMD_FOR_HELP_LONG","FOR %%variable IN (set) DO command [command-parameters]\n\n %%variable Specifies a replaceable parameter.\n (set) Specifies a set of one or more files. Wildcards may be used.\n command Specifies the command to carry out for each file.\n command-parameters\n Specifies parameters or switches for the specified command.\n\nTo use the command in a batch program, specify %%%%variable instead of %%variable.\n");
MSG_Add("SHELL_CMD_LFNFOR_HELP","Enables or disables long filenames when processing FOR wildcards.\n");
MSG_Add("SHELL_CMD_LFNFOR_HELP_LONG","LFNFOR [ON | OFF]\n\nType LFNFOR without a parameter to display the current LFNFOR setting.\n\nThis command is only useful if LFN support is currently enabled.\n");
MSG_Add("SHELL_CMD_TYPE_HELP","Displays the contents of a text file.\n");
MSG_Add("SHELL_CMD_TYPE_HELP_LONG","TYPE [drive:][path][filename]\n");
MSG_Add("SHELL_CMD_REM_HELP","Adds comments in a batch file.\n");
MSG_Add("SHELL_CMD_REM_HELP_LONG","REM [comment]\n");
MSG_Add("SHELL_CMD_RENAME_HELP","Renames a file/directory or files.\n");
MSG_Add("SHELL_CMD_RENAME_HELP_LONG","RENAME [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]\n"
"REN [drive:][path][directoryname1 | filename1] [directoryname2 | filename2]\n\n"
"Note that you can not specify a new drive or path for your destination.\n\n"
"Wildcards (* and ?) are supported for files. For example, the following command\n"
"renames all text files: \033[37;1mREN *.TXT *.BAK\033[0m\n");
MSG_Add("SHELL_CMD_DELETE_HELP","Removes one or more files.\n");
MSG_Add("SHELL_CMD_DELETE_HELP_LONG","DEL [/P] [/F] [/Q] names\n"
"ERASE [/P] [/F] [/Q] names\n\n"
" names Specifies a list of one or more files or directories.\n"
" Wildcards may be used to delete multiple files. If a\n"
" directory is specified, all files within the directory\n"
" will be deleted.\n"
" /P Prompts for confirmation before deleting one or more files.\n"
" /F Force deleting of read-only files.\n"
" /Q Quiet mode, do not ask if ok to delete on global wildcard.\n");
MSG_Add("SHELL_CMD_COPY_HELP","Copies one or more files.\n");
MSG_Add("SHELL_CMD_COPY_HELP_LONG","COPY [/Y | /-Y] source [+source [+ ...]] [destination]\n\n"
" source Specifies the file or files to be copied.\n"
" destination Specifies the directory and/or filename for the new file(s).\n"
" /Y Suppresses prompting to confirm you want to overwrite an\n"
" existing destination file.\n"
" /-Y Causes prompting to confirm you want to overwrite an\n"
" existing destination file.\n\n"
"The switch /Y may be preset in the COPYCMD environment variable.\n"
"This may be overridden with /-Y on the command line.\n\n"
"To append files, specify a single file for destination, but multiple files\n"
"for source (using wildcards or file1+file2+file3 format).\n");
MSG_Add("SHELL_CMD_CALL_HELP","Starts a batch file from within another batch file.\n");
MSG_Add("SHELL_CMD_CALL_HELP_LONG","CALL [drive:][path]filename [batch-parameters]\n\n"
"batch-parameters Specifies any command-line information required by\n"
" the batch program.\n");
MSG_Add("SHELL_CMD_SUBST_HELP","Assigns an internal directory to a drive.\n");
MSG_Add("SHELL_CMD_SUBST_HELP_LONG","SUBST [drive1: [drive2:]path]\nSUBST drive1: /D\n\n"
" drive1: Specifies a drive to which you want to assign a path.\n"
" [drive2:]path Specifies a mounted local drive and path you want to assign to.\n"
" /D Deletes a mounted or substituted drive.\n\n"
"Type SUBST with no parameters to display a list of mounted local drives.\n");
MSG_Add("SHELL_CMD_LOADHIGH_HELP","Loads a program into upper memory (requires XMS and UMB memory).\n");
MSG_Add("SHELL_CMD_LOADHIGH_HELP_LONG","LH [drive:][path]filename [parameters]\n"
"LOADHIGH [drive:][path]filename [parameters]\n");
MSG_Add("SHELL_CMD_CHOICE_HELP","Waits for a keypress and sets ERRORLEVEL.\n");
MSG_Add("SHELL_CMD_CHOICE_HELP_LONG","CHOICE [/C:choices] [/N] [/S] text\n"
" /C[:]choices - Specifies allowable keys. Default is: yn.\n"
" /N - Do not display the choices at end of prompt.\n"
" /S - Enables case-sensitive choices to be selected.\n"
" text - The text to display as a prompt.\n");
MSG_Add("SHELL_CMD_ATTRIB_HELP","Displays or changes file attributes.\n");
MSG_Add("SHELL_CMD_ATTRIB_HELP_LONG","ATTRIB [+R | -R] [+A | -A] [+S | -S] [+H | -H] [drive:][path][filename] [/S]\n\n"
" + Sets an attribute.\n"
" - Clears an attribute.\n"
" R Read-only file attribute.\n"
" A Archive file attribute.\n"
" S System file attribute.\n"
" H Hidden file attribute.\n"
" [drive:][path][filename]\n"
" Specifies file(s) or directory for ATTRIB to process.\n"
" /S Processes files in all directories in the specified path.\n");
MSG_Add("SHELL_CMD_PATH_HELP","Displays or sets a search path for executable files.\n");
MSG_Add("SHELL_CMD_PATH_HELP_LONG","PATH [[drive:]path[;...][;%PATH%]\n"
"PATH ;\n\n"
"Type PATH ; to clear all search path settings.\n"
"Type PATH without parameters to display the current path.\n");
MSG_Add("SHELL_CMD_PUSHD_HELP","Stores the current directory for use by the POPD command, then\nchanges to the specified directory.\n");
MSG_Add("SHELL_CMD_PUSHD_HELP_LONG","PUSHD [path]\n\n"
"path Specifies the directory to make the current directory.\n\n"
"Type PUSHD with no parameters to display currently stored directories.\n");
MSG_Add("SHELL_CMD_POPD_HELP","Changes to the directory stored by the PUSHD command.\n");
MSG_Add("SHELL_CMD_POPD_HELP_LONG","POPD\n");
MSG_Add("SHELL_CMD_VERIFY_HELP","Controls whether to verify files are written correctly to a disk.\n");
MSG_Add("SHELL_CMD_VERIFY_HELP_LONG","VERIFY [ON | OFF]\n\nType VERIFY without a parameter to display the current VERIFY setting.\n");
MSG_Add("SHELL_CMD_VER_HELP","Displays or sets DOSBox-X's reported DOS version.\n");
MSG_Add("SHELL_CMD_VER_HELP_LONG","VER [/R]\n"
"VER [SET] number or VER SET [major minor]\n\n"
" /R Display DOSBox-X's Git commit version and build date.\n"
" [SET] number Set the specified number as the reported DOS version.\n"
" SET [major minor] Set the reported DOS version in major and minor format.\n\n"
" \033[0mE.g., \033[37;1mVER 6.0\033[0m or \033[37;1mVER 7.1\033[0m sets the DOS version to 6.0 and 7.1, respectively.\n"
" On the other hand, \033[37;1mVER SET 7 1\033[0m sets the DOS version to 7.01 instead of 7.1.\n\n"
"Type VER without parameters to display DOSBox-X and the reported DOS version.\n");
MSG_Add("SHELL_CMD_VER_VER","DOSBox-X version %s (%s). Reported DOS version %d.%02d.\n");
MSG_Add("SHELL_CMD_VER_INVALID","The specified DOS version is not correct.\n");
MSG_Add("SHELL_CMD_VOL_HELP","Displays the disk volume label and serial number, if they exist.\n");
MSG_Add("SHELL_CMD_VOL_HELP_LONG","VOL [drive]\n");
MSG_Add("SHELL_CMD_PROMPT_HELP","Changes the command prompt.\n");
MSG_Add("SHELL_CMD_PROMPT_HELP_LONG","PROMPT [text]\n"
" text Specifies a new command prompt.\n\n"
"Prompt can be made up of normal characters and the following special codes:\n"
" $A & (Ampersand)\n"
" $B | (pipe)\n"
" $C ( (Left parenthesis)\n"
" $D Current date\n"
" $E Escape code (ASCII code 27)\n"
" $F ) (Right parenthesis)\n"
" $G > (greater-than sign)\n"
" $H Backspace (erases previous character)\n"
" $L < (less-than sign)\n"
" $N Current drive\n"
" $P Current drive and path\n"
" $Q = (equal sign)\n"
" $S (space)\n"
" $T Current time\n"
" $V DOS version number\n"
" $_ Carriage return and linefeed\n"
" $$ $ (dollar sign)\n");
MSG_Add("SHELL_CMD_ALIAS_HELP", "Defines or displays aliases.\n");
MSG_Add("SHELL_CMD_ALIAS_HELP_LONG", "ALIAS [name[=value] ... ]\n\nType ALIAS without parameters to display the list of aliases in the form:\n`ALIAS NAME = VALUE'\n");
MSG_Add("SHELL_CMD_ASSOC_HELP", "Displays or changes file extension associations.\n");
MSG_Add("SHELL_CMD_ASSOC_HELP_LONG", "ASSOC [.ext[=command] ... ]\n\nType ASSOC without parameters to display the current file associations.\nFile extensions must start with a dot (.); wildcards (* and ?) are allowed.\n");
MSG_Add("SHELL_CMD_CHCP_HELP", "Displays or changes the current DOS code page.\n");
MSG_Add("SHELL_CMD_CHCP_HELP_LONG", "CHCP [nnn [file]]\n\n nnn Specifies a code page number.\n file Specifies a code page file.\n\nSupported code pages for changing in the TrueType font output:\n\n437,737,775,808,850,852,853,855,857,858,860-866,869,872,874,3021\n\nWindows code pages: 1250,1251,1252,1253,1254,1255,1256,1257,1258\n\nAlso double-byte code pages including 932, 936, 949, and 950.\n\nCustomized code pages are supported by providing code page files.\n");
MSG_Add("SHELL_CMD_CHCP_ACTIVE", "Active code page: %d\n");
MSG_Add("SHELL_CMD_CHCP_MISSING", "ASCII characters not defined in TTF font: %d\n");
MSG_Add("SHELL_CMD_CHCP_INVALID", "Invalid code page number - %s\n");
MSG_Add("SHELL_CMD_COUNTRY_HELP", "Displays or changes the current country.\n");
MSG_Add("SHELL_CMD_COUNTRY_HELP_LONG", "COUNTRY [nnn] \n\n nnn Specifies a country code.\n\nCountry-specific information such as date and time formats will be affected.\n");
MSG_Add("SHELL_CMD_CTTY_HELP","Changes the terminal device used to control the system.\n");
MSG_Add("SHELL_CMD_CTTY_HELP_LONG","CTTY device\n device The terminal device to use, such as CON.\n");
MSG_Add("SHELL_CMD_MORE_HELP","Displays output one screen at a time.\n");
MSG_Add("SHELL_CMD_MORE_HELP_LONG","MORE [drive:][path][filename]\nMORE < [drive:][path]filename\ncommand-name | MORE [drive:][path][filename]\n");
MSG_Add("SHELL_CMD_TRUENAME_HELP","Finds the fully-expanded name for a file.\n");
MSG_Add("SHELL_CMD_TRUENAME_HELP_LONG","TRUENAME [/H] file\n");
MSG_Add("SHELL_CMD_DXCAPTURE_HELP","Runs program with video or audio capture.\n");
MSG_Add("SHELL_CMD_DXCAPTURE_HELP_LONG","DX-CAPTURE [/V|/-V] [/A|/-A] [/M|/-M] [command] [options]\n\nIt will start video or audio capture, run program, and then automatically stop capture when the program exits.\n");
#if C_DEBUG
MSG_Add("SHELL_CMD_DEBUGBOX_HELP","Runs program and breaks into debugger at entry point.\n");
MSG_Add("SHELL_CMD_DEBUGBOX_HELP_LONG","DEBUGBOX [command] [options]\n\nType DEBUGBOX without a parameter to start the debugger.\n");
#endif
MSG_Add("SHELL_CMD_COMMAND_HELP","Starts the DOSBox-X command shell.\n\nThe following options are accepted:\n\n /C Executes the specified command and returns.\n /K Executes the specified command and continues running.\n /P Loads a permanent copy of the command shell.\n /INIT Initializes the command shell.\n");
/* Regular startup */
call_shellstop=CALLBACK_Allocate();
/* Setup the startup CS:IP to kill the last running machine when exited */
RealPt newcsip=CALLBACK_RealPointer(call_shellstop);
SegSet16(cs,RealSeg(newcsip));
reg_ip=RealOff(newcsip);
CALLBACK_Setup(call_shellstop,shellstop_handler,CB_IRET,"shell stop");
/* NTS: Some DOS programs behave badly if run from a command interpreter
* who's PSP segment is too low in memory and does not appear in
* the MCB chain (SimCity 2000). So allocate shell memory normally
* as any DOS application would do.
*
* That includes allocating COMMAND.COM stack NORMALLY (not up in
* the UMB as DOSBox SVN would do) */
/* Now call up the shell for the first time */
uint16_t psp_seg;//=DOS_FIRST_SHELL;
uint16_t env_seg;//=DOS_FIRST_SHELL+19; //DOS_GetMemory(1+(4096/16))+1;
uint16_t stack_seg;//=DOS_GetMemory(2048/16,"COMMAND.COM stack");
uint16_t tmp,total_sz;
// decide shell env size
if (dosbox_shell_env_size == 0)
dosbox_shell_env_size = (0x158u - (0x118u + 19u)) << 4u; /* equivalent to mainline DOSBox */
else
dosbox_shell_env_size = (dosbox_shell_env_size+15u)&(~15u); /* round up to paragraph */
LOG_MSG("COMMAND.COM env size: %u bytes",dosbox_shell_env_size);
// According to some sources, 0x0008 is a special PSP segment value used by DOS before the first
// program is used. We need the current PSP segment to be nonzero so that DOS_AllocateMemory()
// can properly allocate memory.
dos.psp(8);
auto savedMemAllocStrategy = DOS_GetMemAllocStrategy();
auto shellHigh = std::string(static_cast<Section_prop*>(control->GetSection("dos"))->Get_string("shellhigh"));
if (shellHigh=="true" || shellHigh=="1" ||
(shellHigh=="auto" && dos.version.major >= 7))
{
DOS_SetMemAllocStrategy(savedMemAllocStrategy | 0x80);
}
// COMMAND.COM environment block
tmp = dosbox_shell_env_size>>4;
if (!DOS_AllocateMemory(&env_seg,&tmp)) E_Exit("COMMAND.COM failed to allocate environment block segment");
LOG_MSG("COMMAND.COM environment block: 0x%04x sz=0x%04x",env_seg,tmp);
// COMMAND.COM main binary (including PSP and stack)
tmp = 0x1A + (2048/16);
total_sz = tmp;
if (!DOS_AllocateMemory(&psp_seg,&tmp)) E_Exit("COMMAND.COM failed to allocate main body + PSP segment");
LOG_MSG("COMMAND.COM main body (PSP): 0x%04x sz=0x%04x",psp_seg,tmp);
DOS_SetMemAllocStrategy(savedMemAllocStrategy);
// now COMMAND.COM has a main body and PSP segment, reflect it
dos.psp(psp_seg);
shell_psp = psp_seg;
{
DOS_MCB mcb((uint16_t)(env_seg-1));
mcb.SetPSPSeg(psp_seg);
mcb.SetFileName("COMMAND");
}
{
DOS_MCB mcb((uint16_t)(psp_seg-1));
mcb.SetPSPSeg(psp_seg);
mcb.SetFileName("COMMAND");
}
// set the stack at 0x1A
stack_seg = psp_seg + 0x1A;
LOG_MSG("COMMAND.COM stack: 0x%04x",stack_seg);
// set the stack pointer
SegSet16(ss,stack_seg);
reg_sp=2046;
/* Set up int 24 and psp (Telarium games) */
real_writeb(psp_seg+16+1,0,0xea); /* far jmp */
real_writed(psp_seg+16+1,1,real_readd(0,0x24*4));
real_writed(0,0x24*4,((uint32_t)psp_seg<<16) | ((16+1)<<4));
/* Set up int 23 to "int 20" in the psp. Fixes what.exe */
real_writed(0,0x23*4,((uint32_t)psp_seg<<16));
/* Set up int 2e handler */
if (call_int2e == 0)
call_int2e = CALLBACK_Allocate();
// RealPt addr_int2e=RealMake(psp_seg+16+1,8);
// NTS: It's apparently common practice to enumerate MCBs by reading the segment value of INT 2Eh and then
// scanning forward from there. The assumption seems to be that COMMAND.COM writes INT 2Eh there using
// it's PSP segment and an offset like that of a COM executable even though COMMAND.COM is often an EXE file.
RealPt addr_int2e=RealMake(psp_seg,8+((16+1)*16));
CALLBACK_Setup(call_int2e,&INT2E_Handler,CB_IRET_STI,Real2Phys(addr_int2e),"Shell Int 2e");
RealSetVec(0x2e,addr_int2e);
/* Setup environment */
PhysPt env_write=PhysMake(env_seg,0);
MEM_BlockWrite(env_write,path_string,(Bitu)(strlen(path_string)+1));
env_write += (PhysPt)(strlen(path_string)+1);
MEM_BlockWrite(env_write,comspec_string,(Bitu)(strlen(comspec_string)+1));
env_write += (PhysPt)(strlen(comspec_string)+1);
MEM_BlockWrite(env_write,prompt_string,(Bitu)(strlen(prompt_string)+1));
env_write +=(PhysPt)(strlen(prompt_string)+1);
mem_writeb(env_write++,0);
mem_writew(env_write,1);
env_write+=2;
MEM_BlockWrite(env_write,full_name,(Bitu)(strlen(full_name)+1));
// extern bool Mouse_Vertical;
extern bool Mouse_Drv;
Mouse_Drv = true;
DOS_PSP psp(psp_seg);
psp.MakeNew(0);
dos.psp(psp_seg);
/* The start of the filetable in the psp must look like this:
* 01 01 01 00 02
* In order to achieve this: First open 2 files. Close the first and
* duplicate the second (so the entries get 01) */
uint16_t dummy=0;
DOS_OpenFile("CON",OPEN_READWRITE,&dummy); /* STDIN */
DOS_OpenFile("CON",OPEN_READWRITE,&dummy); /* STDOUT */
DOS_CloseFile(0); /* Close STDIN */
DOS_ForceDuplicateEntry(1,0); /* "new" STDIN */
DOS_ForceDuplicateEntry(1,2); /* STDERR */
DOS_OpenFile("CON",OPEN_READWRITE,&dummy); /* STDAUX */
if (!DOS_OpenFile("PRN",OPEN_READWRITE,&dummy)) DOS_OpenFile("CON",OPEN_READWRITE,&dummy); /* STDPRN */
psp.SetSize(psp_seg + total_sz);
psp.SetStack(((unsigned int)stack_seg << 16u) + (unsigned int)reg_sp);
/* Create appearance of handle inheritance by first shell */
for (uint16_t i=0;i<5;i++) {
uint8_t handle=psp.GetFileHandle(i);
if (Files[handle]) Files[handle]->AddRef();
}
psp.SetParent(psp_seg);
/* Set the environment */
psp.SetEnvironment(env_seg);
/* Set the command line for the shell start up */
CommandTail tail;
tail.count=(uint8_t)strlen(init_line);
memset(&tail.buffer, 0, CTBUF);
strncpy(tail.buffer,init_line,CTBUF);
MEM_BlockWrite(PhysMake(psp_seg,CTBUF+1),&tail,CTBUF+1);
/* Setup internal DOS Variables */
dos.dta(RealMake(psp_seg,CTBUF+1));
dos.psp(psp_seg);
}
/* Pfff... starting and running the shell from a configuration section INIT
* What the hell were you guys thinking? --J.C. */
void SHELL_Run() {
dos_shell_running_program = false;
#if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU
Reflect_Menu();
#endif
LOG(LOG_MISC,LOG_DEBUG)("Running DOS shell now");
if (first_shell != NULL) E_Exit("Attempt to start shell when shell already running");
Section_prop *section = static_cast<Section_prop *>(control->GetSection("config"));
bool altshell=false;
char namestr[CROSS_LEN], tmpstr[CROSS_LEN], *name=namestr, *tmp=tmpstr;
SHELL_ProgramStart_First_shell(&first_shell);
first_shell->Prepare();
prepared = true;
if (section!=NULL&&!control->opt_noconfig&&!control->opt_securemode&&!control->SecureMode()) {
char *shell = (char *)section->Get_string("shell");
if (strlen(shell)) {
tmp=trim(shell);
name=StripArg(tmp);
upcase(name);
if (*name&&(DOS_FileExists(name)||DOS_FileExists((std::string("Z:\\SYSTEM\\")+name).c_str())||DOS_FileExists((std::string("Z:\\BIN\\")+name).c_str())||DOS_FileExists((std::string("Z:\\DOS\\")+name).c_str())||DOS_FileExists((std::string("Z:\\4DOS\\")+name).c_str())||DOS_FileExists((std::string("Z:\\DEBUG\\")+name).c_str())||DOS_FileExists((std::string("Z:\\TEXTUTIL\\")+name).c_str()))) {
strreplace(name,'/','\\');
altshell=true;
} else if (*name)
first_shell->WriteOut(MSG_Get("SHELL_MISSING_FILE"), name);
}
}
#if C_DEBUG
if (control->opt_test) {
RUN_ALL_TESTS();
#if defined(WIN32)
DOSBox_ConsolePauseWait();
#endif
return;
}
#endif
i4dos=false;
if (altshell) {
if (strstr(name, "4DOS.COM")) i4dos=true;
first_shell->SetEnv("COMSPEC",name);
if (!strlen(tmp)) {
char *p=strrchr(name, '\\');
if (!strcasecmp(p==NULL?name:p+1, "COMMAND.COM") || !strcasecmp(name, "Z:COMMAND.COM")) {strcpy(tmpstr, init_line);tmp=tmpstr;}
else if (!strcasecmp(p==NULL?name:p+1, "4DOS.COM") || !strcasecmp(name, "Z:4DOS.COM")) {strcpy(tmpstr, "AUTOEXEC.BAT");tmp=tmpstr;}
}
first_shell->Execute(name, tmp);
return;
}
try {
first_shell->Run();
delete first_shell;
first_shell = 0;//Make clear that it shouldn't be used anymore
prepared = false;
dos_shell_running_program = false;
#if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU
Reflect_Menu();
#endif
}
catch (...) {
delete first_shell;
first_shell = 0;//Make clear that it shouldn't be used anymore
prepared = false;
dos_shell_running_program = false;
#if DOSBOXMENU_TYPE == DOSBOXMENU_HMENU
Reflect_Menu();
#endif
throw;
}
}
| 49.796286 | 536 | 0.625914 | mediaexplorer74 |