hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5084e1999ca8630e3c8ab2ebd4f6ded0dc2be481 | 531 | cpp | C++ | leetcode/121_best_time_to_buy_and_sell_stock.cpp | haohaibo/learn | 7a30489e76abeda1465fe610b1c5cf4c4de7e3b6 | [
"MIT"
] | 1 | 2021-02-20T00:14:35.000Z | 2021-02-20T00:14:35.000Z | leetcode/121_best_time_to_buy_and_sell_stock.cpp | haohaibo/learn | 7a30489e76abeda1465fe610b1c5cf4c4de7e3b6 | [
"MIT"
] | null | null | null | leetcode/121_best_time_to_buy_and_sell_stock.cpp | haohaibo/learn | 7a30489e76abeda1465fe610b1c5cf4c4de7e3b6 | [
"MIT"
] | null | null | null | /*
*
* Filename: 121_best_time_to_buy_and_sell_stock.cpp
*
* Author: Haibo Hao
* Email : haohaibo@ncic.ac.cn
* Description: ---
* Create: 2017-10-23 17:26:09
* Last Modified: 2017-10-23 17:27:18
**/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int minPrice = INT_MAX;
int maxProfit = 0;
for (int i = 0; i < prices.size(); ++i) {
minPrice = min(minPrice, prices[i]);
maxProfit = max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}
};
| 23.086957 | 57 | 0.587571 | [
"vector"
] |
508a5c3abdc4f555916dacc141a0fb71003ca551 | 2,285 | hh | C++ | include/goetia/benchmarks/bench_storage.hh | camillescott/boink | db75dc0d87126c5ad20c35405699d89153f109a8 | [
"MIT"
] | 3 | 2019-03-10T02:30:16.000Z | 2020-02-07T20:11:26.000Z | include/goetia/benchmarks/bench_storage.hh | camillescott/boink | db75dc0d87126c5ad20c35405699d89153f109a8 | [
"MIT"
] | 6 | 2018-04-11T02:01:18.000Z | 2020-01-31T14:21:55.000Z | include/goetia/benchmarks/bench_storage.hh | camillescott/goetia | 677e3ef028be6b70a2dacbcf7a4e83f4bb9fdf9a | [
"MIT"
] | 2 | 2019-03-09T19:15:08.000Z | 2019-04-18T19:27:08.000Z | #include "goetia/goetia.hh"
#include "goetia/storage/storage.hh"
#include <chrono>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
namespace goetia {
namespace bench {
template<class storage_type>
void storage_insert_bench(std::unique_ptr<storage_type>& storage,
std::vector<uint64_t>& hashes) {
for (auto hash: hashes) {
storage->insert(hash);
}
}
template<class storage_type>
void storage_query_bench(std::unique_ptr<storage_type>& storage,
std::vector<uint64_t>& hashes) {
for (auto hash: hashes) {
auto val = storage->query(hash);
}
}
template<class storage_type>
void storage_insert_and_query_bench(std::unique_ptr<storage_type>& storage,
std::vector<uint64_t>& hashes) {
for (auto hash: hashes) {
auto val = storage->insert_and_query(hash);
}
}
template<class callable, class storage_type>
double time_it(callable &&func,
std::unique_ptr<storage_type>& storage,
std::vector<uint64_t>& hashes) {
auto time_start = std::chrono::system_clock::now();
func(storage, hashes);
auto time_elapsed = std::chrono::system_clock::now() - time_start;
return std::chrono::duration<double>(time_elapsed).count();
}
template<class storage_type>
void _run_storage_bench(std::unique_ptr<storage_type>& storage,
std::vector<uint64_t>& hashes,
std::string storage_name) {
storage->reset();
std::cout << storage_name << ", " << hashes.size() << ", insert, " << time_it(storage_insert_bench<storage_type>, storage, hashes) << std::endl;
std::cout << storage_name << ", " << hashes.size() << ", insert_second, " << time_it(storage_insert_bench<storage_type>, storage, hashes) << std::endl;
std::cout << storage_name << ", " << hashes.size() << ", query, " << time_it(storage_query_bench<storage_type>, storage, hashes) << std::endl;
std::cout << storage_name << ", " << hashes.size() << ", insert_and_query, " << time_it(storage_insert_and_query_bench<storage_type>, storage, hashes) << std::endl;
}
std::vector<uint64_t> generate_hashes(size_t n_hashes);
void run_storage_bench();
}
}
| 30.065789 | 168 | 0.6407 | [
"vector"
] |
509084a087bc61c0ecc7e023e59ef2df5552b55f | 542 | hpp | C++ | include/EventHandler.hpp | LuisHsu/Assignment_4 | 1735738d3d523d9c3a007d9fb471f121071e75fe | [
"BSD-3-Clause"
] | null | null | null | include/EventHandler.hpp | LuisHsu/Assignment_4 | 1735738d3d523d9c3a007d9fb471f121071e75fe | [
"BSD-3-Clause"
] | null | null | null | include/EventHandler.hpp | LuisHsu/Assignment_4 | 1735738d3d523d9c3a007d9fb471f121071e75fe | [
"BSD-3-Clause"
] | null | null | null | #ifndef EVENTHANDLER_DEF
#define EVENTHANDLER_DEF
#include <sys/epoll.h>
#include <cstdint>
#include <vector>
#include <functional>
#include <unordered_map>
class EventHandler{
using callback_t = std::function<void(uint32_t)>;
public:
EventHandler(int size);
~EventHandler();
void run();
void stop();
void setEvent(int fd, uint32_t flags, callback_t callback);
private:
int epollFd;
bool isRunning;
std::vector<struct epoll_event> events;
std::unordered_map<int, callback_t> callbackTable;
};
#endif | 21.68 | 63 | 0.715867 | [
"vector"
] |
5095383a0172f1890a1fbee4a7f882a2f31387e3 | 735 | cc | C++ | i_wanna_be_the_guy.cc | maximilianbrine/github-slideshow | 76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1 | [
"MIT"
] | null | null | null | i_wanna_be_the_guy.cc | maximilianbrine/github-slideshow | 76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1 | [
"MIT"
] | 3 | 2021-01-04T18:33:39.000Z | 2021-01-04T19:37:21.000Z | i_wanna_be_the_guy.cc | maximilianbrine/github-slideshow | 76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n, n_p, n_q; std::cin >> n;
std::vector<int> x , y;
std::cin >> n_p;
for (int i = 0; i < n_p; ++i) {
int p;
std::cin >> p;
x.push_back(p);
}
std::cin >> n_q;
for (int i = 0; i < n_q; ++i) {
int q;
std:: cin >> q;
y.push_back(q);
}
for (int i = 1; i <= n; ++i) {
if ( std::find(x.begin(), x.end(), i) != x.end() ) {
continue;
}
if ( std::find(y.begin(), y.end(), i) != y.end() ) {
continue;
}
std::cout << "Oh, my keyboard!";
return 0;
}
std::cout << "I become the guy.";
return 0;
} | 21 | 60 | 0.405442 | [
"vector"
] |
50981abc2d6dcd83530c6207a04684826e111490 | 3,098 | hpp | C++ | src/test_suites/oclc/oclc_function_qualifiers/src/common.hpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | 1 | 2021-10-05T14:15:34.000Z | 2021-10-05T14:15:34.000Z | src/test_suites/oclc/oclc_function_qualifiers/src/common.hpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | null | null | null | src/test_suites/oclc/oclc_function_qualifiers/src/common.hpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#ifndef CASSIAN_OCLC_FUNCTION_QUALIFIERS_COMMON_HPP
#define CASSIAN_OCLC_FUNCTION_QUALIFIERS_COMMON_HPP
#include "test_config.hpp"
#include <cassian/logging/logging.hpp>
#include <cassian/runtime/runtime.hpp>
#include <catch2/catch.hpp>
#include <tuple>
#include <utility>
#include <vector>
namespace ca = cassian;
int suggest_work_size(const std::string &type);
int suggest_2d_work_size(const std::string &type);
int suggest_3d_work_size(const std::string &type);
struct work_size_data {
uint32_t work_size_x;
uint32_t work_size_y;
uint32_t work_size_z;
work_size_data() = default;
bool operator!=(const work_size_data &rhs) const {
return work_size_x != rhs.work_size_x || work_size_y != rhs.work_size_y ||
work_size_z != rhs.work_size_z;
}
};
std::array<size_t, 3>
get_different_reqd_size(const std::array<size_t, 3> &work_size);
template <typename T>
std::vector<T> run_kernel_reqd(const cassian::Kernel &kernel,
const std::array<size_t, 3> &global_ws,
const std::array<size_t, 3> &local_ws,
cassian::Runtime *runtime) {
size_t size = 1;
std::for_each(global_ws.begin(), global_ws.end(),
[&size](size_t in) { size *= in; });
ca::Buffer buffer = runtime->create_buffer(size * sizeof(T));
runtime->set_kernel_argument(kernel, 0, buffer);
runtime->run_kernel(kernel, global_ws, local_ws);
std::vector<T> output = runtime->read_buffer_to_vector<T>(buffer);
runtime->release_buffer(buffer);
return output;
}
template <typename T>
std::vector<T> run_kernel_multiple(const cassian::Kernel &kernel,
const std::vector<T> &input,
const std::array<size_t, 3> &work_size,
cassian::Runtime *runtime) {
cassian::Buffer input_buffer =
runtime->create_buffer(input.size() * sizeof(T));
cassian::Buffer output_buffer = runtime->create_buffer(
input.size() * sizeof(T), ca::AccessQualifier::write_only);
runtime->write_buffer_from_vector(input_buffer, input);
runtime->set_kernel_argument(kernel, 0, input_buffer);
runtime->set_kernel_argument(kernel, 1, output_buffer);
runtime->run_kernel(kernel, work_size);
std::vector<T> output = runtime->read_buffer_to_vector<T>(output_buffer);
runtime->release_buffer(output_buffer);
runtime->release_buffer(input_buffer);
return output;
}
std::array<size_t, 3>
get_distributed_work_size(const std::array<size_t, 3> &global_ws,
const std::array<size_t, 3> &work_size_limits,
const std::array<size_t, 3> &local_ws,
const int &work_dim);
namespace Catch {
std::string work_size_data_to_string(work_size_data const &value);
template <> struct StringMaker<work_size_data> {
static std::string convert(work_size_data const &value) {
return work_size_data_to_string(value);
}
};
} // namespace Catch
#endif
| 34.808989 | 78 | 0.677534 | [
"vector"
] |
5098ae2c52f97ecfe884c6ab0746d60fa180b719 | 8,930 | cpp | C++ | src/example.cpp | fengzhang2011/audio-processing | 5fc4c21b8924f00fb0c901c1f04443da23b63f38 | [
"MIT"
] | 25 | 2018-11-30T22:12:00.000Z | 2021-12-09T19:20:35.000Z | src/example.cpp | fengzhang2011/audio-processing | 5fc4c21b8924f00fb0c901c1f04443da23b63f38 | [
"MIT"
] | 5 | 2018-12-02T22:47:16.000Z | 2020-11-06T05:54:56.000Z | src/example.cpp | fengzhang2011/audio-processing | 5fc4c21b8924f00fb0c901c1f04443da23b63f38 | [
"MIT"
] | 2 | 2020-10-16T23:27:37.000Z | 2022-01-12T18:19:31.000Z | /*************************************************
*
* A simple example that uses the three libraries: AudioFile, FFTS, and Pitch_Detection.
*
* Author: Feng Zhang (zhjinf@gmail.com)
* Date: 2018-10-13
*
* Copyright:
* See LICENSE.
*
************************************************/
#include <algorithm>
#include <complex>
#include <cmath>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "AudioFile.h"
#include "ffts.h"
#include "pitch_detection.h"
#include "mfcc.h"
#include "amr.h"
#include "minimp3.h"
#include "denoise.h"
#include "samplerate.h"
void pitch_detection (const char* filename)
{
AudioFile<double> audioFile;
audioFile.load(filename);
//fprintf(stdout, "%d\n", audioFile.getNumChannels());
printf("Sample rate = %d\n", audioFile.getSampleRate());
uint32_t sampleRate = audioFile.getSampleRate();
std::vector<std::vector<double>> buffer = audioFile.samples;
if(buffer.size()>0) // We only use the first channel
{
std::vector<double> wavData = buffer[0];
//printf("samples=%d\n", (int)wavData.size());
float sum = 0.0;
int count = 0;
int step = 8192;
for(int i=0; i<wavData.size()-step; i+=1024)
{
//printf("[%d, %d]\n", i, i+step);
std::vector<double>::const_iterator first = wavData.begin() + i;
std::vector<double>::const_iterator last = wavData.begin() + i + step;
std::vector<double> data(first, last);
//printf("data size=%d\n", (int)data.size());
//float pitch1 = get_pitch_autocorrelation(data, sampleRate);
//printf("pitch [autocorrelation] = %f\n", pitch1);
//float pitch2 = get_pitch_yin(data, sampleRate);
//printf("pitch [yin] = %f\n", pitch2);
float pitch3 = get_pitch_mpm(data, sampleRate);
//printf("pitch [mpm] = %f\n", pitch3);
//float pitch4 = get_pitch_goertzel(data, sampleRate);
//printf("pitch [goertzel] = %f\n", pitch4);
//float pitch5 = get_pitch_dft(data, sampleRate);
//printf("pitch [dft] = %f\n", pitch5);
//if(pitch2>0 || pitch3>0)
//{
// printf("pitch [yin] = %f\n", pitch2);
// printf("pitch [mpm] = %f\n", pitch3);
// //printf("pitch [goertzel] = %f\n", pitch4);
//}
if(pitch3>0 && pitch3<1000)
{
sum += pitch3;
count ++;
}
}
double mean = sum/count;
printf("Pitch = %f Hz\n", mean);
}
}
void mfcc_test ()
{
std::string wavFileName = "../wav/OSR_us_000_0010_8k.wav";
int sampleRate = 0;
int frameLength = 0;
int frameStep = 0;
int nbFrames = 0;
float* signal = MFCC::loadWaveData(wavFileName.c_str(), 25, 10, nbFrames, frameLength, frameStep, sampleRate);
double lowerBound = 0;
double upperBound = 3500;
int nbFilters = 40;
double preEmphFactor = 0.97;
MFCC m(frameLength, sampleRate, nbFilters, lowerBound, upperBound, preEmphFactor);
for(int i=0; i<nbFrames; i++)
{
// printf("%d,", i);
m.mfcc(signal+i*frameStep);
std::vector<float> mfccs = m.getMFCCs(1, 12);
// mfccs = m.getMelBankFeatures(0, 40, false);
for(int j=0; j<mfccs.size(); j++)
{
printf("%f,", mfccs[j]);
}
printf("\n");
// break;
}
}
void amr_test()
{
char szInputFileName[] = "../wav/sample.amr";
char szOutputFileName[256] = {0};
strcpy(szOutputFileName, basename(szInputFileName));
strcat(szOutputFileName, ".pcm");
FILE *fp = NULL;
if (!(fp = fopen(szInputFileName, "rb"))) return;
fseek(fp, 0L, SEEK_END);
int sz = ftell(fp);
printf("file size = %d\n", sz);
fseek(fp, 0L, SEEK_SET);
char* data = (char*)malloc(sz);
fread(data, (size_t)1, sz, fp);
short* output = amr2pcm(data, sz);
free(output);
free(data);
fclose(fp);
}
void wav2amr_test()
{
// char szInputFileName[] = "../wav/OSR_us_000_0010_8k.wav";
char szInputFileName[] = "../wav/female.wav";
char szOutputFileName[256] = {0};
strcpy(szOutputFileName, basename(szInputFileName));
strcat(szOutputFileName, ".amr");
FILE *fp = NULL;
if (!(fp = fopen(szInputFileName, "rb"))) return;
fseek(fp, 0L, SEEK_END);
int sz = ftell(fp);
printf("file size = %d\n", sz);
fseek(fp, 0L, SEEK_SET);
char* data = (char*)malloc(sz);
fread(data, (size_t)1, sz, fp);
fclose(fp);
int out_size = 0;
char* output = wav2amr(data, sz, &out_size, 7);
free(data);
FILE *fpo = NULL;
if (!(fpo = fopen(szOutputFileName, "wb"))) {
free(output);
return;
}
fwrite(output, sizeof(char), out_size, fpo);
free(output);
fclose(fpo);
}
void mp32amr_test()
{
char szInputFileName[] = "../wav/t2.mp3";
char szOutputFileName[256] = {0};
strcpy(szOutputFileName, basename(szInputFileName));
strcat(szOutputFileName, ".amr");
FILE *fp = NULL;
if (!(fp = fopen(szInputFileName, "rb"))) return;
fseek(fp, 0L, SEEK_END);
int sz = ftell(fp);
printf("file size = %d\n", sz);
fseek(fp, 0L, SEEK_SET);
char* data = (char*)malloc(sz);
fread(data, (size_t)1, sz, fp);
fclose(fp);
int out_size = 0;
char* output = mp32amr((short*)data, sz/2, &out_size, 7);
free(data);
FILE *fpo = NULL;
if (!(fpo = fopen(szOutputFileName, "wb"))) {
free(output);
return;
}
fwrite(output, sizeof(char), out_size, fpo);
free(output);
fclose(fpo);
}
void mp3_test(const char* fileName)
{
// Convert MP3 data
mp3dec_t mp3d;
mp3dec_file_info_t info;
mp3dec_load(&mp3d, fileName, &info, 0, 0);
printf("mp3_test: samples = %d\n", info.samples);
printf("mp3_test: channels = %d\n", info.channels);
printf("mp3_test: hz = %d\n", info.hz);
printf("mp3_test: layer = %d\n", info.layer);
printf("mp3_test: avg_bitrate_kbps = %d\n", info.avg_bitrate_kbps);
int samples = info.samples;
if(samples == 0 ) return;
short* pcm = info.buffer;
int sampleRate = info.hz;
printf("mp3_test: Sample rate = %d\n", sampleRate);
}
void denoise_test(const char* fileName)
{
AudioFile<float> audioFile;
audioFile.load(fileName);
int sampleRate = audioFile.getSampleRate();
printf("Sample rate = %d\n", sampleRate);
std::vector<std::vector<float>> buffer = audioFile.samples;
if(buffer.size()==0) return;
// We only use the first channel
int samples = buffer[0].size();
std::vector<float> noisySpeech(samples);
for(int i=0; i<samples; i++) {
noisySpeech[i] = buffer[0][i];
}
std::vector<float> clean = weinerDenoiseTSNR(noisySpeech, sampleRate, 10);
//for(int i=0; i<20; i++) {//clean.size(); i++) {
// printf("%.20f\n", clean[i]);
//}
std::vector<std::vector<float>> cleanedBuffer;
cleanedBuffer.push_back(clean);
AudioFile<float> audioFileOut;
audioFileOut.setAudioBuffer(cleanedBuffer);
audioFileOut.setSampleRate(sampleRate);
audioFileOut.setNumChannels(1);
audioFileOut.save("./clean.wav");
}
void resample_test(const char* fileName)
{
// Read in the audio data
AudioFile<float> audioFile;
audioFile.load(fileName);
int sampleRate = audioFile.getSampleRate();
printf("Sample rate = %d\n", sampleRate);
std::vector<std::vector<float>> buffer = audioFile.samples;
if(buffer.size()==0) return;
// We only use the first channel
int samples = buffer[0].size();
// Preparing the input and output data
float* data_in = (float*)malloc(sizeof(float)*samples);
long input_frames = samples;
for(int i=0; i<input_frames; i++) {
data_in[i] = buffer[0][i];
}
double src_ratio = 1.0*16000/sampleRate;
long output_frames = (int)(samples*src_ratio);
float* data_out = (float*)malloc(sizeof(float)*output_frames);
// Resampling
SRC_DATA* src_data = (SRC_DATA*)malloc(sizeof(SRC_DATA));
if (!src_data) return;
src_data->data_in = data_in;
src_data->data_out = data_out;
src_data->input_frames = input_frames;
src_data->output_frames = output_frames;
src_data->src_ratio = src_ratio;
int converter = SRC_SINC_FASTEST;
int channels = 1;
src_simple(src_data, converter, channels);// (SRC_DATA *data, int converter_type, int channels);
printf("Resample: expected samples = %ld actual samples = %ld\n", output_frames, src_data->output_frames_gen);
// Write the resampled audio
std::vector<float> resampled;
for(int i=0; i<output_frames; i++) {
resampled.push_back(data_out[i]);
}
std::vector<std::vector<float>> resampledBuffer;
resampledBuffer.push_back(resampled);
AudioFile<float> audioFileOut;
audioFileOut.setAudioBuffer(resampledBuffer);
// audioFileOut.setAudioBuffer(buffer);
audioFileOut.setSampleRate(16000);
audioFileOut.setNumChannels(1);
audioFileOut.save("./resampled.wav");
free(src_data);
free(data_in);
free(data_out);
}
int main (int argc, char *argv[])
{
// pitch_detection("../wav/female.wav");
// mfcc_test();
// mp3_test("../wav/t2.mp3");
// denoise_test("../wav/noisy.wav");
// resample_test("../wav/female.wav");
wav2amr_test();
// mp32amr_test();
return 0;
}
| 24.600551 | 112 | 0.635946 | [
"vector"
] |
50a0b6b89da3b68283232901527709df0f445ef5 | 2,587 | hpp | C++ | include/rainbow/memory/object_operations.hpp | Manu343726/rainbow | a125bbf04b0b94686fe0bd4149a097c56df02732 | [
"MIT"
] | 3 | 2021-05-10T21:18:32.000Z | 2021-05-24T02:46:30.000Z | include/rainbow/memory/object_operations.hpp | Manu343726/rainbow | a125bbf04b0b94686fe0bd4149a097c56df02732 | [
"MIT"
] | null | null | null | include/rainbow/memory/object_operations.hpp | Manu343726/rainbow | a125bbf04b0b94686fe0bd4149a097c56df02732 | [
"MIT"
] | null | null | null | #ifndef RAINBOW_MEMORY_OBJECTOPERATIONS_HPP_INCLUDED
#define RAINBOW_MEMORY_OBJECTOPERATIONS_HPP_INCLUDED
#include <cassert>
#include <rainbow/memory/block.hpp>
#include <rainbow/memory/cast.hpp>
#include <type_traits>
#include <utility>
namespace rainbow::memory
{
template<typename T>
void defaultConstruct(const rainbow::memory::Block& object)
{
if constexpr(std::is_default_constructible_v<T>)
{
assert(object.isAligned(alignof(T)));
assert(object.size() >= sizeof(T));
new(object.begin()) T{};
}
}
template<typename T, typename... Args>
void construct(const rainbow::memory::Block& object, Args&&... args)
{
if constexpr(std::is_constructible_v<
T,
decltype(std::forward<Args>(args))...>)
{
assert(object != nullptr);
assert(object.isAligned(alignof(T)));
assert(object.size() >= sizeof(T));
new(object.begin()) T{std::forward<Args>(args)...};
}
}
template<typename T>
void copy(const rainbow::memory::Block& from, const rainbow::memory::Block& to)
{
if constexpr(std::is_copy_constructible_v<T>)
{
assert(from != nullptr);
assert(to != nullptr);
rainbow::memory::construct<T>(
to, *rainbow::memory::object_cast<T>(from));
}
}
template<typename T>
void move(const rainbow::memory::Block& from, const rainbow::memory::Block& to)
{
if constexpr(std::is_move_constructible_v<T>)
{
assert(from != nullptr);
assert(to != nullptr);
rainbow::memory::construct<T>(
to, std::move(*rainbow::memory::object_cast<T>(from)));
}
}
template<typename T>
void copyAssign(
const rainbow::memory::Block& from, const rainbow::memory::Block& to)
{
if constexpr(std::is_copy_assignable_v<T>)
{
assert(from != nullptr);
assert(to != nullptr);
*rainbow::memory::object_cast<T>(to) =
*rainbow::memory::object_cast<T>(from);
}
}
template<typename T>
void moveAssign(
const rainbow::memory::Block& from, const rainbow::memory::Block& to)
{
if constexpr(std::is_move_assignable_v<T>)
{
assert(from != nullptr);
assert(to != nullptr);
*rainbow::memory::object_cast<T>(to) =
std::move(*rainbow::memory::object_cast<T>(from));
}
}
template<typename T>
void destroy(const rainbow::memory::Block& object)
{
assert(object != nullptr);
rainbow::memory::object_cast<T>(object)->~T();
}
} // namespace rainbow::memory
#endif // RAINBOW_MEMORY_OBJECTOPERATIONS_HPP_INCLUDED
| 25.116505 | 79 | 0.636258 | [
"object"
] |
50a6b44554d31cdf1197e0fea676b378be94364a | 355 | cc | C++ | codechef/cook87/ck87medi.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | codechef/cook87/ck87medi.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | codechef/cook87/ck87medi.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://www.codechef.com/COOK87/problems/CK87MEDI
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int t;
cin >> t;
for (int i = 0; i < t; i++) {
int n, k;
cin >> n >> k;
vector<int> v(n);
for (int j = 0; j < n; j++) cin >> v[j];
sort(v.begin(), v.end());
cout << v[(n + k)/2] << endl;
}
}
| 17.75 | 52 | 0.538028 | [
"vector"
] |
50a71de5ad898805ac8e66dafa87fd4a5dee7232 | 51,915 | cpp | C++ | platform/mt6592/hardware/mtkcam/core/featureio/drv/eis/eis_drv.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2022-01-07T01:53:19.000Z | 2022-01-07T01:53:19.000Z | platform/mt6592/hardware/mtkcam/core/featureio/drv/eis/eis_drv.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | null | null | null | platform/mt6592/hardware/mtkcam/core/featureio/drv/eis/eis_drv.cpp | touxiong88/92_mediatek | 5e96a7bb778fd9d9b335825584664e0c8b5ff2c7 | [
"Apache-2.0"
] | 1 | 2020-02-28T02:48:42.000Z | 2020-02-28T02:48:42.000Z | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
/********************************************************************************************
* LEGAL DISCLAIMER
*
* (Header of MediaTek Software/Firmware Release or Documentation)
*
* BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED
* FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS
* ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
* A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY
* WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK
* ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION
* OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH
* RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION,
* TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE
* FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS
* OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES.
************************************************************************************************/
//! \file eis_drv.cpp
#include <utils/Errors.h>
#include <cutils/xlog.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <utils/threads.h>
#include <cutils/atomic.h>
#include <cutils/properties.h>
#include <linux/cache.h>
#include "EIS_Type.h"
#include "imem_drv.h"
#include "isp_reg.h"
#include "isp_drv.h"
#include "m4u_lib.h"
#include "eis_drv.h"
/****************************************************************************************
* Define Value
****************************************************************************************/
#define LOG_TAG "EISDrv"
#undef __func__
#define __func__ __FUNCTION__
#define EIS_LOG(fmt, arg...) XLOGD("[%s]" fmt, __func__, ##arg)
#define EIS_WRN(fmt, arg...) XLOGW("[%s] WRN(%5d):" fmt, __func__, __LINE__, ##arg)
#define EIS_ERR(fmt, arg...) XLOGE("[%s] %s ERR(%5d):" fmt, __func__,__FILE__, __LINE__, ##arg)
//#define EIS_MEMORY_SIZE 408 // 51 * 64 (bits) = 408 bytes
#define EIS_MEMORY_SIZE 256 // 32 * 64 (bits) = 256 bytes
/*******************************************************************************
* Global variable
********************************************************************************/
static MINT32 g_debugDump = 0;
/*******************************************************************************
*
********************************************************************************/
EisDrvBase *EisDrvBase::createInstance()
{
return EisDrv::getInstance();
}
/*******************************************************************************
*
********************************************************************************/
EisDrvBase *EisDrv::getInstance()
{
EIS_LOG("+");
static EisDrv singleton;
if(singleton.init() != EIS_RETURN_NO_ERROR)
{
EIS_LOG("singleton.init() fail");
return NULL;
}
EIS_LOG("-");
return &singleton;
}
/*******************************************************************************
*
********************************************************************************/
MVOID EisDrv::destroyInstance()
{
uninit();
}
/*******************************************************************************
*
********************************************************************************/
EisDrv::EisDrv() : EisDrvBase()
{
// reference count
mUsers = 0;
//search window offset max value
mFLOffsetMax_H = 15;
mFLOffsetMax_V = 65;
//ISP object
m_pISPDrvObj = NULL;
m_pISPVirtDrv = NULL;
// ISP register address
mISPRegAddr = 0;
//IMEM
m_pIMemDrv = NULL;
mEisIMemInfo.memID = -5;
mEisIMemInfo.virtAddr = mEisIMemInfo.phyAddr = mEisIMemInfo.size = 0;
// config protection usage
mConfigFail = MFALSE;
mImgW = 0;
mImgH = 0;
mDSRatio = 0;
mMBNum_H = 0;
mMBNum_V = 0;
mRPNum_H = 0;
mRPNum_V = 0;
mFLOfset_H = 0;
mFLOfset_V = 0;
mMBOfset_H = 0;
mMBOfset_V = 0;
}
/*******************************************************************************
*
********************************************************************************/
EisDrv::~EisDrv()
{
}
/*******************************************************************************
*
********************************************************************************/
MINT32 EisDrv::init()
{
EIS_LOG("mUsers(%d)",mUsers);
MINT32 err = EIS_RETURN_NO_ERROR;
//====== Reference Count ======
Mutex::Autolock lock(mLock);
if(mUsers > 0)
{
EIS_LOG("%d has inited",mUsers);
android_atomic_inc(&mUsers);
err = EIS_RETURN_NO_ERROR;
return err;
}
android_atomic_inc(&mUsers); // increase reference count
//====== Prepare Memory for DMA ======
//IMEM
m_pIMemDrv = IMemDrv::createInstance();
if(m_pIMemDrv == NULL)
{
EIS_LOG("Null IMemDrv Obj");
err = EIS_RETURN_NULL_OBJ;
return err;
}
MUINT32 eisMemSize = EIS_MEMORY_SIZE;
createMemBuf(eisMemSize,1,&mEisIMemInfo);
if(mEisIMemInfo.virtAddr == 0 && mEisIMemInfo.phyAddr == 0)
{
EIS_LOG("create IMem fail");
err = EIS_RETURN_MEMORY_ERROR;
return err;
}
EIS_LOG("EisIMem : memID(%d),size(%u),virAdd(0x%x),phyAddr(0x%x)",mEisIMemInfo.memID,
mEisIMemInfo.size,
mEisIMemInfo.virtAddr,
mEisIMemInfo.phyAddr);
//====== Create ISP Driver Get ISP HW Register Address ======
m_pISPDrvObj = IspDrv::createInstance();
if(m_pISPDrvObj == NULL)
{
EIS_ERR("m_pISPDrvObj create instance fail");
err = EIS_RETURN_NULL_OBJ;
return err;
}
if(MTRUE != m_pISPDrvObj->init())
{
EIS_LOG("m_pISPDrvObj->init() fail");
err = EIS_RETURN_API_FAIL;
return err;
}
#if 0
// Command Queue
m_pISPVirtDrv = m_pISPDrvObj->getCQInstance(ISP_DRV_CQ0);
if(m_pISPVirtDrv == NULL)
{
EIS_ERR("m_pISPVirtDrv create instance fail");
err = EIS_RETURN_NULL_OBJ;
return err;
}
mISPRegAddr = (MUINT32)m_pISPVirtDrv->getRegAddr();
if(mISPRegAddr == 0)
{
EIS_ERR("get mISPRegAddr fail");
err = EIS_RETURN_API_FAIL;
return err;
}
m_pISPVirtDrv->cqAddModule(ISP_DRV_CQ0, CAM_DMA_EISO);
m_pISPVirtDrv->cqAddModule(ISP_DRV_CQ0, CAM_ISP_EIS);
#else
mISPRegAddr = m_pISPDrvObj->getRegAddr();
if(mISPRegAddr == 0)
{
EIS_ERR("get mISPRegAddr fail");
err = EIS_RETURN_API_FAIL;
return err;
}
#endif
EIS_LOG("mISPRegAddr = 0x%8x",mISPRegAddr);
//====== Initializa EIS ======
setEISOAddr(); // set DMA(EISO) output memory address
EIS_LOG("X");
return err;
}
/*******************************************************************************
*
********************************************************************************/
MINT32 EisDrv::uninit()
{
EIS_LOG("mUsers(%d) ",mUsers);
MINT32 err = EIS_RETURN_NO_ERROR;
//====== Reference Count ======
Mutex::Autolock lock(mLock);
if(mUsers <= 0) // No more users
{
EIS_LOG("No user");
return EIS_RETURN_NO_ERROR;
}
// >= one user
android_atomic_dec(&mUsers);
if(mUsers == 0)
{
//====== Reset Register ======
resetRegister();
//====== Free Memory ======
destroyMemBuf(1,&mEisIMemInfo);
mEisIMemInfo.memID = -5;
mEisIMemInfo.virtAddr = mEisIMemInfo.phyAddr = mEisIMemInfo.size = 0;
if(m_pIMemDrv != NULL)
{
m_pIMemDrv->destroyInstance();
m_pIMemDrv = NULL;
}
//====== Destory ISP Driver Object ======
if(m_pISPVirtDrv != NULL)
{
m_pISPVirtDrv = NULL;
}
if(m_pISPDrvObj != NULL)
{
err = m_pISPDrvObj->uninit();
if(err < 0)
{
EIS_ERR("m_pISPDrvObj->uninit fail");
return err;
}
m_pISPDrvObj->destroyInstance();
m_pISPDrvObj = NULL;
}
//====== Reset Member Variable ======
mFLOffsetMax_H = 15;
mFLOffsetMax_V = 65;
mISPRegAddr = 0;
mConfigFail = MFALSE;
mImgW = 0;
mImgH = 0;
mDSRatio = 0;
mMBNum_H = 0;
mMBNum_V = 0;
mRPNum_H = 0;
mRPNum_V = 0;
mFLOfset_H = 0;
mFLOfset_V = 0;
mMBOfset_H = 0;
mMBOfset_V = 0;
}
else
{
EIS_LOG("Still %d users ", mUsers);
}
EIS_LOG("X");
return EIS_RETURN_NO_ERROR;
}
/*******************************************************************************
*
********************************************************************************/
MINT32 EisDrv::createMemBuf(MUINT32 &memSize, MUINT32 bufCnt, IMEM_BUF_INFO *bufInfo)
{
MINT32 err = EIS_RETURN_NO_ERROR;
MUINT32 alingSize = (memSize + L1_CACHE_BYTES - 1) & ~(L1_CACHE_BYTES - 1);
EIS_LOG("Cnt(%u),Size(%u),alingSize(%u)",bufCnt, memSize, alingSize);
memSize = alingSize;
if(bufCnt > 1) // more than one
{
for(MUINT32 i = 0; i < bufCnt; ++i)
{
bufInfo[i].size = alingSize;
if(m_pIMemDrv->allocVirtBuf(&bufInfo[i]) < 0)
{
EIS_ERR("m_pIMemDrv->allocVirtBuf() error, i(%d)",i);
err = EIS_RETURN_API_FAIL;
}
if(m_pIMemDrv->mapPhyAddr(&bufInfo[i]) < 0)
{
EIS_ERR("m_pIMemDrv->mapPhyAddr() error, i(%d)",i);
err = EIS_RETURN_API_FAIL;
}
}
}
else
{
bufInfo->size = alingSize;
if(m_pIMemDrv->allocVirtBuf(bufInfo) < 0)
{
EIS_ERR("m_pIMemDrv->allocVirtBuf() error");
err = EIS_RETURN_API_FAIL;
}
if(m_pIMemDrv->mapPhyAddr(bufInfo) < 0)
{
EIS_ERR("m_pIMemDrv->mapPhyAddr() error");
err = EIS_RETURN_API_FAIL;
}
}
EIS_LOG("-");
return err;
}
/******************************************************************************
*
*******************************************************************************/
MINT32 EisDrv::destroyMemBuf(MUINT32 bufCnt, IMEM_BUF_INFO *bufInfo)
{
EIS_LOG("Cnt(%u)", bufCnt);
MINT32 err = EIS_RETURN_NO_ERROR;
if(bufCnt > 1) // more than one
{
for(MUINT32 i = 0; i < bufCnt; ++i)
{
if(0 == bufInfo[i].virtAddr)
{
EIS_LOG("Buffer doesn't exist, i(%d)",i);
continue;
}
if(m_pIMemDrv->unmapPhyAddr(&bufInfo[i]) < 0)
{
EIS_ERR("m_pIMemDrv->unmapPhyAddr() error, i(%d)",i);
err = EIS_RETURN_API_FAIL;
}
if (m_pIMemDrv->freeVirtBuf(&bufInfo[i]) < 0)
{
EIS_ERR("m_pIMemDrv->freeVirtBuf() error, i(%d)",i);
err = EIS_RETURN_API_FAIL;
}
}
}
else
{
if(0 == bufInfo->virtAddr)
{
EIS_LOG("Buffer doesn't exist");
}
if(m_pIMemDrv->unmapPhyAddr(bufInfo) < 0)
{
EIS_ERR("m_pIMemDrv->unmapPhyAddr() error");
err = EIS_RETURN_API_FAIL;
}
if (m_pIMemDrv->freeVirtBuf(bufInfo) < 0)
{
EIS_ERR("m_pIMemDrv->freeVirtBuf() error");
err = EIS_RETURN_API_FAIL;
}
}
EIS_LOG("-");
return err;
}
/******************************************************************************
*
*******************************************************************************/
MVOID EisDrv::resetRegister()
{
EIS_LOG("+");
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_SEL_SET, EIS_SEL_SET,0);
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_SEL_SET, EIS_RAW_SEL_SET,0);
ISP_WRITE_BITS(pEis, CAM_CTL_SPARE3, EIS_DB_LD_SEL,0);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_H, 1);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_V, 1);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HRP, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VRP, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_AD_KNEE, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_AD_CLIP, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HWIN, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VWIN, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_H, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_IIR_H, 3);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_FIR_H, 16);
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_IIR_V, 3);
ISP_WRITE_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_X_CENTER, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_X_SOURROUND, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_Y_CENTER, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_Y_SURROUND, 0);
ISP_WRITE_BITS(pEis, CAM_EIS_MB_OFFSET, MB_OFFSET_H,0);
ISP_WRITE_BITS(pEis, CAM_EIS_MB_OFFSET, MB_OFFSET_V,0);
ISP_WRITE_BITS(pEis, CAM_EIS_MB_INTERVAL, MB_INTERVAL_H,0);
ISP_WRITE_BITS(pEis, CAM_EIS_MB_INTERVAL, MB_INTERVAL_V,0);
EIS_LOG("-");
}
/*******************************************************************************
* 15004008, CAM_CTL_EN2, EIS_EN[16]
********************************************************************************/
MVOID EisDrv::enableEIS(MBOOL a_Enable)
{
EIS_LOG("Enable(0x%x)", a_Enable);
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
//15004008, CAM_CTL_EN2_SET, EIS_EN_SET[16]
if(a_Enable == MTRUE) //enable
{
//ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_EN2_SET, EIS_EN_SET, 0x1);
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_EN2, EIS_EN, 1);
ISP_WRITE_BITS(pEis, CAM_CTL_CDP_DCM_DIS, EIS_DCM_DIS, 1); // only need in MT6589
#if 1 //disable this block if Af is ready
ISP_WRITE_BITS(pEis , CAM_SGG_PGN, SGG_GAIN, 16);
ISP_WRITE_BITS(pEis , CAM_SGG_GMR, SGG_GMR1, 31);
ISP_WRITE_BITS(pEis , CAM_SGG_GMR, SGG_GMR2, 63);
ISP_WRITE_BITS(pEis , CAM_SGG_GMR, SGG_GMR3, 127);
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_DMA_EN_SET, ESFKO_EN_SET, 1);
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_EN1_SET, SGG_EN_SET, 1);
#endif
}
else if(a_Enable == MFALSE) //disable
{
//ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_EN2_CLR, EIS_EN_CLR, 0x1);
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_EN2, EIS_EN, 0);
ISP_WRITE_BITS(pEis, CAM_CTL_CDP_DCM_DIS, EIS_DCM_DIS, 0); // only need in MT6589
}
else
{
EIS_ERR("wrong value");
}
}
/*******************************************************************************
*
********************************************************************************/
MBOOL EisDrv::isEISEnable()
{
MBOOL ret;
//15004008, CAM_CTL_EN2, EIS_EN[16]
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
ret = (0x1 & ISP_READ_BITS(pEis, CAM_CTL_EN2, EIS_EN));
EIS_LOG("%d",ret);
return ret;
}
/*******************************************************************************
* 15004018, CAM_CTL_SEL, EIS_SEL[15]
********************************************************************************/
MVOID EisDrv::setEISSel(MBOOL a_EisSel)
{
EIS_LOG("[0-before CDRZ, 1-after CDRZ] EisSel(0x%x)", (a_EisSel & 0x1));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_SEL_SET, EIS_SEL_SET,(a_EisSel & 0x1));
}
/*******************************************************************************
* 15004018, CAM_CTL_SEL, EIS_RAW_SEL[16]
********************************************************************************/
MVOID EisDrv::setEISRawSel(MBOOL a_EisRawSel)
{
EIS_LOG("[0-CDP, 1-RAW] EisRawSel(0x%x)", (a_EisRawSel & 0x1));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_SEL_SET, EIS_RAW_SEL_SET,(a_EisRawSel & 0x1));
}
/*******************************************************************************
* 1500406C, CAM_CTL_SPARE3, EIS_DB_LD_SEL[6]
********************************************************************************/
MVOID EisDrv::setEIS_DB_SEL(MBOOL a_EisDB)
{
EIS_LOG("[0-no change, 1-raw_db_load1] EisDB(0x%x)", (a_EisDB & 0x1));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
ISP_WRITE_ENABLE_BITS(pEis, CAM_CTL_SPARE3, EIS_DB_LD_SEL,(a_EisDB & 0x1));
}
/*******************************************************************************
* 15004DC0, CAM_EIS_PREP_ME_CTRL1
********************************************************************************/
MVOID EisDrv::setEISFilterDS(MINT32 a_DS)
{
EIS_LOG("a_DS(0x%x)", (a_DS & 0x7));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
switch(a_DS)
{
case 1 :
case 2 :
case 4 :
break;
default :
EIS_ERR("Error down sample ratio");
return;
break;
}
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_H, (a_DS & 0x7));
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_V, (a_DS & 0x7));
mDSRatio = (a_DS & 0x7);
}
/*******************************************************************************
* 15004DC0, CAM_EIS_PREP_ME_CTRL1
********************************************************************************/
MVOID EisDrv::setRPNum(MINT32 a_RPNum_H, MINT32 a_RPNum_V)
{
EIS_LOG("[H:1-16,V:1-8] H(%d),V(%d)", a_RPNum_H, a_RPNum_V);
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
//====== Horizontal ======
boundaryCheck(a_RPNum_H, 16, 1);
EIS_LOG("final RPNum_H(0x%x)", (a_RPNum_H & 0x1F));
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HRP, (a_RPNum_H & 0x1F));
mRPNum_H = (a_RPNum_H & 0x1F);
//====== Vertical ======
MINT32 tempMBNum_V = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VWIN);
if(tempMBNum_V != mMBNum_V)
{
EIS_ERR("ISP read ME_NUM_VWIN fail : tempMBNum_V(%d),mMBNum_V(%d)", tempMBNum_V, mMBNum_V);
tempMBNum_V = mMBNum_V;
mConfigFail |= MTRUE;
}
else
{
mConfigFail |= MFALSE;
}
if(tempMBNum_V <= 4)
{
boundaryCheck(a_RPNum_V,8,1);
}
else
{
boundaryCheck(a_RPNum_V,4,1);
}
EIS_LOG("MBNum_V(0x%x),final RPNum_V(0x%x)",tempMBNum_V,(a_RPNum_V & 0xF));
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VRP, (a_RPNum_V & 0xF));
mRPNum_V = (a_RPNum_V & 0xF);
}
/*******************************************************************************
* 15004DC0, CAM_EIS_PREP_ME_CTRL1
********************************************************************************/
void EisDrv::setADKneeClip(MINT32 a_Knee, MINT32 a_Clip)
{
EIS_LOG("Knee(%d),Clip(%d)", a_Knee, a_Clip);
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
boundaryCheck(a_Knee,15,0);
boundaryCheck(a_Clip,15,0);
EIS_LOG("Final Knee(0x%x),Clip(0x%x)", (a_Knee & 0xF), (a_Clip & 0xF));
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_AD_KNEE, (a_Knee & 0xF));
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_AD_CLIP, (a_Clip & 0xF));
}
/*******************************************************************************
* 15004DC0, CAM_EIS_PREP_ME_CTRL1
********************************************************************************/
MVOID EisDrv::setMBNum(MINT32 a_MBNum_H, MINT32 a_MBNum_V)
{
EIS_LOG("[H:1-4,V:1-8] H(%d),V(%d)", a_MBNum_H, a_MBNum_V);
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
//====== Horizontal =====
boundaryCheck(a_MBNum_H, 4, 1);
EIS_LOG("final MBNum_H(0x%x)", (a_MBNum_H & 0x7));
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HWIN, (a_MBNum_H & 0x7));
mMBNum_H = (a_MBNum_H & 0x7);
//====== Vertical ======
boundaryCheck(a_MBNum_V, 8, 1);
EIS_LOG("final MBNum_V(0x%x)", (a_MBNum_V & 0xF));
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VWIN, (a_MBNum_V & 0xF));
mMBNum_V = (a_MBNum_V & 0xF);
}
/*******************************************************************************
* 15004DC4, CAM_EIS_PREP_ME_CTRL2
********************************************************************************/
MVOID EisDrv::setFilter_H(MINT32 a_Gain, MINT32 a_IIRGain, MINT32 a_FIRGain)
{
EIS_LOG("Gain(%d),IIRGain(%d),FIRGain(%d)", (a_Gain & 0x3), (a_IIRGain & 0x7), (a_FIRGain & 0x3F));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
if(a_Gain != 0 && a_Gain != 1 && a_Gain != 3)
{
EIS_ERR("wrong a_Gain, setting fail");
}
else
{
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_H, (a_Gain & 0x3));
}
if (a_IIRGain != 3 && a_IIRGain != 4)
{
EIS_ERR("wrong a_IIRGain, setting fail");
}
else
{
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_IIR_H, (a_IIRGain & 0x7));
}
if (a_FIRGain != 16 && a_FIRGain != 32)
{
EIS_ERR("wrong a_FIRGain, setting fail");
}
else
{
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_FIR_H, (a_FIRGain & 0x3F));
}
}
/*******************************************************************************
* 15004DC4, CAM_EIS_PREP_ME_CTRL2
********************************************************************************/
MVOID EisDrv::setFilter_V(MINT32 a_IIRGain)
{
EIS_LOG("IIRGain(0x%x)", (a_IIRGain & 0x7));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
if (a_IIRGain != 3 && a_IIRGain != 4)
{
EIS_ERR("wrong a_IIRGain, setting fail");
}
else
{
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_IIR_V, (a_IIRGain & 0x7));
}
}
/*******************************************************************************
* 15004DC4, CAM_EIS_PREP_ME_CTRL2
********************************************************************************/
MVOID EisDrv::setWRPEnable(MBOOL a_Enable)
{
EIS_LOG("Enable(0x%x)", (a_Enable & 0x1));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
if (a_Enable != MTRUE && a_Enable != MFALSE)
{
EIS_ERR("wrong a_Enable, setting fail");
}
else
{
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, EIS_WRP_EN, (a_Enable & 0x1));
}
}
/*******************************************************************************
* 15004DC4, CAM_EIS_PREP_ME_CTRL2
********************************************************************************/
MVOID EisDrv::setFirstFrame(MBOOL a_First)
{
EIS_LOG("First(0x%x)", (a_First & 0x1));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
if (a_First != MTRUE && a_First != MFALSE)
{
EIS_ERR("wrong a_First, setting fail");
}
else
{
ISP_WRITE_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, EIS_FIRST_FRM, (a_First & 0x1));
}
}
/*******************************************************************************
* 15004DC8, CAM_EIS_LMV_TH
********************************************************************************/
MVOID EisDrv::setLMV_TH(MINT32 a_Center_X, MINT32 a_Surrond_X, MINT32 a_Center_Y, MINT32 a_Surrond_Y)
{
EIS_LOG("HC(%d),HS(%d),VC(%d),VS(%d)", a_Center_X, a_Surrond_X, a_Center_Y, a_Surrond_Y);
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
boundaryCheck(a_Center_X, 255, 0);
boundaryCheck(a_Surrond_X, 255, 0);
boundaryCheck(a_Center_Y, 255, 0);
boundaryCheck(a_Surrond_Y, 255, 0);
EIS_LOG("Final HC(0x%x),HS(0x%x),VC(0x%x),VS(0x%x)",(a_Center_X & 0xFF),(a_Surrond_X & 0xFF),(a_Center_Y & 0xFF),(a_Surrond_Y & 0xFF));
ISP_WRITE_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_X_CENTER, (a_Center_X & 0xFF));
ISP_WRITE_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_X_SOURROUND, (a_Surrond_X & 0xFF));
ISP_WRITE_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_Y_CENTER, (a_Center_Y & 0xFF));
ISP_WRITE_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_Y_SURROUND, (a_Surrond_Y & 0xFF));
}
/*******************************************************************************
* 15004DCC, CAM_EIS_FL_OFFSET
********************************************************************************/
MVOID EisDrv::setFLOffsetMax(MINT32 a_FLOffsetMax_H, MINT32 a_FLOffsetMax_V)
{
EIS_LOG("Max_H(%d),Max_V(%d)", a_FLOffsetMax_H,a_FLOffsetMax_V);
mFLOffsetMax_H = a_FLOffsetMax_H;
mFLOffsetMax_V = a_FLOffsetMax_V;
boundaryCheck(mFLOffsetMax_H, 15, 0);
boundaryCheck(mFLOffsetMax_V, 33, 0);
EIS_LOG("final Max_H(%d),Max_V(%d)", mFLOffsetMax_H,mFLOffsetMax_V);
}
/*******************************************************************************
* 15004DCC, CAM_EIS_FL_OFFSET
********************************************************************************/
MVOID EisDrv::setFLOffset(MINT32 a_FLOffset_H, MINT32 a_FLOffset_V)
{
EIS_LOG("H(%d),V(%d)", a_FLOffset_H, a_FLOffset_V);
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
boundaryCheck(a_FLOffset_H, mFLOffsetMax_H, (0 - mFLOffsetMax_H));
boundaryCheck(a_FLOffset_V, mFLOffsetMax_V, (0 - (mFLOffsetMax_V - 1)));
EIS_LOG("final FLOfs_H(0x%x), FLOfs_V(0x%x)", (a_FLOffset_H & 0xFFF), (a_FLOffset_V & 0xFFF));
ISP_WRITE_BITS(pEis, CAM_EIS_FL_OFFSET, FL_OFFSET_H, (a_FLOffset_H & 0xFFF));
ISP_WRITE_BITS(pEis, CAM_EIS_FL_OFFSET, FL_OFFSET_V, (a_FLOffset_V & 0xFFF));
mFLOfset_H = (a_FLOffset_H & 0xFFF);
mFLOfset_V = (a_FLOffset_V & 0xFFF);
}
/*******************************************************************************
* 15004DD0, CAM_EIS_MB_OFFSET
********************************************************************************/
MVOID EisDrv::setMBOffset_H(MINT32 a_MBOffset_H)
{
EIS_LOG("H(%d)", a_MBOffset_H);
MBOOL errFlag = MFALSE;
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
MINT32 upBound,lowBound;
MINT32 tempWidth = ISP_READ_BITS(pEis, CAM_EIS_IMAGE_CTRL, WIDTH);
MINT32 tempFLOffset_H = Complement2(ISP_READ_BITS(pEis, CAM_EIS_FL_OFFSET, FL_OFFSET_H), 12);
MINT32 tempDSRatio_H = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_H);
MINT32 tempMBNum_H = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HWIN);
MINT32 tempMBInterval_H = Complement2(ISP_READ_BITS(pEis, CAM_EIS_MB_INTERVAL, MB_INTERVAL_H), 12);
MINT32 tempRPNum_H = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HRP);
//====== Value Checking ======
if(mImgW != tempWidth)
{
EIS_ERR("ISP read WIDTH fail : tempWidth(%d),mImgW(%d)", tempWidth, mImgW);
tempWidth = mImgW;
errFlag = MTRUE;
}
if(mFLOfset_H != tempFLOffset_H)
{
EIS_ERR("ISP read FL_OFFSET_H fail : tempFLOffset_H(%d),mFLOfset_H(%d)", tempFLOffset_H, mFLOfset_H);
tempFLOffset_H = mFLOfset_H;
errFlag = MTRUE;
}
if(mDSRatio != tempDSRatio_H)
{
EIS_ERR("ISP read PREP_DS_IIR_H fail : tempDSRatio_H(%d),mDSRatio(%d)", tempDSRatio_H, mDSRatio);
tempDSRatio_H = mDSRatio;
errFlag = MTRUE;
}
if(mMBNum_H != tempMBNum_H)
{
EIS_ERR("ISP read ME_NUM_HWIN fail : tempMBNum_H(%d),mMBNum_H(%d)", tempMBNum_H, mMBNum_H);
tempMBNum_H = mMBNum_H;
errFlag = MTRUE;
}
if(errFlag == MFALSE)
{
mConfigFail |= MFALSE;
}
else
{
mConfigFail |= MTRUE;
}
//====== Check Limitation ======
// low bound
if(tempFLOffset_H < 0)
{
lowBound = 11 - tempFLOffset_H;
}
else
{
lowBound = 11 + tempFLOffset_H;
}
// up bound
if(tempFLOffset_H > 0)
{
upBound = tempWidth/tempDSRatio_H - tempRPNum_H*16 - tempFLOffset_H - tempMBInterval_H*(tempMBNum_H-1);
}
else
{
upBound = tempWidth/tempDSRatio_H - tempRPNum_H*16 - 1 - tempMBInterval_H*(tempMBNum_H-1);
}
EIS_LOG("W(%d),FLOfs_H(%d),DSRat_H(%d),MBNum_H(%d),MBInt_H(%d),RPNum_H(%d)"
,tempWidth,tempFLOffset_H,tempDSRatio_H,tempMBNum_H,tempMBInterval_H,tempRPNum_H);
EIS_LOG("upB(%d),lowB(%d)", upBound, lowBound);
if(upBound < lowBound)
{
EIS_ERR("wrong boundary");
}
else
{
boundaryCheck(a_MBOffset_H, upBound, lowBound);
EIS_LOG("final MBOfs_H(0x%x)", (a_MBOffset_H & 0xFFF));
ISP_WRITE_BITS(pEis, CAM_EIS_MB_OFFSET, MB_OFFSET_H,(a_MBOffset_H & 0xFFF));
mMBOfset_H = (a_MBOffset_H & 0xFFF);
}
}
/*******************************************************************************
* 15004DD0, CAM_EIS_MB_OFFSET
********************************************************************************/
MVOID EisDrv::setMBOffset_V(MINT32 a_MBOffset_V)
{
EIS_LOG("V(%d)", a_MBOffset_V);
MBOOL errFlag = MFALSE;
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
MINT32 upBound,lowBound;
MINT32 tempHeight = ISP_READ_BITS(pEis, CAM_EIS_IMAGE_CTRL, HEIGHT);
MINT32 tempFLOffset_V = Complement2(ISP_READ_BITS(pEis, CAM_EIS_FL_OFFSET, FL_OFFSET_V), 12);
MINT32 tempDSRatio_V = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_V);
MINT32 tempMBNum_V = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VWIN);
MINT32 tempMBInterval_V = Complement2(ISP_READ_BITS(pEis, CAM_EIS_MB_INTERVAL, MB_INTERVAL_V), 12);
MINT32 tempRPNum_V = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VRP);
//====== Value Checking ======
if(mImgH != tempHeight)
{
EIS_ERR("ISP read HEIGHT fail : tempHeight(%d),mImgH(%d)", tempHeight, mImgH);
tempHeight = mImgH;
errFlag = MTRUE;
}
if(mFLOfset_V != tempFLOffset_V)
{
EIS_ERR("ISP read FL_OFFSET_V fail : tempFLOffset_V(%d),mFLOfset_V(%d)", tempFLOffset_V, mFLOfset_V);
tempFLOffset_V = mFLOfset_V;
errFlag = MTRUE;
}
if(mDSRatio != tempDSRatio_V)
{
EIS_ERR("ISP read PREP_DS_IIR_V fail : tempDSRatio_V(%d),mDSRatio(%d)", tempDSRatio_V, mDSRatio);
tempDSRatio_V = mDSRatio;
errFlag = MTRUE;
}
if(mMBNum_V != tempMBNum_V)
{
EIS_ERR("ISP read ME_NUM_VWIN fail : tempMBNum_V(%d),mMBNum_V(%d)", tempMBNum_V, mMBNum_V);
tempMBNum_V = mMBNum_V;
errFlag = MTRUE;
}
if(errFlag == MFALSE)
{
mConfigFail |= MFALSE;
}
else
{
mConfigFail |= MTRUE;
}
//====== Check Limitation ======
// low bound
if(tempFLOffset_V < 0)
{
lowBound = 9 - tempFLOffset_V;
}
else
{
lowBound = 9 + tempFLOffset_V;
}
// up bound
if(tempFLOffset_V > 0)
{
upBound = tempHeight/tempDSRatio_V - tempRPNum_V*16 - tempFLOffset_V - tempMBInterval_V*(tempMBNum_V-1);
}
else
{
upBound = tempHeight/tempDSRatio_V - tempRPNum_V*16 - 1 - tempMBInterval_V*(tempMBNum_V-1);
}
EIS_LOG("H(%d),FLOfs_V(%d),DSRat_V(%d),MBNum_V(%d),MBInt_V(%d),RPNum_V(%d)"
,tempHeight,tempFLOffset_V,tempDSRatio_V,tempMBNum_V,tempMBInterval_V,tempRPNum_V);
EIS_LOG("upB(%d), lowB(%d)", upBound, lowBound);
if(upBound < lowBound)
{
EIS_ERR("wrong boundary");
}
else
{
boundaryCheck(a_MBOffset_V, upBound, lowBound);
EIS_LOG("final MBOfs_V(0x%x)", (a_MBOffset_V & 0xFFF));
ISP_WRITE_BITS(pEis, CAM_EIS_MB_OFFSET, MB_OFFSET_V,(a_MBOffset_V & 0xFFF));
mMBOfset_V = (a_MBOffset_V & 0xFFF);
}
}
/*******************************************************************************
* 15004DD4, CAM_EIS_MB_INTERVAL
********************************************************************************/
MVOID EisDrv::setMBInterval_H(MINT32 a_MBInterval_H)
{
EIS_LOG("H(%d)", a_MBInterval_H);
MBOOL errFlag = MFALSE;
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
MINT32 upBound,lowBound;
MINT32 tempWidth = ISP_READ_BITS(pEis, CAM_EIS_IMAGE_CTRL, WIDTH);
MINT32 tempFLOffset_H = Complement2(ISP_READ_BITS(pEis, CAM_EIS_FL_OFFSET, FL_OFFSET_H), 12);
MINT32 tempDSRatio_H = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_H);
MINT32 tempRPNum_H = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HRP);
MINT32 tempMBNum_H = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HWIN);
MINT32 tempMBOffset_H = Complement2(ISP_READ_BITS(pEis, CAM_EIS_MB_OFFSET, MB_OFFSET_H), 12);
//====== Value Checking ======
if(mImgW != tempWidth)
{
EIS_ERR("ISP read WIDTH fail : tempWidth(%d),mImgW(%d)", tempWidth, mImgW);
tempWidth = mImgW;
errFlag = MTRUE;
}
if(mFLOfset_H != tempFLOffset_H)
{
EIS_ERR("ISP read FL_OFFSET_H fail : tempFLOffset_H(%d),mFLOfset_H(%d)", tempFLOffset_H, mFLOfset_H);
tempFLOffset_H = mFLOfset_H;
errFlag = MTRUE;
}
if(mDSRatio != tempDSRatio_H)
{
EIS_ERR("ISP read PREP_DS_IIR_H fail : tempDSRatio_H(%d),mDSRatio(%d)", tempDSRatio_H, mDSRatio);
tempDSRatio_H = mDSRatio;
errFlag = MTRUE;
}
if(mRPNum_H != tempRPNum_H)
{
EIS_ERR("ISP read ME_NUM_HRP fail : tempRPNum_H(%d),mRPNum_H(%d)", tempRPNum_H, mRPNum_H);
tempRPNum_H = mRPNum_H;
errFlag = MTRUE;
}
if(mMBNum_H != tempMBNum_H)
{
EIS_ERR("ISP read ME_NUM_HWIN fail : tempMBNum_H(%d),mMBNum_H(%d)", tempMBNum_H, mMBNum_H);
tempMBNum_H = mMBNum_H;
errFlag = MTRUE;
}
if(mMBOfset_H != tempMBOffset_H)
{
EIS_ERR("ISP read MB_OFFSET_H fail : tempMBOffset_H(%d),mMBOfset_H(%d)", tempMBOffset_H, mMBOfset_H);
tempMBOffset_H = mMBOfset_H;
errFlag = MTRUE;
}
if(errFlag == MFALSE)
{
mConfigFail |= MFALSE;
}
else
{
mConfigFail |= MTRUE;
}
//====== Check Limitation ======
// low bound
lowBound = (tempRPNum_H + 1) * 16;
// up bound
if(tempFLOffset_H > 0)
{
upBound = ((tempWidth / tempDSRatio_H) - tempMBOffset_H - tempRPNum_H*16 - tempFLOffset_H) / (tempMBNum_H-1);
}
else
{
upBound = ((tempWidth / tempDSRatio_H) - tempMBOffset_H - tempRPNum_H*16 - 1) / (tempMBNum_H-1);
}
EIS_LOG("W(%d),FLOfs_H(%d),DSRat_H(%d),RPNum_H(%d),MBNum_H(%d),MBOfs_H(%d)"
,tempWidth,tempFLOffset_H,tempDSRatio_H,tempRPNum_H,tempMBNum_H,tempMBOffset_H);
EIS_LOG("upB(%d), lowB(%d)", upBound, lowBound);
if(upBound < lowBound)
{
EIS_ERR("wrong boundary");
}
else
{
boundaryCheck(a_MBInterval_H, upBound, lowBound);
EIS_LOG("final MBInt_H(0x%x)", (a_MBInterval_H & 0xFFF));
ISP_WRITE_BITS(pEis, CAM_EIS_MB_INTERVAL, MB_INTERVAL_H,(a_MBInterval_H & 0xFFF));
}
}
/*******************************************************************************
* 15004DD4, CAM_EIS_MB_INTERVAL
********************************************************************************/
MVOID EisDrv::setMBInterval_V(MINT32 a_MBInterval_V)
{
EIS_LOG("V(%d)", a_MBInterval_V);
MBOOL errFlag = MFALSE;
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
MINT32 upBound,lowBound;
MINT32 tempHeight = ISP_READ_BITS(pEis, CAM_EIS_IMAGE_CTRL, HEIGHT);
MINT32 tempFLOffset_V = Complement2(ISP_READ_BITS(pEis, CAM_EIS_FL_OFFSET, FL_OFFSET_V), 12);
MINT32 tempDSRatio_V = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_V);
MINT32 tempRPNum_V = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VRP);
MINT32 tempMBNum_V = ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VWIN);
MINT32 tempMBOffset_V = Complement2(ISP_READ_BITS(pEis, CAM_EIS_MB_OFFSET, MB_OFFSET_V), 12);
//====== Value Checking ======
if(mImgH != tempHeight)
{
EIS_ERR("ISP read HEIGHT fail : tempHeight(%d),mImgH(%d)", tempHeight, mImgH);
tempHeight = mImgH;
errFlag = MTRUE;
}
if(mFLOfset_V != tempFLOffset_V)
{
EIS_ERR("ISP read FL_OFFSET_V fail : tempFLOffset_V(%d),mFLOfset_V(%d)", tempFLOffset_V, mFLOfset_V);
tempFLOffset_V = mFLOfset_V;
errFlag = MTRUE;
}
if(mDSRatio != tempDSRatio_V)
{
EIS_ERR("ISP read PREP_DS_IIR_V fail : tempDSRatio_V(%d),mDSRatio(%d)", tempDSRatio_V, mDSRatio);
tempDSRatio_V = mDSRatio;
errFlag = MTRUE;
}
if(mRPNum_V != tempRPNum_V)
{
EIS_ERR("ISP read ME_NUM_VRP fail : tempRPNum_V(%d),mRPNum_V(%d)", tempRPNum_V, mRPNum_V);
tempRPNum_V = mRPNum_V;
errFlag = MTRUE;
}
if(mMBNum_V != tempMBNum_V)
{
EIS_ERR("ISP read ME_NUM_VWIN fail : tempMBNum_H(%d),mMBNum_V(%d)", tempMBNum_V, mMBNum_V);
tempMBNum_V = mMBNum_V;
errFlag = MTRUE;
}
if(mMBOfset_V != tempMBOffset_V)
{
EIS_ERR("ISP read MB_OFFSET_V fail : tempMBOffset_V(%d),mMBOfset_V(%d)", tempMBOffset_V, mMBOfset_V);
tempMBOffset_V = mMBOfset_V;
errFlag = MTRUE;
}
if(errFlag == MFALSE)
{
mConfigFail |= MFALSE;
}
else
{
mConfigFail |= MTRUE;
}
//====== Check Limitation ======
// low bound
lowBound = (tempRPNum_V + 1) * 16 + 1;
// up bound
if(tempFLOffset_V > 0)
{
upBound = ((tempHeight / tempDSRatio_V) - tempMBOffset_V - tempRPNum_V*16 - tempFLOffset_V) / (tempMBNum_V-1);
}
else
{
upBound = ((tempHeight / tempDSRatio_V) - tempMBOffset_V - tempRPNum_V*16 - 1) / (tempMBNum_V-1);
}
EIS_LOG("H(%d),FLOfs_V(%d),DSRat_V(%d),RPNum_V(%d),MBNum_V(%d),MBOfs_V(%d)"
,tempHeight,tempFLOffset_V,tempDSRatio_V,tempRPNum_V,tempMBNum_V,tempMBOffset_V);
EIS_LOG("upB(%d), lowB(%d)", upBound, lowBound);
if(upBound < lowBound)
{
EIS_ERR("wrong boundary");
}
else
{
boundaryCheck(a_MBInterval_V, upBound, lowBound);
EIS_LOG("final MBInt_V(0x%x)", (a_MBInterval_V & 0xFFF));
ISP_WRITE_BITS(pEis, CAM_EIS_MB_INTERVAL, MB_INTERVAL_V, (a_MBInterval_V & 0xFFF));
}
}
/*******************************************************************************
* 15004DE0, CAM_EIS_IMAGE_CTRL
********************************************************************************/
MVOID EisDrv::setEISImage(MINT32 a_ImgWidth, MINT32 a_ImgHeight)
{
EIS_LOG("W(%d),H(%d)",(a_ImgWidth & 0x1FFF),(a_ImgHeight & 0x1FFF));
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
ISP_WRITE_BITS(pEis, CAM_EIS_IMAGE_CTRL, WIDTH,(a_ImgWidth & 0x1FFF));
ISP_WRITE_BITS(pEis, CAM_EIS_IMAGE_CTRL, HEIGHT,(a_ImgHeight & 0x1FFF));
mImgW = (a_ImgWidth & 0x1FFF);
mImgH = (a_ImgHeight & 0x1FFF);
}
/*******************************************************************************
*
********************************************************************************/
MVOID EisDrv::setEISOAddr()
{
EIS_LOG("VA(0x%x),PA(0x%x)",mEisIMemInfo.virtAddr, mEisIMemInfo.phyAddr);
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
ISP_WRITE_REG(pEis, CAM_EISO_BASE_ADDR, mEisIMemInfo.phyAddr);
ISP_WRITE_BITS(pEis, CAM_EISO_XSIZE, XSIZE, EIS_MEMORY_SIZE-1); // fix number : 0x197(407)
}
/*******************************************************************************
*
********************************************************************************/
MVOID EisDrv::getFLOffsetMax(MINT32 &a_FLOffsetMax_H, MINT32 &a_FLOffsetMax_V)
{
a_FLOffsetMax_H = mFLOffsetMax_H;
a_FLOffsetMax_V = mFLOffsetMax_V;
EIS_LOG("Max_H(%d),Max_V(%d)", a_FLOffsetMax_H, a_FLOffsetMax_V);
}
/*******************************************************************************
*
********************************************************************************/
MVOID EisDrv::getDSRatio(MINT32 &a_DS_H, MINT32 &a_DS_V)
{
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
a_DS_H = (MINT32)ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_H);
a_DS_V = (MINT32)ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_V);
EIS_LOG("DS_H(%d),DS_V(%d)",a_DS_H,a_DS_V);
}
/*******************************************************************************
*
********************************************************************************/
MVOID EisDrv::getStatistic(EIS_STATISTIC_T *a_pEIS_Stat)
{
char value[32] = {'\0'};
property_get("debug.eis.dump", value, "0");
g_debugDump = atoi(value);
MUINT32 *pEISOAddr = (MUINT32 *)mEisIMemInfo.virtAddr;
if(g_debugDump == 3)
{
EIS_LOG("+");
EIS_LOG("pEISOAddr(0x%x)",(MUINT32)pEISOAddr);
}
//====== BASE + 0~31 ======
for(MINT32 i = 0; i < EIS_MAX_WIN_NUM; ++i)
{
if(i != 0)
{
pEISOAddr += 2; // 64bits(8bytes)
if(g_debugDump == 3)
{
EIS_LOG("1. i(%d),pEISOAddr(0x%x)",i,(MUINT32)pEISOAddr);
}
}
a_pEIS_Stat->i4LMV_X2[i] = Complement2(*pEISOAddr & 0x1F, 5); //[0:4]
a_pEIS_Stat->i4LMV_Y2[i] = Complement2(((*pEISOAddr & 0x3E0) >> 5), 5); //[5:9]
a_pEIS_Stat->i4SAD[i] = (*pEISOAddr & 0x7FC00) >> 10; //[10:18]
a_pEIS_Stat->i4NewTrust_X[i]= (*pEISOAddr & 0x03F80000) >> 19; //[19:25]
a_pEIS_Stat->i4NewTrust_Y[i]= ((*pEISOAddr & 0xFC000000) >> 26) //[26:32]
+ ((*(pEISOAddr+1) & 0x00000001) << 6);
a_pEIS_Stat->i4LMV_X[i] = Complement2(((*(pEISOAddr + 1) & 0x00003FFE) >> 1), 13); //[33:45] -> [1:13]
a_pEIS_Stat->i4LMV_Y[i] = Complement2(((*(pEISOAddr + 1) & 0x07FFC000) >> 14), 13); //[46:58] -> [14:26]
a_pEIS_Stat->i4SAD2[i] = 0;
a_pEIS_Stat->i4AVG[i] = 0;
}
#if 0
for(MINT32 i = 0; i < 10; ++i)
{
EIS_LOG("EIS[%d]=mv(%d,%d), trust(%d,%d), sad(%d), avg(%d), mv2(%d,%d), sad2(%d)"
, i
, a_pEIS_Stat->i4LMV_X[i], a_pEIS_Stat->i4LMV_Y[i]
, a_pEIS_Stat->i4NewTrust_X[i], a_pEIS_Stat->i4NewTrust_Y[i]
, a_pEIS_Stat->i4SAD[i]
, a_pEIS_Stat->i4AVG[i]
, a_pEIS_Stat->i4LMV_X2[i], a_pEIS_Stat->i4LMV_Y2[i]
, a_pEIS_Stat->i4SAD2[i]
);
}
#endif
#if 0
pEISOAddr = (MUINT32 *)mEisIMemInfo.virtAddr;
//for(MINT32 i = 0; i < 2*EIS_MAX_WIN_NUM; ++i)
for(MINT32 i = 0; i < 10; ++i)
{
EIS_LOG("EIS[%d]=(0x%08x)",i,pEISOAddr[i]);
}
#endif
#if 0
EIS_LOG("LMV");
for(MINT32 i = 0; i < EIS_MAX_WIN_NUM; ++i)
{
EIS_LOG("MB%d%d, LMV_X = %d, LMV_Y = %d",(i/4),(i%4),a_pEIS_Stat->i4LMV_X[i],a_pEIS_Stat->i4LMV_Y[i]);
}
EIS_LOG("LMV_2nd");
for(MINT32 i = 0; i < EIS_MAX_WIN_NUM; ++i)
{
EIS_LOG("MB%d%d, LMV_X2 = %d, LMV_Y2 = %d",(i/4),(i%4),a_pEIS_Stat->i4LMV_X2[i],a_pEIS_Stat->i4LMV_Y2[i]);
}
EIS_LOG("MinSAD");
for(MINT32 i = 0; i < EIS_MAX_WIN_NUM; ++i)
{
EIS_LOG("MB%d%d, MinSAD = %d",(i/4),(i%4),a_pEIS_Stat->i4SAD[i]);
}
EIS_LOG("MinSAD_2nd");
for(MINT32 i = 0; i < EIS_MAX_WIN_NUM; ++i)
{
EIS_LOG("MB%d%d, MinSAD2 = %d",(i/4),(i%4),a_pEIS_Stat->i4SAD2[i]);
}
EIS_LOG("AvgSAD");
for(MINT32 i = 0; i < EIS_MAX_WIN_NUM; ++i)
{
EIS_LOG("MB%d%d, AvgSAD = %d",(i/4),(i%4),a_pEIS_Stat->i4AVG[i]);
}
EIS_LOG("NewTrust");
for(MINT32 i = 0; i < EIS_MAX_WIN_NUM; ++i)
{
EIS_LOG("MB%d%d, NewTrust_X = %d, NewTrust_Y = %d",(i/4),(i%4),a_pEIS_Stat->i4NewTrust_X[i],a_pEIS_Stat->i4NewTrust_Y[i]);
}
dumpReg();
#endif
if(g_debugDump == 3)
{
EIS_LOG("-");
}
}
/*******************************************************************************
*
********************************************************************************/
MBOOL EisDrv::configStatus()
{
return mConfigFail;
}
/*******************************************************************************
*
********************************************************************************/
MVOID EisDrv::resetConfigStatus()
{
mConfigFail = MFALSE;
EIS_LOG("mConfigFail(%d)",mConfigFail);
}
/*******************************************************************************
*
********************************************************************************/
MVOID EisDrv::dumpReg()
{
EIS_LOG("+");
isp_reg_t *pEis = (isp_reg_t *)mISPRegAddr;
EIS_LOG("ESFKO_EN(0x%x)",ISP_READ_BITS(pEis, CAM_CTL_DMA_EN, ESFKO_EN));
EIS_LOG("SGG_EN(0x%x)",ISP_READ_BITS(pEis, CAM_CTL_EN1, SGG_EN));
EIS_LOG("SGG_PGN(0x%x)",ISP_READ_REG(pEis, CAM_SGG_PGN));
EIS_LOG("SGG_GMR1(0x%x)",ISP_READ_BITS(pEis, CAM_SGG_GMR, SGG_GMR1));
EIS_LOG("SGG_GMR2(0x%x)",ISP_READ_BITS(pEis, CAM_SGG_GMR, SGG_GMR2));
EIS_LOG("SGG_GMR3(0x%x)",ISP_READ_BITS(pEis, CAM_SGG_GMR, SGG_GMR3));
EIS_LOG("EISO(0x%x)",ISP_READ_REG(pEis, CAM_EISO_BASE_ADDR));
EIS_LOG("EIS_EN(0x%x)",ISP_READ_BITS(pEis, CAM_CTL_EN2, EIS_EN));
EIS_LOG("EIS_RAW_SEL(0x%x)",ISP_READ_BITS(pEis, CAM_CTL_SEL, EIS_RAW_SEL));
EIS_LOG("EIS_DB_LD_SEL(0x%x)",ISP_READ_BITS(pEis, CAM_CTL_SPARE3, EIS_DB_LD_SEL));
EIS_LOG("DS_IIR_H(0x%x),DS_IIR_V(0x%x),NumRP_H(0x%x),NumRP_V(0x%x),CLIP(0x%x),KNEE(0x%x),NumMB_H(0x%x),NumMB_V(0x%x)",
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_H),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, PREP_DS_IIR_V),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HRP),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VRP),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_AD_CLIP),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_AD_KNEE),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_HWIN),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL1, ME_NUM_VWIN));
EIS_LOG("GAIN_H(0x%x),GAIN_IIR_H(0x%x),GAIN_IIR_V(0x%x),GAIN_FIR_H(0x%x),WRP_EN(0x%x),FIRST_FRM(0x%x)",
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_H),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_IIR_H),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_GAIN_IIR_V),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, PREP_FIR_H),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, EIS_WRP_EN),
ISP_READ_BITS(pEis, CAM_EIS_PREP_ME_CTRL2, EIS_FIRST_FRM));
EIS_LOG("X_CENTER(0x%x),X_SURROUND(0x%x),Y_CENTER(0x%x),Y_SURROUND(0x%x)",
ISP_READ_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_X_CENTER),
ISP_READ_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_X_SOURROUND),
ISP_READ_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_Y_CENTER),
ISP_READ_BITS(pEis, CAM_EIS_LMV_TH, LMV_TH_Y_SURROUND));
EIS_LOG("FL_OFFSET_H(0x%x),FL_OFFSET_V(0x%x)",
Complement2(ISP_READ_BITS(pEis, CAM_EIS_FL_OFFSET, FL_OFFSET_H), 12),
Complement2(ISP_READ_BITS(pEis, CAM_EIS_FL_OFFSET, FL_OFFSET_V), 12));
EIS_LOG("MB_OFFSET_H(0x%x),MB_OFFSET_V(0x%x)",
Complement2(ISP_READ_BITS(pEis, CAM_EIS_MB_OFFSET, MB_OFFSET_H), 12),
Complement2(ISP_READ_BITS(pEis, CAM_EIS_MB_OFFSET, MB_OFFSET_V), 12));
EIS_LOG("MB_INTERVAL_H(0x%x),MB_INTERVAL_V(0x%x)",
Complement2(ISP_READ_BITS(pEis, CAM_EIS_MB_INTERVAL, MB_INTERVAL_H), 12),
Complement2(ISP_READ_BITS(pEis, CAM_EIS_MB_INTERVAL, MB_INTERVAL_V), 12));
EIS_LOG("WIDTH(0x%x),HEIGHT(0x%x),PIPE_MODE(0x%x)",
ISP_READ_BITS(pEis, CAM_EIS_IMAGE_CTRL, WIDTH),
ISP_READ_BITS(pEis, CAM_EIS_IMAGE_CTRL, HEIGHT),
ISP_READ_BITS(pEis, CAM_EIS_IMAGE_CTRL, PIPE_MODE));
EIS_LOG("-");
}
/*******************************************************************************
*
********************************************************************************/
MINT32 EisDrv::max(MINT32 a, MINT32 b)
{
if(a >= b)
{
return a;
}
else
{
return b;
}
}
/*******************************************************************************
*
********************************************************************************/
MINT32 EisDrv::Complement2(MUINT32 Vlu, MUINT32 Digit)
{
MINT32 Result;
if (((Vlu >> (Digit - 1)) & 0x1) == 1) // negative
{
Result = 0 - (MINT32)((~Vlu + 1) & ((1 << Digit) - 1));
}
else
{
Result = (MINT32)(Vlu & ((1 << Digit) - 1));
}
return Result;
}
/*******************************************************************************
*
*******************************************************************************/
MVOID EisDrv::boundaryCheck(MINT32 &a_input, MINT32 upBound, MINT32 lowBound)
{
if(a_input > upBound)
{
a_input = upBound;
}
if(a_input < lowBound)
{
a_input = lowBound;
}
}
| 32.406367 | 141 | 0.541924 | [
"object"
] |
50a9c13a74d76a601ac8ea6aeef6ed6e4550ee80 | 37,996 | cpp | C++ | external/cfmesh/meshLibrary/utilities/octrees/meshOctree/meshOctreeAddressing/meshOctreeAddressingCreation.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/cfmesh/meshLibrary/utilities/octrees/meshOctree/meshOctreeAddressing/meshOctreeAddressingCreation.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | external/cfmesh/meshLibrary/utilities/octrees/meshOctree/meshOctreeAddressing/meshOctreeAddressingCreation.cpp | MrAwesomeRocks/caelus-cml | 55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7 | [
"mpich2"
] | null | null | null | /*---------------------------------------------------------------------------*\
Copyright (C) Creative Fields, Ltd.
-------------------------------------------------------------------------------
License
This file is part of cfMesh.
cfMesh 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.
cfMesh 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 cfMesh. If not, see <http://www.gnu.org/licenses/>.
Author: Franjo Juretic (franjo.juretic@c-fields.com)
\*---------------------------------------------------------------------------*/
#include "meshOctreeAddressing.hpp"
#include "helperFunctions.hpp"
#include "VRWGraphSMPModifier.hpp"
#include "demandDrivenData.hpp"
#include "meshOctree.hpp"
#include "labelLongList.hpp"
#include "triSurf.hpp"
# ifdef USE_OMP
#include <omp.h>
# endif
//#define DEBUGVrt
# ifdef DEBUGVrt
#include "OFstream.hpp"
# endif
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace CML
{
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
# ifdef DEBUGVrt
void writeOctreeToVTK
(
const fileName& fName,
const meshOctree& octree,
const List<direction>& boxTypes,
const direction bType
)
{
OFstream file(fName);
//- write the header
file << "# vtk DataFile Version 3.0\n";
file << "vtk output\n";
file << "ASCII\n";
file << "DATASET UNSTRUCTURED_GRID\n";
label nBoxes(0);
forAll(boxTypes, leafI)
if( boxTypes[leafI] & bType )
++nBoxes;
//- write points
file << "POINTS " << 8*nBoxes << " float\n";
forAll(boxTypes, leafI)
{
if( boxTypes[leafI] & bType )
{
FixedList<point, 8> vertices;
octree.returnLeaf(leafI).vertices(octree.rootBox(), vertices);
forAll(vertices, vI)
{
const point& p = vertices[vI];
file << p.x() << ' ' << p.y() << ' ' << p.z() << nl;
}
}
}
//- write boxes
file << "\nCELLS " << nBoxes
<< " " << 9 * nBoxes << nl;
nBoxes = 0;
forAll(boxTypes, leafI)
{
if( boxTypes[leafI] & bType )
{
const label start = 8 * nBoxes;
file << 8 << " " << start << " " << start+1
<< " " << start+3 << " " << start+2
<< " " << start+4 << " " << start+5
<< " " << start+7 << " " << start+6 << nl;
++nBoxes;
}
}
file << nl;
//- write cell types
file << "CELL_TYPES " << nBoxes << nl;
for(label i=0;i<nBoxes;++i)
file << 12 << nl;
file << nl;
}
# endif
void meshOctreeAddressing::createOctreePoints() const
{
const VRWGraph& nodeLabels = this->nodeLabels();
const boundBox& rootBox = octree_.rootBox();
octreePointsPtr_ = new pointField(nNodes_);
pointField& octreePoints = *octreePointsPtr_;
const label nLeaves = nodeLabels.size();
# ifdef USE_OMP
# pragma omp parallel for schedule(guided, 100)
# endif
for(label cubeI=0;cubeI<nLeaves;++cubeI)
{
if( nodeLabels.sizeOfRow(cubeI) == 0 )
continue;
FixedList<point, 8> vertices;
const meshOctreeCubeBasic& oc = octree_.returnLeaf(cubeI);
oc.vertices(rootBox, vertices);
forAllRow(nodeLabels, cubeI, nI)
{
const label nodeI = nodeLabels(cubeI, nI);
octreePoints[nodeI] = vertices[nI];
}
}
}
void meshOctreeAddressing::createNodeLabels() const
{
const List<direction>& boxType = this->boxType();
nodeLabelsPtr_ = new VRWGraph(octree_.numberOfLeaves());
VRWGraph& nodeLabels = *nodeLabelsPtr_;
//- allocate storage for node labels
forAll(nodeLabels, leafI)
{
if( boxType[leafI] )
{
nodeLabels.setRowSize(leafI, 8);
forAllRow(nodeLabels, leafI, i)
nodeLabels(leafI, i) = -1;
}
}
//- start creating node labels
nNodes_ = 0;
DynList<label> numLocalNodes;
# ifdef USE_OMP
# pragma omp parallel
# endif
{
# ifdef USE_OMP
const label nThreads = omp_get_num_threads();
const label threadI = omp_get_thread_num();
# else
const label nThreads = 1;
const label threadI = 0;
# endif
# ifdef USE_OMP
# pragma omp master
# endif
numLocalNodes.setSize(nThreads);
# ifdef USE_OMP
# pragma omp barrier
# endif
//- count the number of nodes local to each process
label& nLocalNodes = numLocalNodes[threadI];
nLocalNodes = 0;
# ifdef USE_OMP
# pragma omp for schedule(static, 100)
# endif
forAll(nodeLabels, leafI)
{
forAllRow(nodeLabels, leafI, nI)
{
if( nodeLabels(leafI, nI) != -1 )
continue;
FixedList<label, 8> pLeaves;
octree_.findLeavesForCubeVertex(leafI, nI, pLeaves);
FixedList<bool, 8> validLeaf(true);
label minLeaf(leafI);
forAll(pLeaves, plI)
{
if( pLeaves[plI] > -1 )
{
for(label i=plI+1;i<8;++i)
if( pLeaves[plI] == pLeaves[i] )
{
validLeaf[plI] = false;
validLeaf[i] = false;
}
if( !boxType[pLeaves[plI]] )
{
validLeaf[plI] = false;
pLeaves[plI] = -1;
}
if( validLeaf[plI] )
minLeaf = CML::min(minLeaf, pLeaves[plI]);
}
else
{
validLeaf[plI] = false;
}
}
if( (minLeaf == leafI) && validLeaf[7-nI] )
{
forAll(pLeaves, plI)
if( validLeaf[plI] )
{
//- set node labels to -2 not to repeat searches
nodeLabels(pLeaves[plI], (7-plI)) = -2;
}
++nLocalNodes;
}
}
}
//- set start node for each process
# ifdef USE_OMP
# pragma omp barrier
# endif
label startNode(0);
for(label i=0;i<threadI;++i)
startNode += numLocalNodes[i];
//- start creating node labels
# ifdef USE_OMP
# pragma omp for schedule(static, 100)
# endif
forAll(nodeLabels, leafI)
{
forAllRow(nodeLabels, leafI, nI)
{
if( nodeLabels(leafI, nI) >= 0 )
continue;
FixedList<label, 8> pLeaves;
octree_.findLeavesForCubeVertex(leafI, nI, pLeaves);
FixedList<bool, 8> validLeaf(true);
label minLeaf(leafI);
forAll(pLeaves, plI)
{
if( pLeaves[plI] > -1 )
{
for(label i=plI+1;i<8;++i)
if( pLeaves[plI] == pLeaves[i] )
{
validLeaf[plI] = false;
validLeaf[i] = false;
}
if( !boxType[pLeaves[plI]] )
{
validLeaf[plI] = false;
pLeaves[plI] = -1;
}
if( validLeaf[plI] )
minLeaf = CML::min(minLeaf, pLeaves[plI]);
}
else
{
validLeaf[plI] = false;
}
}
if( (minLeaf == leafI) && validLeaf[7-nI] )
{
forAll(pLeaves, plI)
if( validLeaf[plI] )
{
//- store the vertex at the corresponding
//- location in the cube
nodeLabels(pLeaves[plI], (7-plI)) = startNode;
}
//- store vertex label
++startNode;
}
}
}
//- set the number of nodes
# ifdef USE_OMP
# pragma omp critical
# endif
{
nNodes_ = CML::max(nNodes_, startNode);
}
}
# ifdef DEBUGVrt
List<direction> badLeaves(nodeLabels.size(), direction(0));
forAll(nodeLabels, leafI)
forAllRow(nodeLabels, leafI, i)
if( nodeLabels(leafI, i) < 0 )
badLeaves[leafI] |= 1;
writeOctreeToVTK("badLeaves.vtk", octree_, badLeaves, 1);
writeOctreeToVTK("meshCells.vtk", octree_, boxType, MESHCELL);
writeOctreeToVTK("boundaryCells.vtk", octree_, boxType, BOUNDARY);
Info << "Checking for existence of negative node labels" << endl;
forAll(nodeLabels, leafI)
{
forAllRow(nodeLabels, leafI, nI)
{
if( nodeLabels(leafI, nI) < 0 )
{
FixedList<label, 8> pLeaves;
octree_.findLeavesForCubeVertex(leafI, nI, pLeaves);
FixedList<bool, 8> validLeaf(true);
label minLeaf(leafI);
forAll(pLeaves, plI)
{
if( pLeaves[plI] > -1 )
{
for(label i=plI+1;i<8;++i)
if( pLeaves[plI] == pLeaves[i] )
{
validLeaf[plI] = false;
validLeaf[i] = false;
}
if( !boxType[pLeaves[plI]] )
{
validLeaf[plI] = false;
pLeaves[plI] = -1;
}
if( validLeaf[plI] )
minLeaf = CML::min(minLeaf, pLeaves[plI]);
}
else
{
validLeaf[plI] = false;
}
}
Info << "Min leaf " << minLeaf << endl;
Info << "Valid leaf " << validLeaf << endl;
Info << "pLeaves " << pLeaves << endl;
Info << "Node position " << nI << endl;
Info << "1.Leaf " << leafI << " node labels "
<< nodeLabels[leafI] << endl;
forAll(validLeaf, i)
if( validLeaf[i] )
Info << "Leaf at position " << i << " has node labels "
<< nodeLabels[pLeaves[i]]
<< " at level "
<< octree_.returnLeaf(pLeaves[i]).level() << endl;
}
}
}
# endif
}
void meshOctreeAddressing::createNodeLeaves() const
{
const List<direction>& boxType = this->boxType();
const VRWGraph& nodeLabels = this->nodeLabels();
//- allocate nodeLeavesPtr_
nodeLeavesPtr_ = new FRWGraph<label, 8>(nNodes_);
FRWGraph<label, 8>& nodeLeaves = *nodeLeavesPtr_;
boolList storedNode(nNodes_, false);
# ifdef USE_OMP
# pragma omp parallel for schedule(dynamic, 100)
# endif
forAll(nodeLabels, leafI)
{
forAllRow(nodeLabels, leafI, nI)
{
const label nodeI = nodeLabels(leafI, nI);
if( storedNode[nodeI] )
continue;
storedNode[nodeI] = true;
FixedList<label, 8> pLeaves;
octree_.findLeavesForCubeVertex(leafI, nI, pLeaves);
forAll(pLeaves, plI)
{
if( pLeaves[plI] < 0 )
continue;
if( !boxType[pLeaves[plI]] )
pLeaves[plI] = -1;
}
nodeLeaves.setRow(nodeI, pLeaves);
}
}
}
void meshOctreeAddressing::findUsedBoxes() const
{
boxTypePtr_ = new List<direction>(octree_.numberOfLeaves(), NONE);
List<direction>& boxType = *boxTypePtr_;
# ifdef USE_OMP
# pragma omp parallel for schedule(dynamic, 40)
# endif
forAll(boxType, leafI)
{
const meshOctreeCubeBasic& leaf = octree_.returnLeaf(leafI);
if(
!octree_.hasContainedTriangles(leafI) &&
!octree_.hasContainedEdges(leafI) &&
(leaf.cubeType() & meshOctreeCubeBasic::INSIDE)
)
boxType[leafI] |= MESHCELL;
}
if( meshDict_.found("nonManifoldMeshing") )
{
const bool nonManifoldMesh
(
readBool(meshDict_.lookup("nonManifoldMeshing"))
);
if( nonManifoldMesh )
{
# ifdef USE_OMP
# pragma omp parallel for schedule(dynamic, 40)
# endif
forAll(boxType, leafI)
{
const meshOctreeCubeBasic& leaf = octree_.returnLeaf(leafI);
if( leaf.cubeType() & meshOctreeCubeBasic::UNKNOWN )
boxType[leafI] |= MESHCELL;
}
}
}
if( useDATABoxes_ )
{
Info << "Using DATA boxes" << endl;
forAll(boxType, leafI)
{
if(
octree_.hasContainedTriangles(leafI) ||
octree_.hasContainedEdges(leafI)
)
boxType[leafI] |= MESHCELL;
}
//- do not use boxes intersecting given patches
if( meshDict_.found("removeCellsIntersectingPatches") )
{
wordHashSet patchesToRemove;
if( meshDict_.isDict("removeCellsIntersectingPatches") )
{
const dictionary& dict =
meshDict_.subDict("removeCellsIntersectingPatches");
const wordList patchNames = dict.toc();
forAll(patchNames, patchI)
patchesToRemove.insert(patchNames[patchI]);
}
else
{
wordHashSet patchesToRemoveCopy
(
meshDict_.lookup("removeCellsIntersectingPatches")
);
patchesToRemove.transfer(patchesToRemoveCopy);
}
const triSurf& ts = octree_.surface();
boolList removeFacets(ts.size(), false);
//- remove facets in patches
forAllConstIter(HashSet<word>, patchesToRemove, it)
{
const labelList matchedPatches = ts.findPatches(it.key());
boolList activePatch(ts.patches().size(), false);
forAll(matchedPatches, ptchI)
activePatch[matchedPatches[ptchI]] = true;
forAll(ts, triI)
{
if( activePatch[ts[triI].region()] )
removeFacets[triI] = true;
}
}
//- remove facets in subsets
forAllConstIter(HashSet<word>, patchesToRemove, it)
{
const label subsetID = ts.facetSubsetIndex(it.key());
if( subsetID >= 0 )
{
labelLongList facets;
ts.facetsInSubset(subsetID, facets);
forAll(facets, i)
removeFacets[facets[i]] = true;
}
}
//- set BOUNDARY flag to boxes intersected by the given facets
DynList<label> containedTriangles;
forAll(boxType, leafI)
{
octree_.containedTriangles(leafI, containedTriangles);
forAll(containedTriangles, i)
{
if( removeFacets[containedTriangles[i]] )
{
boxType[leafI] = NONE;
}
}
}
}
}
else if( meshDict_.found("keepCellsIntersectingPatches") )
{
wordHashSet patchesToKeep;
if( meshDict_.isDict("keepCellsIntersectingPatches") )
{
const dictionary& dict =
meshDict_.subDict("keepCellsIntersectingPatches");
const wordList patchNames = dict.toc();
forAll(patchNames, patchI)
patchesToKeep.insert(patchNames[patchI]);
}
else
{
wordHashSet patchesToKeepCopy
(
meshDict_.lookup("keepCellsIntersectingPatches")
);
patchesToKeep.transfer(patchesToKeepCopy);
}
const triSurf& ts = octree_.surface();
boolList keepFacets(ts.size(), false);
//- keep facets in patches
forAllConstIter(HashSet<word>, patchesToKeep, it)
{
const labelList matchedPatches = ts.findPatches(it.key());
boolList activePatch(ts.patches().size(), false);
forAll(matchedPatches, ptchI)
activePatch[matchedPatches[ptchI]] = true;
forAll(ts, triI)
{
if( activePatch[ts[triI].region()] )
keepFacets[triI] = true;
}
}
//- keep facets in subsets
forAllConstIter(wordHashSet, patchesToKeep, it)
{
const label subsetID = ts.facetSubsetIndex(it.key());
if( subsetID >= 0 )
{
labelLongList facets;
ts.facetsInSubset(subsetID, facets);
forAll(facets, i)
keepFacets[facets[i]] = true;
}
}
//- set MESHCELL flag to boxes intersected by the given facets
DynList<label> containedTriangles;
forAll(boxType, leafI)
{
octree_.containedTriangles(leafI, containedTriangles);
forAll(containedTriangles, i)
{
if( keepFacets[containedTriangles[i]] )
{
boxType[leafI] = MESHCELL;
}
}
}
}
//- set BOUNDARY flag to boxes which do not have a MESHCELL flag
DynList<label> neighs;
# ifdef USE_OMP
# pragma omp parallel for if( boxType.size() > 1000 ) \
private(neighs) schedule(dynamic, 20)
# endif
forAll(boxType, leafI)
{
if( boxType[leafI] & MESHCELL )
{
for(label i=0;i<6;++i)
{
neighs.clear();
octree_.findNeighboursInDirection(leafI, i, neighs);
forAll(neighs, neiI)
{
const label neiLabel = neighs[neiI];
if( neiLabel < 0 )
continue;
if( !(boxType[neiLabel] & MESHCELL) )
boxType[neiLabel] = BOUNDARY;
}
}
}
}
if( Pstream::parRun() )
{
//- make sure that all processors have the same information
//- about BOUNDARY boxes
const labelLongList& globalLeafLabel = this->globalLeafLabel();
const VRWGraph& leafAtProcs = this->leafAtProcs();
const Map<label>& globalLeafToLocal =
this->globalToLocalLeafAddressing();
std::map<label, labelLongList> exchangeData;
forAll(octree_.neiProcs(), procI)
exchangeData.insert
(
std::make_pair
(
octree_.neiProcs()[procI],
labelLongList()
)
);
forAllConstIter(Map<label>, globalLeafToLocal, iter)
{
const label leafI = iter();
if( boxType[leafI] & BOUNDARY )
{
forAllRow(leafAtProcs, leafI, procI)
{
const label neiProc = leafAtProcs(leafI, procI);
if( neiProc == Pstream::myProcNo() )
continue;
exchangeData[neiProc].append(globalLeafLabel[leafI]);
}
}
}
labelLongList receivedData;
help::exchangeMap(exchangeData, receivedData);
forAll(receivedData, i)
boxType[globalLeafToLocal[receivedData[i]]] = BOUNDARY;
}
}
void meshOctreeAddressing::calculateNodeType() const
{
const FRWGraph<label, 8>& nodeLeaves = this->nodeLeaves();
nodeTypePtr_ = new List<direction>(nNodes_, NONE);
List<direction>& nodeType = *nodeTypePtr_;
# ifdef USE_OMP
# pragma omp parallel for schedule(static, 1)
# endif
forAll(nodeLeaves, nodeI)
{
forAllRow(nodeLeaves, nodeI, nlI)
{
const label leafI = nodeLeaves(nodeI, nlI);
if( leafI == -1 )
continue;
const meshOctreeCubeBasic& oc = octree_.returnLeaf(leafI);
if(
(oc.cubeType() & meshOctreeCubeBasic::OUTSIDE) ||
(oc.cubeType() & meshOctreeCubeBasic::UNKNOWN)
)
{
nodeType[nodeI] |= OUTERNODE;
break;
}
else if(
!octree_.hasContainedTriangles(leafI) &&
(oc.cubeType() & meshOctreeCubeBasic::INSIDE)
)
{
nodeType[nodeI] |= INNERNODE;
break;
}
}
}
}
void meshOctreeAddressing::createOctreeFaces() const
{
octreeFacesPtr_ = new VRWGraph();
octreeFacesOwnersPtr_ = new labelLongList();
octreeFacesNeighboursPtr_ = new labelLongList();
const VRWGraph& nodeLabels = this->nodeLabels();
const List<direction>& boxType = this->boxType();
this->nodeLeaves();
label nFaces(0);
labelList rowSizes, chunkSizes;
# ifdef USE_OMP
# pragma omp parallel
# endif
{
//- faces are created and stored into helper arrays, and each thread
//- allocates its own graph for storing faces. The faces are generated
//- by dividing the octree leaves into chunks, and distributing these
//- chunks over the threads. There are four chunks per each thread to
//- improve load balancing. The number of faces generated in each chunk
//- is stored and later in used to store the faces into the octree faces
//- graph in the correct order
VRWGraph helperFaces;
labelLongList helperOwner, helperNeighbour;
# ifdef USE_OMP
const label nThreads = omp_get_num_threads();
const label threadI = omp_get_thread_num();
const label nChunks = 4 * omp_get_num_threads();
const label chunkSize = boxType.size() / nChunks + 1;
# else
const label nThreads(1);
const label threadI(0);
const label nChunks(1);
const label chunkSize = boxType.size();
# endif
# ifdef USE_OMP
# pragma omp master
# endif
{
chunkSizes.setSize(nChunks);
chunkSizes = 0;
}
# ifdef USE_OMP
# pragma omp barrier
# endif
for
(
label chunkI=threadI;
chunkI<nChunks;
chunkI+=nThreads
)
{
const label start = chunkSize * chunkI;
const label end = CML::min(start+chunkSize, boxType.size());
const label nBefore = helperFaces.size();
for(label leafI=start;leafI<end;++leafI)
{
const meshOctreeCubeBasic& oc = octree_.returnLeaf(leafI);
if( boxType[leafI] & MESHCELL )
{
FixedList<label, 12> edgeCentreLabel(-1);
for(label i=0;i<12;++i)
edgeCentreLabel[i] = findEdgeCentre(leafI, i);
for(label fI=0;fI<6;++fI)
{
DynList<label> neighbours;
octree_.findNeighboursInDirection
(
leafI,
fI,
neighbours
);
if( neighbours.size() != 1 )
continue;
const label nei = neighbours[0];
//- stop if the neighbour is on other processor
if( nei == meshOctreeCubeBasic::OTHERPROC )
continue;
//- create face
DynList<label, 8> f;
for(label pI=0;pI<4;++pI)
{
const label nI =
meshOctreeCubeCoordinates::faceNodes_[fI][pI];
const label feI =
meshOctreeCubeCoordinates::faceEdges_[fI][pI];
f.append(nodeLabels(leafI, nI));
if( edgeCentreLabel[feI] != -1 )
f.append(edgeCentreLabel[feI]);
}
if( nei < 0 )
{
//- face is at the boundary of the octree
helperFaces.appendList(f);
helperOwner.append(leafI);
helperNeighbour.append(-1);
}
else if( boxType[nei] & MESHCELL )
{
//- face is an internal face
if( nei > leafI )
{
helperFaces.appendList(f);
helperOwner.append(leafI);
helperNeighbour.append(nei);
}
else if
(
octree_.returnLeaf(nei).level() < oc.level()
)
{
//- append a reversed face
label i(1);
for(label j=f.size()-1;j>i;--j)
{
const label add = f[j];
f[j] = f[i];
f[i] = add;
++i;
}
helperFaces.appendList(f);
helperOwner.append(nei);
helperNeighbour.append(leafI);
}
}
else if( boxType[nei] & BOUNDARY )
{
//- face is at the boundary of the mesh cells
helperFaces.appendList(f);
helperOwner.append(leafI);
helperNeighbour.append(nei);
}
}
}
else if( boxType[leafI] & BOUNDARY )
{
for(label fI=0;fI<6;++fI)
{
DynList<label> neighbours;
octree_.findNeighboursInDirection
(
leafI,
fI,
neighbours
);
if( neighbours.size() != 1 )
continue;
const label nei = neighbours[0];
if( nei < 0 )
continue;
if(
(boxType[nei] & MESHCELL) &&
(octree_.returnLeaf(nei).level() < oc.level())
)
{
//- add a boundary face
const label* fNodes =
meshOctreeCubeCoordinates::faceNodes_[fI];
face cf(4);
for(label i=0;i<4;++i)
{
cf[i] = nodeLabels(leafI, fNodes[i]);
}
helperFaces.appendList(cf.reverseFace());
helperOwner.append(nei);
helperNeighbour.append(leafI);
}
}
}
}
//- store the size of this chunk
chunkSizes[chunkI] = helperFaces.size() - nBefore;
}
//- set the sizes of faces graph
# ifdef USE_OMP
# pragma omp critical
# endif
nFaces += helperFaces.size();
# ifdef USE_OMP
# pragma omp barrier
# pragma omp master
# endif
{
rowSizes.setSize(nFaces);
octreeFacesPtr_->setSize(nFaces);
octreeFacesOwnersPtr_->setSize(nFaces);
octreeFacesNeighboursPtr_->setSize(nFaces);
}
# ifdef USE_OMP
# pragma omp barrier
# endif
//- set the size of face graph rows and copy owners and neighbours
for
(
label chunkI=threadI;
chunkI<nChunks;
chunkI+=nThreads
)
{
label start(0), localStart(0);
for(label i=0;i<chunkI;++i)
start += chunkSizes[i];
for(label i=threadI;i<chunkI;i+=nThreads)
localStart += chunkSizes[i];
for(label faceI=0;faceI<chunkSizes[chunkI];++faceI)
{
octreeFacesOwnersPtr_->operator[](start) =
helperOwner[localStart];
octreeFacesNeighboursPtr_->operator[](start) =
helperNeighbour[localStart];
rowSizes[start++] = helperFaces.sizeOfRow(localStart++);
}
}
# ifdef USE_OMP
# pragma omp barrier
//- set the size of octree faces
# pragma omp master
# endif
VRWGraphSMPModifier(*octreeFacesPtr_).setSizeAndRowSize(rowSizes);
# ifdef USE_OMP
# pragma omp barrier
# endif
//- copy the data into octree faces
for
(
label chunkI=threadI;
chunkI<nChunks;
chunkI+=nThreads
)
{
label start(0), localStart(0);
for(label i=0;i<chunkI;++i)
start += chunkSizes[i];
for(label i=threadI;i<chunkI;i+=nThreads)
localStart += chunkSizes[i];
for(label faceI=0;faceI<chunkSizes[chunkI];++faceI)
{
for(label i=0;i<helperFaces.sizeOfRow(localStart);++i)
octreeFacesPtr_->operator()(start, i) =
helperFaces(localStart, i);
++start;
++localStart;
}
}
}
# ifdef DEBUGVrt
List<vector> sum(octree_.numberOfLeaves(), vector::zero);
for(label faceI=0;faceI<octreeFacesPtr_->size();++faceI)
{
face f(octreeFacesPtr_->sizeOfRow(faceI));
forAll(f, pI)
f[pI] = octreeFacesPtr_->operator()(faceI, pI);
const vector n = f.normal(this->octreePoints());
sum[(*octreeFacesOwnersPtr_)[faceI]] += n;
const label nei = (*octreeFacesNeighboursPtr_)[faceI];
if( nei < 0 )
continue;
sum[nei] -= n;
}
forAll(sum, lfI)
{
if
(
Pstream::parRun() &&
octree_.returnLeaf(lfI).procNo() != Pstream::myProcNo()
)
continue;
if( (boxType[lfI] & MESHCELL) && (mag(sum[lfI]) > SMALL) )
Info << "Leaf " << lfI << " is not closed " << sum[lfI] << endl;
}
# endif
}
void meshOctreeAddressing::calculateLeafFaces() const
{
const labelLongList& owner = octreeFaceOwner();
const labelLongList& neighbour = octreeFaceNeighbour();
leafFacesPtr_ = new VRWGraph(octree_.numberOfLeaves());
VRWGraph& leafFaces = *leafFacesPtr_;
labelList nlf(leafFaces.size(), 0);
forAll(owner, fI)
{
++nlf[owner[fI]];
if( neighbour[fI] < 0 )
continue;
++nlf[neighbour[fI]];
}
forAll(nlf, leafI)
leafFaces.setRowSize(leafI, nlf[leafI]);
nlf = 0;
forAll(owner, fI)
{
leafFaces(owner[fI], nlf[owner[fI]]++) = fI;
if( neighbour[fI] < 0 )
continue;
leafFaces(neighbour[fI], nlf[neighbour[fI]]++) = fI;
}
}
void meshOctreeAddressing::calculateNodeFaces() const
{
const VRWGraph& octreeFaces = this->octreeFaces();
nodeFacesPtr_ = new VRWGraph(numberOfNodes());
VRWGraph& nodeFaces = *nodeFacesPtr_;
VRWGraphSMPModifier(nodeFaces).reverseAddressing(octreeFaces);
nodeFaces.setSize(numberOfNodes());
}
void meshOctreeAddressing::calculateLeafLeaves() const
{
const labelLongList& owner = octreeFaceOwner();
const labelLongList& neighbour = octreeFaceNeighbour();
leafLeavesPtr_ = new VRWGraph(octree_.numberOfLeaves());
VRWGraph& leafLeaves = *leafLeavesPtr_;
labelList nNei(leafLeaves.size(), 0);
forAll(owner, faceI)
{
if( owner[faceI] < 0 )
continue;
if( neighbour[faceI] < 0 )
continue;
++nNei[owner[faceI]];
++nNei[neighbour[faceI]];
}
forAll(nNei, leafI)
leafLeaves.setRowSize(leafI, nNei[leafI]);
nNei = 0;
forAll(owner, faceI)
{
if( owner[faceI] < 0 )
continue;
if( neighbour[faceI] < 0 )
continue;
leafLeaves(owner[faceI], nNei[owner[faceI]]++) = neighbour[faceI];
leafLeaves(neighbour[faceI], nNei[neighbour[faceI]]++) = owner[faceI];
}
}
void meshOctreeAddressing::createOctreeEdges() const
{
const VRWGraph& faces = this->octreeFaces();
//- allocate memory for edges, face-edges addressing
//- and node-edges addressing
octreeEdgesPtr_ = new LongList<edge>();
LongList<edge>& edges = *octreeEdgesPtr_;
faceEdgesPtr_ = new VRWGraph(faces.size());
VRWGraph& faceEdges = *faceEdgesPtr_;
nodeEdgesPtr_ = new VRWGraph();
VRWGraph& nodeEdges = *nodeEdgesPtr_;
nodeEdges.setSizeAndColumnWidth(nNodes_, 6);
forAll(faces, faceI)
{
faceEdges.setRowSize(faceI, faces[faceI].size());
forAllRow(faceEdges, faceI, feI)
faceEdges(faceI, feI) = -1;
}
forAll(faces, faceI)
{
const label nEdges = faces.sizeOfRow(faceI);
for(label eI=0;eI<nEdges;++eI)
{
const edge e
(
faces(faceI, eI),
faces(faceI, (eI+1)%nEdges)
);
label eLabel(-1);
forAllRow(nodeEdges, e.start(), neI)
{
if( edges[nodeEdges(e.start(), neI)] == e )
{
eLabel = nodeEdges(e.start(), neI);
break;
}
}
if( eLabel < 0 )
{
//- append new edge
faceEdges(faceI, eI) = edges.size();
nodeEdges.append(e.start(), edges.size());
nodeEdges.append(e.end(), edges.size());
edges.append(e);
}
else
{
faceEdges(faceI, eI) = eLabel;
}
}
}
}
void meshOctreeAddressing::calculateLeafEdges() const
{
const VRWGraph& edgeLeaves = this->edgeLeaves();
leafEdgesPtr_ = new VRWGraph();
VRWGraph& leafEdges = *leafEdgesPtr_;
VRWGraphSMPModifier(leafEdges).reverseAddressing(edgeLeaves);
leafEdges.setSize(octree_.numberOfLeaves());
}
void meshOctreeAddressing::calculateEdgeLeaves() const
{
const VRWGraph& edgeFaces = this->edgeFaces();
const labelLongList& owner = this->octreeFaceOwner();
const labelLongList& neighbour = this->octreeFaceNeighbour();
edgeLeavesPtr_ = new VRWGraph();
VRWGraph& edgeLeaves = *edgeLeavesPtr_;
edgeLeaves.setSizeAndColumnWidth(edgeFaces.size(), 4);
forAll(edgeFaces, edgeI)
{
forAllRow(edgeFaces, edgeI, efI)
{
const label fI = edgeFaces(edgeI, efI);
const label own = owner[fI];
const label nei = neighbour[fI];
edgeLeaves.appendIfNotIn(edgeI, own);
if( nei < 0 )
continue;
edgeLeaves.appendIfNotIn(edgeI, nei);
}
}
}
void meshOctreeAddressing::calculateEdgeFaces() const
{
const VRWGraph& faceEdges = this->faceEdges();
edgeFacesPtr_ = new VRWGraph(octreeEdges().size());
VRWGraph& edgeFaces = *edgeFacesPtr_;
VRWGraphSMPModifier(edgeFaces).reverseAddressing(faceEdges);
edgeFaces.setSize(octreeEdges().size());
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace CML
// ************************************************************************* //
| 30.421137 | 80 | 0.471471 | [
"mesh",
"vector"
] |
2716ed04f507a51cb94c5bc371011b6e534c3471 | 4,419 | cpp | C++ | engine/src/engine/entities/shapes/house.cpp | kdivanovich/CPP_Demo_Game | 85be2d2f366728f9d6893ebe42c765c41b685a53 | [
"MIT"
] | null | null | null | engine/src/engine/entities/shapes/house.cpp | kdivanovich/CPP_Demo_Game | 85be2d2f366728f9d6893ebe42c765c41b685a53 | [
"MIT"
] | null | null | null | engine/src/engine/entities/shapes/house.cpp | kdivanovich/CPP_Demo_Game | 85be2d2f366728f9d6893ebe42c765c41b685a53 | [
"MIT"
] | 2 | 2021-12-16T13:04:18.000Z | 2022-01-07T14:06:06.000Z | #include "pch.h"
#include "house.h"
#include <engine.h>
engine::house::house(std::vector<glm::vec3> vertices) : m_vertices(vertices)
{
std::vector<glm::vec3> normals;
// front normal 1:
normals.push_back(glm::cross(vertices.at(0) - vertices.at(3), vertices.at(0) - vertices.at(1)));
// front normal 2:
normals.push_back(glm::cross(vertices.at(1) - vertices.at(3), vertices.at(1) - vertices.at(2)));
// left normal 1:
normals.push_back(glm::cross(vertices.at(7) - vertices.at(4), vertices.at(7) - vertices.at(0)));
// left normal 2:
normals.push_back(glm::cross(vertices.at(0) - vertices.at(4), vertices.at(0) - vertices.at(3)));
// right normal 1:
normals.push_back(glm::cross(vertices.at(1) - vertices.at(2), vertices.at(1) - vertices.at(6)));
// right normal 2:
normals.push_back(glm::cross(vertices.at(6) - vertices.at(2), vertices.at(6) - vertices.at(5)));
// back normal 1:
normals.push_back(glm::cross(vertices.at(6) - vertices.at(5), vertices.at(6) - vertices.at(7)));
// back normal 2:
normals.push_back(glm::cross(vertices.at(7) - vertices.at(5), vertices.at(7) - vertices.at(4)));
// roof front
normals.push_back(glm::cross(vertices.at(8) - vertices.at(0), vertices.at(8) - vertices.at(1)));
// roof left
normals.push_back(glm::cross(vertices.at(8) - vertices.at(7), vertices.at(8) - vertices.at(0)));
// roof right
normals.push_back(glm::cross(vertices.at(8) - vertices.at(1), vertices.at(8) - vertices.at(6)));
// roof back
normals.push_back(glm::cross(vertices.at(8) - vertices.at(6), vertices.at(8) - vertices.at(7)));
std::vector<mesh::vertex> house_vertices
{
//front 1
// position normal tex coord
{ vertices.at(0), normals.at(0), { 0.5f, 1.f } },
{ vertices.at(3), normals.at(0), { 0.5f, 0.f } },
{ vertices.at(1), normals.at(0), { 1.f, 1.f } },
//front 2
{ vertices.at(1), normals.at(1), { 1.f, 1.f } },
{ vertices.at(3), normals.at(1), { 0.5f, 0.f } },
{ vertices.at(2), normals.at(1), { 1.f, 0.f } },
//left 1
{ vertices.at(7), normals.at(2), { 0.5f, 1.f } },
{ vertices.at(4), normals.at(2), { 0.5f, 0.f } },
{ vertices.at(0), normals.at(2), { 1.f, 1.f } },
//left 2
{ vertices.at(0), normals.at(3), { 1.f, 1.f } },
{ vertices.at(4), normals.at(3), { 0.5f, 0.f } },
{ vertices.at(3), normals.at(3), { 1.f, 0.f } },
//right 1
{ vertices.at(1), normals.at(4), { 0.5f, 1.f } },
{ vertices.at(2), normals.at(4), { 0.5f, 0.f } },
{ vertices.at(6), normals.at(4), { 1.f, 1.f } },
//right 2
{ vertices.at(6), normals.at(5), { 1.f, 1.f } },
{ vertices.at(2), normals.at(5), { 0.5f, 0.f } },
{ vertices.at(5), normals.at(5), { 1.f, 0.f } },
//back 1
{ vertices.at(6), normals.at(6), { 0.5f, 1.f } },
{ vertices.at(5), normals.at(6), { 0.5f, 0.f } },
{ vertices.at(7), normals.at(6), { 1.f, 1.f } },
//back 2
{ vertices.at(7), normals.at(7), { 1.f, 1.f } },
{ vertices.at(5), normals.at(7), { 0.5f, 0.f } },
{ vertices.at(4), normals.at(7), { 1.f, 0.f } },
//roof front
{ vertices.at(8), normals.at(8), { 0.25f, 0.5f } },
{ vertices.at(0), normals.at(8), { 0.0f, 0.f } },
{ vertices.at(1), normals.at(8), { 0.5f, 0.f } },
//roof left
{ vertices.at(8), normals.at(9), { 0.25f, 0.5f } },
{ vertices.at(7), normals.at(9), { 0.0f, 0.f } },
{ vertices.at(0), normals.at(9), { 0.5f, 0.f } },
//roof right
{ vertices.at(8), normals.at(10), { 0.25f, 0.5f } },
{ vertices.at(1), normals.at(10), { 0.0f, 0.f } },
{ vertices.at(6), normals.at(10), { 0.5f, 0.f } },
//roof back
{ vertices.at(8), normals.at(11), { 0.25f, 0.5f } },
{ vertices.at(6), normals.at(11), { 0.0f, 0.f } },
{ vertices.at(7), normals.at(11), { 0.5f, 0.f } }
};
const std::vector<uint32_t> house_indices
{
0,1,2, 3,4,5, // front
6,7,8, 9,10,11, // left
12,13,14, 15,16,17, // right
18,19,20, 21,22,23, // back
24,25,26, // roof front
27,28,29, // roof left
30,31,32, // roof right
33,34,35 // roof back
};
m_mesh = engine::mesh::create(house_vertices, house_indices);
}
engine::house::~house() {}
engine::ref<engine::house> engine::house::create(std::vector<glm::vec3> vertices)
{
return std::make_shared<engine::house>(vertices);
}
| 33.732824 | 97 | 0.553519 | [
"mesh",
"vector"
] |
271e63da8f0c55c19075104563957ab19e926402 | 794 | cpp | C++ | 304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.cpp | phaneesh707/LeetCode_Problems | e17db0454b21993aec734bbc5dd3a862c0229acb | [
"MIT"
] | null | null | null | 304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.cpp | phaneesh707/LeetCode_Problems | e17db0454b21993aec734bbc5dd3a862c0229acb | [
"MIT"
] | null | null | null | 304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.cpp | phaneesh707/LeetCode_Problems | e17db0454b21993aec734bbc5dd3a862c0229acb | [
"MIT"
] | null | null | null | class NumMatrix {
public:
vector<vector<int>> a;
NumMatrix(vector<vector<int>>& matrix) {
a = matrix;
if(matrix[0].size()>1){
for(int i=0;i<matrix.size();i++){
for(int j=1;j<matrix[i].size();j++){
a[i][j]+=a[i][j-1];
}
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
int sum=0;
for(int i = row1;i<=row2;i++){
if(col1==0)
sum+=a[i][col2];
else
sum+=a[i][col2]-a[i][col1-1];
}
return sum;
}
};
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix* obj = new NumMatrix(matrix);
* int param_1 = obj->sumRegion(row1,col1,row2,col2);
*/ | 24.8125 | 65 | 0.458438 | [
"object",
"vector"
] |
27207c467cf68d799b3fe23edc94d0198f75d065 | 1,953 | cpp | C++ | tests/rtt_rospack_tests/test/api_tests.cpp | mcx/rtt_ros_integration | df79afb7a7b6e90ea7b807f0e4322662caee8c07 | [
"BSD-3-Clause"
] | 73 | 2015-03-18T00:00:00.000Z | 2022-03-28T10:15:56.000Z | tests/rtt_rospack_tests/test/api_tests.cpp | mcx/rtt_ros_integration | df79afb7a7b6e90ea7b807f0e4322662caee8c07 | [
"BSD-3-Clause"
] | 86 | 2015-01-20T19:12:34.000Z | 2021-12-20T07:18:58.000Z | tests/rtt_rospack_tests/test/api_tests.cpp | mcx/rtt_ros_integration | df79afb7a7b6e90ea7b807f0e4322662caee8c07 | [
"BSD-3-Clause"
] | 59 | 2015-02-22T18:14:47.000Z | 2021-09-04T19:40:12.000Z | /** Copyright (c) 2013, Jonathan Bohren, all rights reserved.
* This software is released under the BSD 3-clause license, for the details of
* this license, please see LICENSE.txt at the root of this repository.
*/
#include <string>
#include <vector>
#include <iterator>
#include <rtt/os/startstop.h>
#include <ocl/DeploymentComponent.hpp>
#include <ocl/TaskBrowser.hpp>
#include <ocl/LoggingService.hpp>
#include <rtt/Logger.hpp>
#include <rtt/deployment/ComponentLoader.hpp>
#include <rtt/scripting/Scripting.hpp>
#include <rtt/internal/GlobalService.hpp>
#include <ros/package.h>
#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
#include <gtest/gtest.h>
boost::shared_ptr<OCL::DeploymentComponent> deployer;
boost::shared_ptr<RTT::Scripting> scripting_service;
RTT::Service::shared_ptr global_service;
TEST(BasicTest, Import)
{
// Import rtt_ros plugin
RTT::ComponentLoader::Instance()->import("rtt_ros", "" );
}
TEST(BasicTest, PackageFinding)
{
// Import rtt_ros plugin
EXPECT_TRUE(scripting_service->eval("ros.import(\"rtt_rospack_tests\")"));
RTT::OperationCaller<std::string(const std::string&)> rpf = global_service->provides("ros")->getOperation("find");
std::string roscpp_dir = ros::package::getPath("roscpp");
EXPECT_EQ(roscpp_dir,rpf("roscpp"));
std::string rtt_rospack_tests_dir = ros::package::getPath("rtt_rospack_tests");
EXPECT_EQ(rtt_rospack_tests_dir,rpf("rtt_rospack_tests"));
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
// Initialize Orocos
__os_init(argc, argv);
deployer = boost::make_shared<OCL::DeploymentComponent>();
scripting_service = deployer->getProvider<RTT::Scripting>("scripting");
global_service = RTT::internal::GlobalService::Instance();
RTT::Logger::log().setStdStream(std::cerr);
RTT::Logger::log().mayLogStdOut(true);
RTT::Logger::log().setLogLevel(RTT::Logger::Debug);
return RUN_ALL_TESTS();
}
| 29.149254 | 116 | 0.738351 | [
"vector"
] |
272a8df63df2847f87340c26094cd6993d10b02f | 980 | cpp | C++ | TimetableProblem/Lecture.cpp | AlbertoKarakoutev/timetable-problem | b3bf34de55af1131b5ea08cfc34632d988793680 | [
"Apache-2.0"
] | null | null | null | TimetableProblem/Lecture.cpp | AlbertoKarakoutev/timetable-problem | b3bf34de55af1131b5ea08cfc34632d988793680 | [
"Apache-2.0"
] | null | null | null | TimetableProblem/Lecture.cpp | AlbertoKarakoutev/timetable-problem | b3bf34de55af1131b5ea08cfc34632d988793680 | [
"Apache-2.0"
] | null | null | null | #include "Lecture.h"
Lecture::Lecture(Course course, int room, std::string teacher, int day, int period)
{
_course = course;
_room = room;
_teacher = teacher;
_day = day;
_period = period;
}
Lecture::Lecture() {
_day = 0;
_period = 0;
_room = 0;
}
void Lecture::setTime(vector<int> time) {
_day = time.at(0);
_period = time.at(1);
}
vector<int> Lecture::getTime() {
return { _day, _period };
}
std::string Lecture::info()
{
std::string info = "";
info += "\t\tRoom " + std::to_string(_room) + ", ";
info += _teacher + ", ";
info += _course.getName() + " [ ";
for (int i = 0; i < studentsPerClass; i++)
{
info += std::to_string(_course.getStudents()[i]) + " ";
}
info += "]\n";
return info;
}
bool Lecture::operator==(const Lecture rhs) const {
bool props = _course == rhs._course && _room == rhs._room && _teacher.compare(rhs._teacher) == 0;
bool time = _day == rhs._day && _period == rhs._period;
return props && time;
}
| 20 | 101 | 0.59898 | [
"vector"
] |
272a93c8abd178c799dcfcaf332a5738aea89a01 | 1,581 | cpp | C++ | component/oai-amf/src/sbi/amf_server/model/InvalidParam_2.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-amf/src/sbi/amf_server/model/InvalidParam_2.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-amf/src/sbi/amf_server/model/InvalidParam_2.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /**
* Namf_Communication
* AMF Communication Service © 2019, 3GPP Organizational Partners (ARIB, ATIS,
* CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* The version of the OpenAPI document: 1.1.0.alpha-1
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
#include "InvalidParam_2.h"
namespace oai {
namespace amf {
namespace model {
InvalidParam_2::InvalidParam_2() {
m_Param = "";
m_Reason = "";
m_ReasonIsSet = false;
}
InvalidParam_2::~InvalidParam_2() {}
void InvalidParam_2::validate() {
// TODO: implement validation
}
void to_json(nlohmann::json& j, const InvalidParam_2& o) {
j = nlohmann::json();
j["param"] = o.m_Param;
if (o.reasonIsSet()) j["reason"] = o.m_Reason;
}
void from_json(const nlohmann::json& j, InvalidParam_2& o) {
j.at("param").get_to(o.m_Param);
if (j.find("reason") != j.end()) {
j.at("reason").get_to(o.m_Reason);
o.m_ReasonIsSet = true;
}
}
std::string InvalidParam_2::getParam() const {
return m_Param;
}
void InvalidParam_2::setParam(std::string const& value) {
m_Param = value;
}
std::string InvalidParam_2::getReason() const {
return m_Reason;
}
void InvalidParam_2::setReason(std::string const& value) {
m_Reason = value;
m_ReasonIsSet = true;
}
bool InvalidParam_2::reasonIsSet() const {
return m_ReasonIsSet;
}
void InvalidParam_2::unsetReason() {
m_ReasonIsSet = false;
}
} // namespace model
} // namespace amf
} // namespace oai
| 22.913043 | 79 | 0.678052 | [
"model"
] |
2737737187635edef37e228f21e77a683cd12973 | 720 | hpp | C++ | src/modeling_2d/creatures.hpp | JustSlavic/gl2 | 1b4752d3273a1e401c970e18ae7151bba004a4ec | [
"MIT"
] | null | null | null | src/modeling_2d/creatures.hpp | JustSlavic/gl2 | 1b4752d3273a1e401c970e18ae7151bba004a4ec | [
"MIT"
] | 2 | 2021-05-29T20:34:50.000Z | 2021-05-29T20:39:25.000Z | src/modeling_2d/creatures.hpp | JustSlavic/gl2 | 1b4752d3273a1e401c970e18ae7151bba004a4ec | [
"MIT"
] | null | null | null | #pragma once
#include <defines.h>
#include <graphics/shader.h>
#include <graphics/vertex_array.h>
#include <graphics/index_buffer.h>
#include <math.hpp>
#include <vector>
struct creature {
enum kind_t {
HERBIVORE,
PREDATOR,
};
math::vector2 position;
math::color24 color;
f32 size = 0.1f;
kind_t kind;
glm::mat4 cached_model_matrix;
static creature make_random (math::vector2 position);
};
struct simulation {
std::vector<creature> creatures;
Shader* shader = nullptr;
VertexArray* va;
IndexBuffer* ib;
void iterate();
void add_creature (creature it);
void draw_creatures ();
void move_creatures (f32 dt);
void clean ();
};
| 16.744186 | 57 | 0.652778 | [
"vector"
] |
273bb472dd83403866fb57f9442bd3af917a1794 | 17,880 | cpp | C++ | cpp/src/ipc_dshow_source/ARibeiroSourceDevice.cpp | A-Ribeiro/OpenMultimedia | 2bac6022f5a4c4bea57826191a9aa1b55e36f2b9 | [
"MIT"
] | null | null | null | cpp/src/ipc_dshow_source/ARibeiroSourceDevice.cpp | A-Ribeiro/OpenMultimedia | 2bac6022f5a4c4bea57826191a9aa1b55e36f2b9 | [
"MIT"
] | null | null | null | cpp/src/ipc_dshow_source/ARibeiroSourceDevice.cpp | A-Ribeiro/OpenMultimedia | 2bac6022f5a4c4bea57826191a9aa1b55e36f2b9 | [
"MIT"
] | null | null | null | #include "ARibeiroSourceDevice.h"
#include "resource.h"
extern HINSTANCE hDllModuleDll;
#define ARIBEIRO_ASSERT(cls_obj, bool_exp, ...) \
if (!(bool_exp)) {\
cls_obj->printf("[%s:%i]\n", __FILE__, __LINE__);\
cls_obj->printf(__VA_ARGS__);\
delete cls_obj;\
cls_obj = NULL;\
ASSERT((bool_exp));\
}
ARibeiroSourceDevice::ARibeiroSourceDevice(
//const char *name_str,
const CFactoryTemplate *base_template, LPUNKNOWN lpunk, HRESULT *phr) :
CSource(
aRibeiro::StringUtil::toString(base_template->m_Name).c_str(),//base_template->m_Name,
lpunk, *base_template->m_ClsID)
{
input_queue = NULL;
debug = NULL;
debug = new DebugConsoleIPC();
ARIBEIRO_ASSERT(debug, phr, "[ARibeiroSourceDevice_CreateInstance] phr NULL.\n");
//ASSERT(phr);
debug->printf("[ARibeiroSourceDevice] Creating Source From Template: %s.\n", aRibeiro::StringUtil::toString(base_template->m_Name).c_str());
debug->printf("[ARibeiroSourceDevice] creating outputstream\n");
this->base_template = base_template;
CAutoLock cAutoLock(&m_cStateLock);
m_paStreams = (CSourceStream **) new ARibeiroOutputStream*[1];
m_paStreams[0] = new ARibeiroOutputStream(phr, this, L"Video");
debug->printf("[ARibeiroSourceDevice] initialization done\n");
//sourceConfig = _sourceConfig;
}
ARibeiroSourceDevice::~ARibeiroSourceDevice() {
CAutoLock cAutoLock(&m_cStateLock);
if (debug != NULL) {
debug->printf("[ARibeiroSourceDevice] destroying Object!!!\n");
}
if (input_queue != NULL) {
delete input_queue;
input_queue = NULL;
}
if (m_paStreams != NULL) {
if (m_paStreams[0] != NULL) {
delete m_paStreams[0];
}
delete[] m_paStreams;
m_paStreams = NULL;
}
if (debug != NULL) {
delete debug;
debug = NULL;
}
}
HRESULT ARibeiroSourceDevice::NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
if (riid == _uuidof(IAMStreamConfig) || riid == _uuidof(IKsPropertySet))
return m_paStreams[0]->QueryInterface(riid, ppv);
else
return CSource::NonDelegatingQueryInterface(riid, ppv);
}
ARibeiroOutputStream *ARibeiroSourceDevice::getStream(int id) {
debug->printf("[ARibeiroSourceDevice] getStream(%i)\n", id);
return (ARibeiroOutputStream *)m_paStreams[0];
}
HRESULT STDMETHODCALLTYPE ARibeiroOutputStream::SetFormat(AM_MEDIA_TYPE *ptrMediaType)
{
if (ptrMediaType == nullptr)
return E_FAIL;
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
if (parent->GetState() != State_Stopped)
return E_FAIL;
if (CheckMediaType((CMediaType *)ptrMediaType) != S_OK)
return E_FAIL;
//VIDEOINFOHEADER *videoInfoHeader = (VIDEOINFOHEADER *)(ptrMediaType->pbFormat);
m_mt.SetFormat(m_mt.Format(), sizeof(VIDEOINFOHEADER));
CheckCreatedFormatList();
/*
format_list.insert(
format_list.begin(),
DShowSourceResolution(
videoInfoHeader->bmiHeader.biWidth,
videoInfoHeader->bmiHeader.biHeight,
videoInfoHeader->AvgTimePerFrame
)
);
*/
IPin* pin;
ConnectedTo(&pin);
if (pin){
IFilterGraph *pGraph = parent->GetGraph();
pGraph->Reconnect(this);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE ARibeiroOutputStream::GetFormat(AM_MEDIA_TYPE **outMediaType)
{
*outMediaType = CreateMediaType(&m_mt);
return S_OK;
}
HRESULT STDMETHODCALLTYPE ARibeiroOutputStream::GetNumberOfCapabilities(int *piCount,
int *piSize)
{
CheckCreatedFormatList();
*piCount = (int)format_list.size();
*piSize = sizeof(VIDEO_STREAM_CONFIG_CAPS);
return S_OK;
}
HRESULT STDMETHODCALLTYPE ARibeiroOutputStream::GetStreamCaps(int iIndex,
AM_MEDIA_TYPE **outMediaType, BYTE *ptrStreamConfigCaps)
{
CheckCreatedFormatList();
if (iIndex < 0 || iIndex > format_list.size() - 1)
return E_INVALIDARG;
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
*outMediaType = CreateMediaType(&m_mt);
VIDEOINFOHEADER* videoInfoHeader = (VIDEOINFOHEADER*)((*outMediaType)->pbFormat);
videoInfoHeader->bmiHeader.biWidth = format_list[iIndex].width;
videoInfoHeader->bmiHeader.biHeight = format_list[iIndex].height;
videoInfoHeader->AvgTimePerFrame = format_list[iIndex].time_per_frame;
//pvi->AvgTimePerFrame = 333333;
//if (parent->sourceConfig->type == DShowSourceFormat_Yuy2) {
videoInfoHeader->bmiHeader.biCompression = MAKEFOURCC('Y', 'U', 'Y', '2');
videoInfoHeader->bmiHeader.biBitCount = 16;
//}
videoInfoHeader->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
videoInfoHeader->bmiHeader.biPlanes = 1;
//if (parent->sourceConfig->type == DShowSourceFormat_Yuy2)
videoInfoHeader->bmiHeader.biSizeImage = videoInfoHeader->bmiHeader.biWidth * videoInfoHeader->bmiHeader.biHeight * 2;
videoInfoHeader->bmiHeader.biClrImportant = 0;
SetRectEmpty(&(videoInfoHeader->rcSource));
SetRectEmpty(&(videoInfoHeader->rcTarget));
(*outMediaType)->majortype = MEDIATYPE_Video;
//if (parent->sourceConfig->type == DShowSourceFormat_Yuy2)
(*outMediaType)->subtype = MEDIASUBTYPE_YUY2;
(*outMediaType)->formattype = FORMAT_VideoInfo;
(*outMediaType)->bTemporalCompression = FALSE;
(*outMediaType)->bFixedSizeSamples = FALSE;
(*outMediaType)->lSampleSize = videoInfoHeader->bmiHeader.biSizeImage;
(*outMediaType)->cbFormat = sizeof(VIDEOINFOHEADER);
VIDEO_STREAM_CONFIG_CAPS* videoStreamConfigCaps = (VIDEO_STREAM_CONFIG_CAPS*)(ptrStreamConfigCaps);
memset(videoStreamConfigCaps, 0, sizeof(VIDEO_STREAM_CONFIG_CAPS));
SIZE size = {
videoInfoHeader->bmiHeader.biWidth,
videoInfoHeader->bmiHeader.biHeight
};
videoStreamConfigCaps->guid = FORMAT_VideoInfo;
videoStreamConfigCaps->VideoStandard = AnalogVideo_None;
videoStreamConfigCaps->InputSize = size;
videoStreamConfigCaps->MinCroppingSize = size;
videoStreamConfigCaps->MaxCroppingSize = size;
videoStreamConfigCaps->CropGranularityX = videoInfoHeader->bmiHeader.biWidth;
videoStreamConfigCaps->CropGranularityY = videoInfoHeader->bmiHeader.biHeight;
videoStreamConfigCaps->MinOutputSize = size;
videoStreamConfigCaps->MaxOutputSize = size;
videoStreamConfigCaps->MinFrameInterval = videoInfoHeader->AvgTimePerFrame;
videoStreamConfigCaps->MaxFrameInterval = videoInfoHeader->AvgTimePerFrame;
LONG bps;
//if (parent->sourceConfig->type == DShowSourceFormat_Yuy2)
bps = videoInfoHeader->bmiHeader.biWidth * videoInfoHeader->bmiHeader.biHeight * 2 * 8 * (10000000 / videoInfoHeader->AvgTimePerFrame);
videoStreamConfigCaps->MinBitsPerSecond = bps;
videoStreamConfigCaps->MaxBitsPerSecond = bps;
return S_OK;
}
void ARibeiroOutputStream::CheckCreatedFormatList()
{
if (format_list.size() > 0)
return;
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
int width = 1920;
int height = 1080;
double framerate = 30.0f;
/*
uint32_t numerator;
uint32_t denominator;
Double2Fract_inverse(framerate, &numerator, &denominator);
*/
double timePerFrame = floor(10000000.0 / static_cast<double>(framerate));
REFERENCE_TIME AvgTimePerFrame = (REFERENCE_TIME)(timePerFrame + 0.5);
format_list.push_back(DShowSourceResolution(
width,
height,
AvgTimePerFrame
));
/*
format_list.push_back(DShowSourceResolution(
parent->sourceConfig->width,
parent->sourceConfig->height,
parent->sourceConfig->AvgTimePerFrame
));
*/
}
ARibeiroOutputStream::ARibeiroOutputStream(HRESULT *phr, ARibeiroSourceDevice *pParent, LPCWSTR pPinName):
CSourceStream(NAME("Video"), phr, pParent, pPinName)
{
process = NULL;
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
parent->debug->printf(" [ARibeiroOutputStream] creating Object!!!\n");
parent->debug->printf(" [ARibeiroOutputStream] hDllModuleDll: %x\n", hDllModuleDll);
// unzip the splash image from rc file
HRSRC hRes = ::FindResourceA(hDllModuleDll, MAKEINTRESOURCE(IDR_SPLASH), RT_RCDATA);//"splash.bin"
if (hRes != NULL) {
parent->debug->printf(" [ARibeiroOutputStream] resource found.\n");
unsigned int myResourceSize = ::SizeofResource(hDllModuleDll, hRes);
HGLOBAL hResLoad = ::LoadResource(hDllModuleDll, hRes);
if (hResLoad != NULL) {
parent->debug->printf(" [ARibeiroOutputStream] Resource loaded.\n");
void* pMyBinaryData = ::LockResource(hResLoad);
if (pMyBinaryData != NULL) {
BinaryReader reader;
reader.readFromBuffer((uint8_t*)pMyBinaryData, myResourceSize);
uint8_t *buffer;
uint32_t size;
reader.readBuffer( &buffer, &size);
data_buffer.setSize(size);
memcpy(data_buffer.data, buffer, size);
}
else {
parent->debug->printf(" [ARibeiroOutputStream] resource pointer is null...\n");
}
//::UnlockResource(myResourceData);
::FreeResource(hResLoad);
}
else {
parent->debug->printf(" [ARibeiroOutputStream] Error to load resource.\n");
}
}
else {
parent->debug->printf(" [ARibeiroOutputStream] resource not found.\n");
}
std::string queueName = aRibeiro::StringUtil::toString(parent->base_template->m_Name);
// 8 buffers of 1920x1080x2 (yuyv2)
data_queue = new PlatformLowLatencyQueueIPC(queueName.c_str(), PlatformQueueIPC_READ, 8, 1920*1080*2, false);
CheckCreatedFormatList();
GetMediaType(0, &m_mt);
first = true;
}
ARibeiroOutputStream::~ARibeiroOutputStream()
{
aRibeiro::setNullAndDelete(process);
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
if (parent != NULL && parent->debug != NULL)
parent->debug->printf(" [ARibeiroOutputStream] destroying Object!!!\n");
if (data_queue != NULL) {
delete data_queue;
data_queue = NULL;
}
}
HRESULT ARibeiroOutputStream::FillBuffer(IMediaSample *ptrMediaSample)
{
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
if (process == NULL) {
char achTemp[MAX_PATH];
if (GetModuleFileNameA(hDllModuleDll, achTemp, sizeof(achTemp)))
{
parent->debug->printf(" [ARibeiroOutputStream] dll file: %s\n", achTemp);
std::string dll_path = PlatformPath::getExecutablePath(achTemp);
parent->debug->printf(" [ARibeiroOutputStream] dll path: %s\n", dll_path.c_str());
process = new PlatformProcess(dll_path + "/network-to-ipc/network-to-ipc", "-noconsole");
parent->debug->printf(" [ARibeiroOutputStream] process created: %i\n", process->isCreated());
}
}
VIDEOINFOHEADER* videoInfoHeader = (VIDEOINFOHEADER*)m_mt.pbFormat;
uint8_t* buffer;
HRESULT hr = ptrMediaSample->GetPointer((BYTE**)&buffer);
int bufferSize = ptrMediaSample->GetActualDataLength();
REFERENCE_TIME duration = videoInfoHeader->AvgTimePerFrame;
bool read_content = false;
/*
//parent->debug->printf(".");
if (data_queue->readHasElement(true)) {
//parent->debug->printf(" [ARibeiroOutputStream] Has content\n");
data_queue->read(&data_buffer, false, true);
//clear queue... low latency strategy
while (data_queue->readHasElement(true))
data_queue->read(&data_buffer, false, true);
if (bufferSize == data_buffer.size) {
//parent->debug->printf(" [ARibeiroOutputStream] Valid Buffer Size\n");
memcpy(buffer, data_buffer.data, bufferSize);
read_content = true;
}
}
*/
if (data_queue->read(&data_buffer)) {
//clear queue... low latency strategy
while (data_queue->read(&data_buffer));
if (bufferSize == data_buffer.size) {
//parent->debug->printf(" [ARibeiroOutputStream] Valid Buffer Size\n");
memcpy(buffer, data_buffer.data, bufferSize);
read_content = true;
}
}
else {
data_buffer.setSize(bufferSize);
if (bufferSize == data_buffer.size) {
//parent->debug->printf(" [ARibeiroOutputStream] Valid Buffer Size\n");
memcpy(buffer, data_buffer.data, bufferSize);
read_content = true;
}
}
timer.update();
if (first){
first = false;
timer.reset();
current_time = 0;
next_time = duration;
} else {
// 1micro = 10 ActiveMovie units (100 nS)
current_time += (REFERENCE_TIME)(timer.deltaTimeMicro * 10);// next_time;
//if (read_content) {
sleepToSync(¤t_time, next_time);
//update next just in case of having new content...
next_time = current_time + duration;
//} else
// return E_PENDING;
}
ptrMediaSample->SetTime(¤t_time, &next_time);
ptrMediaSample->SetSyncPoint(TRUE);
return NOERROR;
}
void ARibeiroOutputStream::sleepToSync(REFERENCE_TIME *current, const REFERENCE_TIME &target) {
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
// 1ms = 1000000ns
// 1micro = 1000ns
// ActiveMovie units (100 nS)
REFERENCE_TIME delta = target - (*current);
//parent->debug->printf(" [ARibeiroOutputStream] SLEEP TO SYNC from: %" PRIi64 " to %" PRIi64 "(delta: %" PRIi64 ")\n", (*current), target, delta);
if (delta <= 0) {
//parent->debug->printf(" [ARibeiroOutputStream] No need to sync...\n", (*current), target);
return;
}
// 1ms = 10000 ActiveMovie units (100 nS)
uint64_t delta_ms = delta / 10000;
if (delta % 10000 > 0)
delta_ms += 1;
PlatformSleep::sleepMillis(delta_ms);
// 1micro = 10 ActiveMovie units (100 nS)
//uint64_t delta_micro = delta / 10;
//PlatformSleep::busySleepMicro(delta_micro);
timer.update();
(*current) += (REFERENCE_TIME)(timer.deltaTimeMicro * 10);
delta = target - (*current);
//parent->debug->printf(" [ARibeiroOutputStream] After SYNC: %" PRIi64 " -> %" PRIi64 "(delta: %" PRIi64 ")\n", (*current), target, delta);
}
HRESULT ARibeiroOutputStream::DecideBufferSize(IMemAllocator *ptrAllocator,
ALLOCATOR_PROPERTIES *ptrProperties)
{
CAutoLock cAutoLock(m_pFilter->pStateLock());
HRESULT hr = NOERROR;
VIDEOINFOHEADER *videoInfoHeader = (VIDEOINFOHEADER *)m_mt.Format();
ptrProperties->cBuffers = 1;
ptrProperties->cbBuffer = videoInfoHeader->bmiHeader.biSizeImage;
ALLOCATOR_PROPERTIES Actual;
hr = ptrAllocator->SetProperties(ptrProperties, &Actual);
if (FAILED(hr)) return hr;
if (Actual.cbBuffer < ptrProperties->cbBuffer) return E_FAIL;
return NOERROR;
}
HRESULT ARibeiroOutputStream::CheckMediaType(const CMediaType *ptrMediaType)
{
if (ptrMediaType == nullptr)
return E_FAIL;
VIDEOINFOHEADER *videoInforHeader = (VIDEOINFOHEADER *)(ptrMediaType->Format());
const GUID* type = ptrMediaType->Type();
const GUID* info = ptrMediaType->FormatType();
const GUID* subtype = ptrMediaType->Subtype();
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
if (*type != MEDIATYPE_Video)
return E_INVALIDARG;
if (*info != FORMAT_VideoInfo)
return E_INVALIDARG;
//if (parent->sourceConfig->type == DShowSourceFormat_Yuy2)
if (*subtype != MEDIASUBTYPE_YUY2)
return E_INVALIDARG;
for (int i = 0; i < format_list.size(); i++)
{
if (videoInforHeader->AvgTimePerFrame == format_list[i].time_per_frame &&
videoInforHeader->bmiHeader.biWidth == format_list[i].width &&
videoInforHeader->bmiHeader.biHeight == format_list[i].height)
return S_OK;
}
/*
if (videoInforHeader->AvgTimePerFrame != parent->sourceConfig->AvgTimePerFrame)
return E_INVALIDARG;
if (videoInforHeader->bmiHeader.biWidth == parent->sourceConfig->width ||
videoInforHeader->bmiHeader.biHeight == parent->sourceConfig->height)
return S_OK;
*/
return E_INVALIDARG;
}
HRESULT ARibeiroOutputStream::GetMediaType(int iPosition,CMediaType *ptrMediaType)
{
CheckCreatedFormatList();
if (iPosition < 0 || iPosition > format_list.size()-1)
return E_INVALIDARG;
VIDEOINFOHEADER* videoInfoHeader = (VIDEOINFOHEADER*)(ptrMediaType->AllocFormatBuffer(sizeof(VIDEOINFOHEADER)));
ZeroMemory(videoInfoHeader, sizeof(VIDEOINFOHEADER));
ARibeiroSourceDevice *parent = (ARibeiroSourceDevice *)m_pFilter;
videoInfoHeader->bmiHeader.biWidth = format_list[iPosition].width;
videoInfoHeader->bmiHeader.biHeight = format_list[iPosition].height;
videoInfoHeader->AvgTimePerFrame = format_list[iPosition].time_per_frame;
//if (parent->sourceConfig->type == DShowSourceFormat_Yuy2)
{
videoInfoHeader->bmiHeader.biCompression = MAKEFOURCC('Y', 'U', 'Y', '2');
videoInfoHeader->bmiHeader.biBitCount = 16;
}
videoInfoHeader->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
videoInfoHeader->bmiHeader.biPlanes = 1;
//if (parent->sourceConfig->type == DShowSourceFormat_Yuy2)
{
videoInfoHeader->bmiHeader.biSizeImage = videoInfoHeader->bmiHeader.biWidth * videoInfoHeader->bmiHeader.biHeight * 2;
}
videoInfoHeader->bmiHeader.biClrImportant = 0;
SetRectEmpty(&(videoInfoHeader->rcSource));
SetRectEmpty(&(videoInfoHeader->rcTarget));
ptrMediaType->SetType(&MEDIATYPE_Video);
ptrMediaType->SetFormatType(&FORMAT_VideoInfo);
ptrMediaType->SetTemporalCompression(FALSE);
//if (parent->sourceConfig->type == DShowSourceFormat_Yuy2)
ptrMediaType->SetSubtype(&MEDIASUBTYPE_YUY2);
ptrMediaType->SetSampleSize(videoInfoHeader->bmiHeader.biSizeImage);
return NOERROR;
}
HRESULT ARibeiroOutputStream::SetMediaType(const CMediaType *ptrMediaType)
{
VIDEOINFOHEADER* videoInfoHeader = (VIDEOINFOHEADER*)(ptrMediaType->Format());
HRESULT hr = CSourceStream::SetMediaType(ptrMediaType);
return hr;
}
| 31.646018 | 152 | 0.693624 | [
"object"
] |
273d4742a2c60174b0b1915704fd16b42d3a0ea0 | 8,438 | cc | C++ | src/lib.cc | Chimu-moe/cpp-chimu-api | 7531727870200a5baa9f8f98fc218e065ad976cf | [
"Unlicense"
] | null | null | null | src/lib.cc | Chimu-moe/cpp-chimu-api | 7531727870200a5baa9f8f98fc218e065ad976cf | [
"Unlicense"
] | null | null | null | src/lib.cc | Chimu-moe/cpp-chimu-api | 7531727870200a5baa9f8f98fc218e065ad976cf | [
"Unlicense"
] | null | null | null | #include <chimu/api.hh>
#include <curl/curl.h>
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include <iostream>
#include <iterator>
using namespace Chimu;
template<typename T>
struct APIResult
{
public:
uint32_t m_iCode{};
std::string m_sMessage{};
T m_tData{};
public:
static APIResult<T> fromJson(const std::string_view& svData)
{
auto json = nlohmann::json::parse(svData);
APIResult<T> result;
result.m_iCode = json["code"];
result.m_sMessage = json["message"];
if (result.m_iCode == 0)
result.m_tData = T::fromJson(json["data"].dump());
return result;
}
static APIResult<std::vector<T>> fromJsonVector(
const std::string_view& svData)
{
auto json = nlohmann::json::parse(svData);
APIResult<std::vector<T>> result;
result.m_iCode = json["code"];
result.m_sMessage = json["message"];
if (result.m_iCode == 0)
{
for (auto json_ : json["data"])
{
result.m_tData.push_back(T::fromJson(json_.dump()));
}
}
return result;
}
};
size_t _writer(void* contents, size_t size, size_t nmemb,
std::vector<uint8_t>* s)
{
size_t newLength = size * nmemb;
s->reserve(newLength);
{
auto begin = (uint8_t*) contents;
auto end = ((uint8_t*) contents) + newLength;
std::copy(begin, end, std::back_inserter(*s));
}
return newLength;
}
APIAccess::APIAccess()
{
m_hCurl = curl_easy_init();
if (!m_hCurl)
throw APIException(APIError::Unknown, "Failed to initialize cURL");
// Allow HTTP/1, HTTP/2, HTTP/3
curl_easy_setopt(m_hCurl, CURLOPT_ALTSVC, "altsvc.txt");
curl_easy_setopt(m_hCurl, CURLOPT_ALTSVC_CTRL,
(long) CURLALTSVC_H1 | CURLALTSVC_H2 | CURLALTSVC_H3);
// Follow redirects, really important for downloads!
curl_easy_setopt(m_hCurl, CURLOPT_FOLLOWLOCATION, true);
curl_easy_setopt(m_hCurl, CURLOPT_WRITEFUNCTION, _writer);
#if (CURLPIPE_MULTIPLEX > 0)
/* Reuse existing connections */
curl_easy_setopt(m_hCurl, CURLOPT_PIPEWAIT, true);
#endif
}
APIAccess::~APIAccess()
{
curl_easy_cleanup(m_hCurl);
}
std::vector<uint8_t> APIAccess::requestRaw(std::string_view svURL,
Method eMethod,
std::vector<uint8_t> vBody)
{
curl_easy_setopt(m_hCurl, CURLOPT_URL, svURL.data());
std::vector<uint8_t> vResultingData{};
curl_easy_setopt(m_hCurl, CURLOPT_WRITEDATA, &vResultingData);
CURLcode hResult = curl_easy_perform(m_hCurl);
if (hResult != CURLE_OK)
throw new APIException(APIError::Unknown, curl_easy_strerror(hResult));
return vResultingData;
}
std::string APIAccess::requestString(std::string_view svURL, Method eMethod,
std::vector<uint8_t> vBody)
{
auto data = requestRaw(svURL, eMethod, std::move(vBody));
return std::string(data.begin(), data.end());
}
bool APIAccess::isConnected()
{
// This will just throw if we failed to establish an connection
try
{
APIAccess::requestRaw("https://api.chimu.moe/");
return true;
}
catch (const APIException& exception)
{
std::cout << exception.what() << std::endl;
return false;
}
}
BeatmapSet APIAccess::getBeatmapSet(uint32_t iSetID)
{
auto result = requestJSON<APIResult<BeatmapSet>>(
fmt::format("{}/v1/set/{}", CHIMU_ENDPOINT, iSetID));
if (result.m_iCode != 0)
throw APIException((APIError) result.m_iCode, result.m_sMessage);
return result.m_tData;
}
Beatmap APIAccess::getBeatmap(uint32_t iBeatmapID)
{
auto result = requestJSON<APIResult<Beatmap>>(
fmt::format("{}/v1/map/{}", CHIMU_ENDPOINT, iBeatmapID));
if (result.m_iCode != 0)
throw APIException((APIError) result.m_iCode, result.m_sMessage);
return result.m_tData;
}
std::vector<BeatmapSet> APIAccess::Search(
std::string_view sQuery, uint32_t iAmount, uint32_t iOffset,
RankedStatus eStatus, PlayMode eMode, Genre eGenre, Language eLanguage,
float fMinAR, float fMaxAR, float fMinOD, float fMaxOD, float fMinCS,
float fMaxCS, float fMinHP, float fMaxHP, float fMinDiff, float fMaxDiff,
float fMinBPM, float fMaxBPM, int32_t iMinLength, int32_t iMaxLength)
{
std::string q = "?query=" + std::string(sQuery);
q += fmt::format("&amount={}", iAmount);
q += fmt::format("&offset={}", iOffset);
if (eStatus != RankedStatus::Any)
q += fmt::format("&status={}", (int) eStatus);
if (eMode != PlayMode::Any) q += fmt::format("&mode={}", (int) eMode);
if (eGenre != Genre::Any) q += fmt::format("&genre={}", (int) eGenre);
if (eLanguage != Language::Any)
q += fmt::format("&language={}", (int) eLanguage);
q += fmt::format("&min_ar={}", fMinAR);
q += fmt::format("&min_od={}", fMinOD);
q += fmt::format("&min_cs={}", fMinCS);
q += fmt::format("&min_hp={}", fMinHP);
q += fmt::format("&min_diff={}", fMinDiff);
q += fmt::format("&min_bpm={}", fMinBPM);
q += fmt::format("&min_length={}", iMinLength);
q += fmt::format("&max_ar={}", fMaxAR);
q += fmt::format("&max_od={}", fMaxOD);
q += fmt::format("&max_cs={}", fMaxCS);
q += fmt::format("&max_hp={}", fMaxHP);
q += fmt::format("&max_diff={}", fMaxDiff);
q += fmt::format("&max_bpm={}", fMaxBPM);
q += fmt::format("&max_length={}", iMaxLength);
auto rawJson =
requestString(fmt::format("{}/v1/search{}", CHIMU_ENDPOINT, q));
auto result = APIResult<BeatmapSet>::fromJsonVector(rawJson);
if (result.m_iCode != 0)
throw APIException((APIError) result.m_iCode, result.m_sMessage);
return result.m_tData;
}
std::vector<uint8_t> APIAccess::download(uint32_t iSetID, bool bNoVideo)
{
auto result = requestRaw(fmt::format(
"{}/v1/download/{}?n={}", CHIMU_ENDPOINT, iSetID, (int) bNoVideo));
if (result.size() > 2 && result[0] == '{' && result[1] == '"')
{
auto _result =
APIResult<Beatmap>::fromJson((const char*) result.data());
if (_result.m_iCode != 0)
throw APIException((APIError) _result.m_iCode, _result.m_sMessage);
}
return requestRaw(fmt::format("{}/v1/download/{}?n={}", CHIMU_ENDPOINT,
iSetID, (int) bNoVideo));
}
Beatmap Beatmap::fromJson(const std::string_view& svData)
{
auto json = nlohmann::json::parse(svData);
Beatmap beatmap;
beatmap.m_iBeatmapID = json["BeatmapId"];
beatmap.m_iParentSetID = json["ParentSetId"];
beatmap.m_sDiffName = json["DiffName"];
beatmap.m_sFileMD5 = json["FileMD5"];
beatmap.m_eMode = json["Mode"];
beatmap.m_fBPM = json["BPM"];
beatmap.m_fAR = json["AR"];
beatmap.m_fOD = json["OD"];
beatmap.m_fCS = json["CS"];
beatmap.m_fHP = json["HP"];
beatmap.m_iTotalLength = json["TotalLength"];
beatmap.m_iHitLength = json["HitLength"];
beatmap.m_iPlayCount = json["Playcount"];
beatmap.m_iPassCount = json["Passcount"];
beatmap.m_iMaxCombo = json["MaxCombo"];
beatmap.m_fDifficultyRating = json["DifficultyRating"];
beatmap.m_sOsuFile = json["OsuFile"];
beatmap.m_sDownloadPath = json["DownloadPath"];
return beatmap;
}
BeatmapSet BeatmapSet::fromJson(const std::string_view& svData)
{
auto json = nlohmann::json::parse(svData);
BeatmapSet beatmapSet;
beatmapSet.m_uSetID = json["SetId"];
beatmapSet.m_eRankedStatus = json["RankedStatus"];
for (auto json_ : json["ChildrenBeatmaps"])
{
beatmapSet.m_vChildrenBeatmaps.push_back(
Beatmap::fromJson(json_.dump()));
}
beatmapSet.m_sApprovedDate = json["ApprovedDate"];
beatmapSet.m_sLastUpdate = json["LastUpdate"];
beatmapSet.m_sLastChecked = json["LastChecked"];
beatmapSet.m_sArtist = json["Artist"];
beatmapSet.m_sTitle = json["Title"];
beatmapSet.m_sCreator = json["Creator"];
beatmapSet.m_sSource = json["Source"];
beatmapSet.m_sTags = json["Tags"];
beatmapSet.m_eGenre = json["Genre"];
beatmapSet.m_eLanguage = json["Language"];
beatmapSet.m_uFavourites = json["Favourites"];
beatmapSet.m_bHasVideo = json["HasVideo"];
beatmapSet.m_bIsDisabled = json["Disabled"];
return beatmapSet;
}
| 29.711268 | 79 | 0.628229 | [
"vector"
] |
275027e0eb27ad9b11231f5a2a7fc03f5887218a | 9,250 | cpp | C++ | oldsrc/calcBtrajfromCoils.cpp | ron2015schmitt/coildes | 2583bc1beb6b5809ed75367970e4f32ba242894a | [
"MIT"
] | null | null | null | oldsrc/calcBtrajfromCoils.cpp | ron2015schmitt/coildes | 2583bc1beb6b5809ed75367970e4f32ba242894a | [
"MIT"
] | null | null | null | oldsrc/calcBtrajfromCoils.cpp | ron2015schmitt/coildes | 2583bc1beb6b5809ed75367970e4f32ba242894a | [
"MIT"
] | null | null | null | /*************************************************************************
*
* File Name :
* Platform : gnu C++ compiler
* Author : Ron Schmitt
* Date :
*
*
* SYNOPSIS
* Calculate Bfield trajectory
*
**************************************************************************/
// Standard C libraries
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <ctime>
// Standard C++ libraries
#include <iostream>
#include <complex>
using namespace std;
// coil libraries
#include "coils.hpp"
#include "coilio.hpp"
#include "coils_cmdline.hpp"
#include "surface.hpp"
// field-line following code
#include "calcPoincare.hpp"
#include "bfield_coils.hpp"
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
const double NEGLECT = 1e-12;
// Main Function for code
int main (int argc, char *argv[])
{
disable_all_options();
enable_option(opt_cf);
enable_option(opt_if);
enable_option(opt_Nphi);
enable_option(opt_Ntheta);
enable_option(opt_Nnn);
enable_option(opt_Nmm);
enable_option(opt_xyz);
enable_option(opt_rzp);
enable_option(opt_NperCycle);
enable_option(opt_Ncircuits);
enable_option(opt_Itoroidal);
enable_option(opt_Ipoloidal);
enable_option(opt_Nharm);
enable_option(opt_Mharm);
enable_option(opt_append);
// parse command line input
if (!parse_cmd(argc, argv))
return 1;
printcr("----------------------------------------------------");
for(int i=0; i<argc; i++){
print(argv[i]);
print(" ");
}
cr();
printcr("----------------------------------------------------");
ostringstream strmtemp;
string fname;
string fext = "out";
// string fext = plasma_extname;
// ios_base::fmtflags flags = ios_base::right | ios_base::scientific;
string ftemp;
p3vectorformat::textformat(text_nobraces);
// variables for measuring times
// struct tms tbuff;
// clock_t ckstart;
// display Matricks mode
cout << endl;
display_execution_mode();
cout << endl;
bool append_data;
if (append_filename == "")
append_data = false;
else
append_data =true;
setupcoils(coil_filename, current_filename, Itoroidal, Ipoloidal,
Nnn, Nmm, Nphi, Ntheta, Nharm, Mharm);
dispcr(Itoroidal);
dispcr(Ipoloidal);
dispcr(NperCycle);
dispcr(Ncircuits);
static int Ncircuits_planned = Ncircuits;
// in cylindrical (R,Z,phi) coords
// starting point should be on the plasma surface
p3vector<double> startPosition(r0,z0,phi0);
unsigned int Np1 = 0;
unsigned int Nc1 = 0;
if (append_data) {
// const unsigned int LINESZ = 1024;
string line;
std::ifstream in;
in.open(append_filename.data(),std::ios::in);
if (!in) {
cant_open_file(append_filename);
return 1;
}
getline(in,line);
// dispcr(line);
in.close();
sscanf(line.data(),"%% NperCycle = %d; Ncircuits = %d",&Np1,&Nc1);
cout<< "According to file header, '"<<append_filename<<"'" <<endl;
cout << "has "<<Nc1<< " circuits of data at "<<Np1<<" datapoints per circuit."<<endl;
if (Np1 != NperCycle) {
cerr<< "ERROR: Number of datapoints per cycle at command line ("<<NperCycle<<") does not match that in file("<<Np1<<")."<<endl;
print(myname);printcr(": aborting.");
return (2);
}
if (Nc1 >= Ncircuits) {
cout<< "Desired number of cycles ("<<Ncircuits << ") already calculated!"<<endl;
return (0);
}
p3vector<double> PreviousStopPosition = startPosition;
// get the last datapoint, which overrides command line position
if (Nc1 > 0) {
Vector<p3vector<double> > Bpath_rzp(0,"Bpath_rzp");
Bpath_rzp = p3vector<double>(0,0,0);
Bpath_rzp.textformat(text_nobraces);
Bpath_rzp.perline(1);
if (load(Bpath_rzp,append_filename)) {
printcr("Above ERROR occurred in "+myname+".");
return 4;
}
if (Bpath_rzp.size()!=(Np1*Nc1)) {
cerr<< "ERROR: Number of datapoints in file ("<<Bpath_rzp.size()<<") does not match values given in file header, (NperCycle = "<<Np1<<") * (Ncircuits = "<<Nc1<<") = "<<(Np1*Nc1)<<"."<<endl;
print(myname);printcr(": aborting.");
return (5);
}
PreviousStopPosition = Bpath_rzp[Bpath_rzp.size()-1];
strmtemp <<"% NperCycle = "<<Np1 << "; Ncircuits = "<<Nc1<<";";
string preamble_string(strmtemp.str());
strmtemp.str("");
// dispcr(preamble_string);
fname = "Bpath.fromcoils.temp.rzp.out";
printcr("Copying existing data to:");
dispcr(fname);
Bpath_rzp.textformat(text_nobraces);
Bpath_rzp.perline(1);
save(Bpath_rzp,fname,std::ios::trunc,preamble_string);
// in.open(append_filename.data(),std::ios::in);
// if (!in) {
// cant_open_file(append_filename);
// return 1;
// }
// int cntr=0;
// while (in.good()) {
// if (!(in >> PreviousStopPosition).fail())
// cntr++;
// }
// in.close();
// if (cntr!=(Np1*Nc1)) {
// cerr<< "ERROR: Number of datapoints in file ("<<cntr<<") does not match values given in file header, (NperCycle = "<<Np1<<") * (Ncircuits = "<<Nc1<<") = "<<(Np1*Nc1)<<"."<<endl;
// print(myname);printcr(": aborting.");
// return (3);
// }
}
dispcr(PreviousStopPosition);
if ( ( PreviousStopPosition[0] == 0) && ( PreviousStopPosition[1] == 0) && ( PreviousStopPosition[2] == 0) ) {
cerr<< "ERROR: Previous Stopping Position is all zeros."<<endl;
print(myname);printcr(": aborting.");
return (6);
}
cout<<"Data will be appended to '"<<append_filename<<"'."<<endl;
p3vector<double> position(0,0,0);
calc_1pt_Poincare(position,PreviousStopPosition);
startPosition = position;
Ncircuits_planned = Ncircuits - Nc1;
}
dispcr(startPosition);
const unsigned int Npts = NperCycle*Ncircuits_planned;
Vector<p3vector<double> > Bpath_rzp(Npts,"Bpath_rzp");
Bpath_rzp = p3vector<double>(0,0,0);
Bpath_rzp.textformat(text_nobraces);
Bpath_rzp.perline(1);
cout << "Calculating "<<Ncircuits_planned<<" circuits of datapoints..."<<endl;
int Ncircuits_actual = Ncircuits_planned;
if (calcPoincare(Bpath_rzp,startPosition,Ncircuits_actual,NperCycle) > 1) {
}
dispcr(Ncircuits_actual);
// Vector<p3vector<double> > Bpath_xyz(Npts,"Bpath_xyz");
// Bpath_xyz.textformat(text_nobraces);
// Bpath_xyz.perline(1);
// Vector<p3vector<double> > B(Npts,"B");
// B.textformat(text_nobraces);
// B.perline(1);
// Vector<p3vector<double> > Brzp(Npts,"Brzp");
// Brzp.textformat(text_nobraces);
// Brzp.perline(1);
// Vector<double> Bmag(Npts,"Bmag");
// Bmag.textformat(text_nobraces);
// Bmag.perline(1);
// for (unsigned int i =0; i<Npts; i++) {
// const double r = Bpath_rzp[i][0];
// const double z = Bpath_rzp[i][1];
// const double phi = Bpath_rzp[i][2];
// p3vector<double> X;
// X.x() = r*cos(phi);
// X.y() = r*sin(phi);
// X.z() = z;
// bTotal(X,B[i]);
// Bmag[i] = norm(B[i]);
// Brzp[i][0] = B[i].x()*cos(phi) + B[i].y()*sin(phi);
// Brzp[i][1] = B[i].z();
// Brzp[i][2] = -B[i].x()*sin(phi) + B[i].y()*cos(phi);
// // Bpath_xyz[i]= X;
// }
// dispcr(min(Bmag));
// dispcr(sum(Bmag)/N);
// dispcr(max(Bmag));
// save(Bpath_xyz,"Bpath.fromcoils.xyz.out");
const unsigned int Npts_actual = NperCycle*Ncircuits_actual;
if (Ncircuits_actual != Ncircuits_planned) {
dispcr(Npts_actual);
Vector<p3vector<double> > Bpath_temp(Npts_actual,"Bpath_temp");
for(unsigned int i = 0; i < Npts_actual; i++) {
Bpath_temp[i] = Bpath_rzp[i];
}
Bpath_rzp.resize() = Bpath_temp;
}
strmtemp <<"% NperCycle = "<<NperCycle << "; Ncircuits = "<<Ncircuits_actual<<";";
string preamble_string(strmtemp.str());
strmtemp.str("");
// dispcr(preamble_string);
Bpath_rzp.textformat(text_nobraces);
Bpath_rzp.perline(1);
fname = "Bpath.fromcoils.rzp.out";
dispcr(fname);
save(Bpath_rzp,fname,std::ios::trunc,preamble_string);
if (append_data) {
// load in previous data points
Bpath_rzp.clear();
fname = "Bpath.fromcoils.temp.rzp.out";
if (load(Bpath_rzp,fname)) {
printcr("Above ERROR occurred in "+myname+".");
return 7;
}
// now save previous data points with new header
strmtemp <<"% NperCycle = "<<NperCycle << "; Ncircuits = "<<(Ncircuits_actual+Nc1)<<";";
string preamble_string(strmtemp.str());
strmtemp.str("");
Bpath_rzp.textformat(text_nobraces);
Bpath_rzp.perline(1);
save(Bpath_rzp,append_filename,std::ios::trunc,preamble_string);
// load back new data points
Bpath_rzp.clear();
fname = "Bpath.fromcoils.rzp.out";
if (load(Bpath_rzp,fname)) {
printcr("Above ERROR occurred in "+myname+".");
return 9;
}
// now append the new data to file
Bpath_rzp.textformat(text_nobraces);
Bpath_rzp.perline(1);
save(Bpath_rzp,append_filename,std::ios::app);
}
// save(NperCycle,"NperCycle.out");
// save(Ncircuits_actual+Nc1,"Ncircuits.out");
// save(Bmag,"Bmag.intrajfromcoils.out");
// save(B,"B.intrajfromcoils.out");
// save(Brzp,"Brzp.intrajfromcoils.out");
return 0;
} // main()
| 26.353276 | 194 | 0.604973 | [
"vector"
] |
27565936c2847580f4bbb43ebed4eb8036be9657 | 4,656 | cpp | C++ | sslhook/pcap.cpp | MicrohexHQ/sslhook | 070873846ed23f54f55612da8b78a746e609a919 | [
"MIT"
] | 42 | 2015-04-22T01:32:26.000Z | 2021-09-06T12:15:39.000Z | sslhook/pcap.cpp | MicrohexHQ/sslhook | 070873846ed23f54f55612da8b78a746e609a919 | [
"MIT"
] | null | null | null | sslhook/pcap.cpp | MicrohexHQ/sslhook | 070873846ed23f54f55612da8b78a746e609a919 | [
"MIT"
] | 17 | 2015-04-22T01:32:28.000Z | 2021-09-28T04:15:00.000Z | //
// pcap.cpp
//
// Simple routines for writing socket data into PCAP format
//
// www.catch22.net
//
// Copyright (C) 2012 James Brown
// Please refer to the file LICENCE.TXT for copying permission
//
#include <WinSock2.h>
#include <stdio.h>
#include <time.h>
#include "pcap.h"
#pragma pack(push, 1)
typedef unsigned int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef int int32;
#define PCAP_MAGIC 0xa1b2c3d4
#define PCAP_VER_MAJOR 2
#define PCAP_VER_MINOR 4
#define LINKTYPE_NULL 0
#define LINKTYPE_ETHERNET 1
#define LINKTYPE_IPV4 228
#define LINKTYPE_IPV6 229
#define IP_PROTO_TCP 6
#define PCAP_SENDING 1
#define PCAP_RECEIVING 2
// PCAP file header
typedef struct pcap_hdr_s {
uint32 magic_number; // magic number
uint16 version_major; // major version number
uint16 version_minor; // minor version number
int32 thiszone; // GMT to local correction
uint32 sigfigs; // accuracy of timestamps
uint32 snaplen; // max length of captured packets, in octets
uint32 network; // data link type
} pcap_hdr_t;
// PCAP packet header
typedef struct pcaprec_hdr_s {
uint32 ts_sec; // timestamp seconds
uint32 ts_usec; // timestamp microseconds
uint32 incl_len; // number of octets of packet saved in file
uint32 orig_len; // actual length of packet
} pcaprec_hdr_t;
// IP header
typedef struct ip_hdr_s {
uint8 verlen; // 4bits version, 4bits header len
uint8 service; // 0
uint16 len; //
uint16 id;
uint8 flags;
uint8 fragoff;
uint8 ttl;
uint8 protocol;
uint16 checksum;
uint32 source;
uint32 dest;
} ip_hdr;
// TCP header
typedef struct tcp_hdr_s
{
uint16 srcport;
uint16 dstport;
uint32 seq;
uint32 ack;
uint8 len;
uint8 flags;
uint16 winsize;
uint16 checksum;
uint16 padding;
} tcp_hdr;
#pragma pack(pop)
//
// Initialize the PCAP file using an existing FILE*
// The returned PCAP object must be used in future
// calls to write_pcap
//
PCAP * pcap_init(FILE *fp)
{
PCAP *p;
if((p = (PCAP*)malloc(sizeof(PCAP))) == 0)
return 0;
p->fp = fp;
p->ack = 1;
p->seq = 1;
// pcap file header
pcap_hdr_t hdr =
{
PCAP_MAGIC, // magic
PCAP_VER_MAJOR, // version major
PCAP_VER_MINOR, // version minor
0, // GMT timezone offset
0, // timestamp accuracy
0xFFFF, // max length of packets
LINKTYPE_IPV4 // data link type
};
fwrite(&hdr, sizeof(hdr), 1, fp);
return p;
}
static void pcap_write(PCAP *p, int flags, void *buf, size_t len, SOCKADDR_IN *source, SOCKADDR_IN *dest)
{
size_t total_len = sizeof(ip_hdr) + sizeof(tcp_hdr) + len;
short id = 0;
clock_t t = clock();
// write pcap header
pcaprec_hdr_t hdr =
{
(int32)(t / CLOCKS_PER_SEC),
(int32)(t % CLOCKS_PER_SEC) * CLOCKS_PER_SEC,
total_len,
total_len
};
fwrite(&hdr, sizeof(hdr), 1, p->fp);
uint32 destaddr, srcaddr;
uint16 destport;//, srcport;
//uint32 seqnum, acknum;
if(flags & PCAP_SENDING)
{
destaddr = dest->sin_addr.S_un.S_addr;
destport =
srcaddr = source->sin_addr.S_un.S_addr;
}
// write IP header
ip_hdr ip =
{
0x45, // version 4, 20 bytes
0x00,
htons(total_len), // total length
htons(id), // identification
0x40, // flags
0x00,
0x80, // ttl
IP_PROTO_TCP, // protocol = tcp
0x0000, // no checksum
flags & PCAP_SENDING ? source->sin_addr.S_un.S_addr : dest->sin_addr.S_un.S_addr,
flags & PCAP_SENDING ? dest->sin_addr.S_un.S_addr : source->sin_addr.S_un.S_addr,
};
fwrite(&ip, sizeof(ip), 1, p->fp);
uint32 seq = flags & PCAP_SENDING ? p->seq : p->ack;
uint32 ack = flags & PCAP_SENDING ? p->ack : p->seq;
// tcp header
tcp_hdr tcp =
{
flags & PCAP_SENDING ? source->sin_port : htons(80),
flags & PCAP_SENDING ? htons(80) : source->sin_port,
htonl(seq), // seq
htonl(ack), // ack
0x50, // length (20 bytes)
0x18, // PSH,ACK
htons(16425), // window size
0x0000, // checksum
0x0000 // padding
};
fwrite(&tcp, sizeof(tcp), 1, p->fp);
// update the TCP sequence numbers AFTER writing the TCP header
if(flags & PCAP_SENDING) p->seq += len;
else p->ack += len;
// finally write the IP payload
fwrite(buf, 1, len, p->fp);
}
void pcap_data_send(PCAP *p, void *buf, size_t len, SOCKADDR_IN *local, SOCKADDR_IN *peer)
{
pcap_write(p, PCAP_SENDING, buf, len, local, peer);
}
void pcap_data_recv(PCAP *p, void *buf, size_t len, SOCKADDR_IN *local, SOCKADDR_IN *peer)
{
pcap_write(p, PCAP_RECEIVING, buf, len, local, peer);
}
void pcap_free(PCAP *p)
{
free(p);
}
| 22.171429 | 105 | 0.659364 | [
"object"
] |
27594a892fd04c3b6a90b81fb02e4729e397ff38 | 4,041 | cpp | C++ | Tankerfield/Tankerfield/Obj_RewardBox.cpp | gamificalostudio/Tankerfield | f3801c5286ae836c0fd62392cc14be081b5c74e8 | [
"MIT"
] | 7 | 2019-03-11T11:31:36.000Z | 2019-05-18T08:03:35.000Z | Tankerfield/Tankerfield/Obj_RewardBox.cpp | gamificalostudio/Tankerfield | f3801c5286ae836c0fd62392cc14be081b5c74e8 | [
"MIT"
] | 86 | 2019-03-27T14:36:16.000Z | 2019-06-10T18:43:52.000Z | Tankerfield/Tankerfield/Obj_RewardBox.cpp | gamificalostudio/Tankerfield | f3801c5286ae836c0fd62392cc14be081b5c74e8 | [
"MIT"
] | 1 | 2019-09-10T17:37:44.000Z | 2019-09-10T17:37:44.000Z |
#include "Brofiler/Brofiler.h"
#include "PugiXml\src\pugixml.hpp"
#include "Obj_RewardBox.h"
#include "App.h"
#include "M_Render.h"
#include "M_Collision.h"
#include "M_PickManager.h"
#include "M_Map.h"
#include "M_Audio.h"
#include "Obj_ElectroShotAnimation.h"
#include "M_Scene.h"
#include "Obj_SpawnPoint.h"
Obj_RewardBox::Obj_RewardBox(fPoint pos) : Object(pos)
{
pugi::xml_node reward_box_node = app->config.child("object").child("reward_box");
reward_box_dead_sound_string = reward_box_node.child("crash_sound").attribute("value").as_string();
reward_box_dead_sound_int = app->audio->LoadFx(reward_box_dead_sound_string, 100);
reward_box_hit_sound_string = reward_box_node.child("hit_sound").attribute("value").as_string();
reward_box_hit_sound_int = app->audio->LoadFx(reward_box_hit_sound_string, 100);
texture = app->tex->Load(reward_box_node.child("image_path").attribute("value").as_string());
curr_tex = texture;
frame = default_frame = { 0, 0, 45, 34 };
frame_white = { 45, 0, 45, 34 };
shadow_frame = { 90, 0, 45, 34 };
draw_offset = { 14, 27 };
float coll_w = 0.75f;
float coll_h = 0.75f;
coll = app->collision->AddCollider(pos, coll_w ,coll_h , TAG::REWARD_BOX, BODY_TYPE::STATIC ,0.f, this);
coll->SetObjOffset({ -coll_w * 0.75f, -coll_h * 0.75f });
}
Obj_RewardBox::~Obj_RewardBox()
{
}
bool Obj_RewardBox::Update(float dt)
{
if (is_white
&& timer_white.ReadSec() >= max_time_in_white)
{
frame = default_frame;
is_white = false;
}
return true;
}
void Obj_RewardBox::OnTriggerEnter(Collider * collider, float dt)
{
TakeDamage(collider);
}
void Obj_RewardBox::OnTrigger(Collider * collider, float dt)
{
TakeDamage(collider);
}
bool Obj_RewardBox::DrawShadow(Camera * camera, float dt)
{
app->render->Blit(
curr_tex,
pos_screen.x - draw_offset.x,
pos_screen.y - draw_offset.y,
camera,
&shadow_frame);
return true;
}
void Obj_RewardBox::Dead()
{
uint probability = rand() % 100;
if (type == PICKUP_TYPE::NO_TYPE)
{
if (probability < 15)
{
app->pick_manager->CreatePickUp(pos_map, PICKUP_TYPE::ITEM);
}
else if (probability < 25)
{
fPoint offset{ 0.5f,0 };
app->pick_manager->CreatePickUp(pos_map - offset, PICKUP_TYPE::ITEM);
app->pick_manager->CreatePickUp(pos_map + offset, PICKUP_TYPE::ITEM);
}
else if (probability < 75)
{
app->pick_manager->CreatePickUp(pos_map, PICKUP_TYPE::WEAPON);
}
else if (probability < 100)
{
app->pick_manager->CreatePickUp(pos_map, PICKUP_TYPE::WEAPON, ItemType::MAX_ITEMS, WEAPON::MAX_WEAPONS, app->scene->round + 1u);
}
if (my_spawn_point != nullptr)
{
my_spawn_point->occupied = false;
}
}
else
{
app->pick_manager->CreatePickUp(pos_map, type);
}
to_remove = true;
app->audio->PlayFx(reward_box_dead_sound_int);
}
void Obj_RewardBox::SetTypeBox(PICKUP_TYPE type)
{
this->type = type;
}
void Obj_RewardBox::TakeDamage(Collider* collider)
{
if (collider->GetTag() == TAG::BULLET || collider->GetTag() == TAG::FRIENDLY_BULLET || collider->GetTag() == TAG::BULLET_LASER || collider->GetTag() == TAG::BULLET_OIL || collider->GetTag() == TAG::FLAMETHROWER)
{
++hits_taken;
if (hits_taken >= max_hits)
{
Dead();
}
else
{
is_white = true;
frame = frame_white;
timer_white.Start();
}
app->audio->PlayFx(reward_box_hit_sound_int);
}
else if (collider->GetTag() == TAG::ELECTRO_SHOT)
{
++hits_taken;
if (hits_taken > max_hits)
{
Dead();
}
else
{
is_white = true;
frame = frame_white;
timer_white.Start();
}
Obj_Tank* player = (Obj_Tank*)collider->GetObj();
Eletro_Shot_Animation* electro_anim = (Eletro_Shot_Animation*)app->objectmanager->CreateObject(ObjectType::ELECTRO_SHOT_ANIMATION, player->pos_map);
electro_anim->tank = player;
electro_anim->draw_offset -= (iPoint)app->map->MapToScreenF(player->GetShotDir());
electro_anim->enemy_pos_screen = pos_screen;
electro_anim->enemy_pos_map = pos_map;
electro_anim->hit_no_enemie = false;
app->audio->PlayFx(reward_box_hit_sound_int);
}
}
| 23.631579 | 212 | 0.702301 | [
"render",
"object"
] |
27661a2c45c6be0911d555a2f29ad032b9f749f5 | 408 | cc | C++ | solutions/Leetcode_775/leetcode_775.cc | YuhanShi53/Leetcode_solutions | cdcad34656d25d6af09b226e17250c6070305ab0 | [
"MIT"
] | null | null | null | solutions/Leetcode_775/leetcode_775.cc | YuhanShi53/Leetcode_solutions | cdcad34656d25d6af09b226e17250c6070305ab0 | [
"MIT"
] | null | null | null | solutions/Leetcode_775/leetcode_775.cc | YuhanShi53/Leetcode_solutions | cdcad34656d25d6af09b226e17250c6070305ab0 | [
"MIT"
] | null | null | null | #include <cmath>
#include <iostream>
#include <vector>
using namespace std;
class Solution1
{
public:
bool isIdealPermutation(vector<int> &A)
{
for (int i = 0; i != A.size(); ++i)
if (abs(A[i] - i) > 1)
return false;
return true;
}
};
int main()
{
vector<int> A{1, 0};
bool ans = Solution1().isIdealPermutation(A);
cout << ans << endl;
} | 17 | 49 | 0.536765 | [
"vector"
] |
276899703b6f1bc8f284a30a4368bec9f7ab59e9 | 1,604 | hpp | C++ | libsamp/libxrpc/xmlrpc-c-1.16.29/tools/xmlrpc_cpp_proxy/xmlrpcMethod.hpp | olebole/voclient | abeee7783f4e84404a8c3a9646bb57f48988b24a | [
"MIT"
] | 4 | 2018-10-31T05:46:30.000Z | 2018-10-31T11:11:52.000Z | libsamp/libxrpc/xmlrpc-c-1.16.29/tools/xmlrpc_cpp_proxy/xmlrpcMethod.hpp | mjfitzpatrick/voclient | 3264c0df294cecc518e5c6a7e6b2aba3f1c76373 | [
"MIT"
] | 1 | 2019-11-30T13:48:50.000Z | 2019-12-02T19:40:25.000Z | libsamp/libxrpc/xmlrpc-c-1.16.29/tools/xmlrpc_cpp_proxy/xmlrpcMethod.hpp | mjfitzpatrick/voclient | 3264c0df294cecc518e5c6a7e6b2aba3f1c76373 | [
"MIT"
] | 2 | 2018-10-31T05:46:31.000Z | 2018-10-31T10:58:51.000Z | #ifndef XMLRPCMETHOD_HPP
#define XMLRPCMETHOD_HPP
#include <string>
#include <iostream>
#include <xmlrpc-c/base.hpp>
class xmlrpcMethod {
// An object of this class contains everything we know about a
// given XML-RPC method, and knows how to print local bindings.
std::string mFunctionName;
std::string mMethodName;
std::string mHelp;
xmlrpc_c::value_array mSynopsis;
public:
xmlrpcMethod(std::string const& function_name,
std::string const& method_name,
std::string const& help,
xmlrpc_c::value_array const& signatureList);
xmlrpcMethod(xmlrpcMethod const& f);
xmlrpcMethod& operator= (xmlrpcMethod const& f);
void
printDeclarations(std::ostream& out) const;
void
printDefinitions(std::ostream & out,
std::string const& className) const;
private:
void
printParameters(std::ostream & out,
size_t const synopsis_index) const;
void
printDeclaration(std::ostream & out,
size_t const synopsis_index) const;
void
printDefinition(std::ostream & out,
std::string const& className,
size_t const synopsis_index) const;
const xmlrpcType&
returnType(size_t const synopsis_index) const;
size_t
parameterCount(size_t const synopsis_index) const;
const xmlrpcType&
parameterType(size_t const synopsis_index,
size_t const parameter_index) const;
};
#endif
| 26.733333 | 67 | 0.620324 | [
"object"
] |
2770c7968e8832dbab5d82225e7d4b8f2b2b9e8c | 2,424 | cpp | C++ | src/PlainFileReader.cpp | KeluDiao/HARENS | c4f0608ee9001044bf916cc18d3dd6576cd18783 | [
"Apache-2.0"
] | 1 | 2020-05-12T02:43:46.000Z | 2020-05-12T02:43:46.000Z | src/PlainFileReader.cpp | ipapapa/HARENS | 13c44c915f18f288750b61d91d7173646e814b29 | [
"Apache-2.0"
] | 1 | 2016-03-17T22:51:28.000Z | 2016-03-17T22:51:28.000Z | src/PlainFileReader.cpp | KeluDiao/HARENS | c4f0608ee9001044bf916cc18d3dd6576cd18783 | [
"Apache-2.0"
] | 3 | 2016-03-11T10:56:39.000Z | 2020-05-14T03:30:33.000Z | #include "PlainFileReader.h"
/*
* Set up a file stream for plain file.
*/
void PlainFileReader::SetupFile(char* filename) {
ifs = new std::ifstream(filename, std::ios::in | std::ios::binary | std::ios::ate);
if (!ifs->is_open()) {
fprintf(stderr, "Cannot open file %s\n", filename);
exit(EXIT_FAILURE);
}
fileLen = ifs->tellg();
ifs->seekg(0, ifs->beg);
curFilePos = 0;
}
PlainFileReader::PlainFileReader() {
buffer = new char[MAX_BUFFER_LEN];
}
PlainFileReader::~PlainFileReader() {
delete ifs;
delete[] buffer;
}
/*
* Set up the reader for a single file, and set up the first file
* Make sure the filename is not empty.
*/
void PlainFileReader::SetupReader(char* filename) {
filenameList = std::vector<char*>();
filenameList.push_back(filename);
fileNum = 1;
fileIdx = 0;
SetupFile(filenameList[fileIdx]);
}
/*
* Set up the reader for a file List, and set up the first file
* Make sure the filenameList is not empty.
*/
void PlainFileReader::SetupReader(std::vector<char*> _filenameList) {
filenameList = _filenameList;
fileNum = filenameList.size();
fileIdx = 0;
SetupFile(filenameList[fileIdx]);
}
/*
* Read the whole file into memory until it reaches the limit.
*/
void PlainFileReader::ReadChunk(FixedSizedCharArray &charArray, unsigned int readLen) {
//Clear char array
charArray.ClearArr(readLen);
unsigned int lenLimit = readLen;
//Fit the read length if there's not this much content
while (fileLen - curFilePos < readLen) {
if (fileIdx == fileNum - 1) { //No more files
readLen = fileLen - curFilePos;
break;
}
else { //Read current file and move on the the next one
//Read current file
ifs->read(buffer, fileLen - curFilePos);
charArray.Append(buffer, fileLen - curFilePos, fileLen - curFilePos);
readLen -= fileLen - curFilePos;
//Set up for next file
SetupFile(filenameList[++fileIdx]);
}
}
curFilePos += readLen;
ifs->read(buffer, readLen);
charArray.Append(buffer, readLen, lenLimit);
}
/*
* Read the whole file into memory
*/
char* PlainFileReader::ReadAll(char* filename) {
ifs = new std::ifstream(filename, std::ios::in | std::ios::binary | std::ios::ate);
if (!ifs->is_open()) {
fprintf(stderr, "Cannot open file %s\n", filename);
exit(EXIT_FAILURE);
}
fileLen = ifs->tellg();
ifs->seekg(0, ifs->beg);
curFilePos = 0;
char* fileContent = new char[fileLen];
ifs->read(fileContent, fileLen);
return fileContent;
} | 26.064516 | 87 | 0.695545 | [
"vector"
] |
2777d15d79735d7a07347257ae5ea5c0c591a8fd | 4,811 | cc | C++ | test/server.cc | tabokie/coplus | e9919c283af57e9366de68ab4b3ea92abc3ff6d4 | [
"MIT"
] | 13 | 2018-12-14T00:32:50.000Z | 2021-12-28T09:10:22.000Z | test/server.cc | tabokie/coplus | e9919c283af57e9366de68ab4b3ea92abc3ff6d4 | [
"MIT"
] | null | null | null | test/server.cc | tabokie/coplus | e9919c283af57e9366de68ab4b3ea92abc3ff6d4 | [
"MIT"
] | null | null | null | #include "coplus/socket.h"
#include "coplus/cotimer.h"
#include "coplus/protocol.h"
#include <string>
#include <sstream>
#include <cassert>
#include <iostream>
using namespace coplus;
int main(int argc, char** argv){
Server server("myServer");
// apply new socket
SOCKET socket;
std::string addr;
if(argc >= 3) {
addr = argv[1];
addr += ":";
addr += argv[2];
socket = Server::NewSocket(argv[1], argv[2]);
}
else if(argc == 2) {
addr = argv[1];
addr += ":";
addr += Server::kDefaultPort;
socket = Server::NewSocket(argv[1]);
}
else {
addr = "127.0.0.1";
addr += ":";
addr += Server::kDefaultPort;
socket = Server::NewSocket("127.0.0.1");
}
assert(socket != INVALID_SOCKET);
// read input and close server
std::atomic<bool> close = false;
std::thread daemon = std::thread([&]{
std::string str;
std::string terminator = "exit";
while(std::cin >> str) {
if(str == terminator) {
colog << "receive terminator";
server.Close();
break;
}
}
});
// serve single socket
std::cout << "server listening on " + addr << std::endl;
server.Serve(
socket,
// response when receiving client message
[&](SOCKET sender, const char* buf, size_t len, std::vector<std::string>& ret) {
static std::ostringstream str_helper;
static bool pending;
static std::string pendingStr;
static auto parse = [&](std::string in, std::string& out)-> int {
std::string head(Protocol::app_head_len, ' ');
memcpy((void*)head.c_str(), (void*)&Protocol::app_head, Protocol::app_head_len);
std::string tail(Protocol::app_terminator_len, ' ');
memcpy((void*)tail.c_str(), (void*)&Protocol::app_terminator, Protocol::app_terminator_len);
int h = in.find(head);
int t = in.find(tail);
bool has_head = (h != std::string::npos);
bool has_end = (t != std::string::npos);
if(has_head && !pending) {
if(has_end) {
str_helper.str("");
str_helper.clear();
out = Protocol::format_message(
str_helper,
in.substr(
h + Protocol::app_head_len,
t - h - Protocol::app_head_len
),
Protocol::kGetContent
);
colog << str_helper.str();
} else {
pending = true;
pendingStr = in.substr(
h + Protocol::app_head_len,
in.size() - Protocol::app_terminator_len - h - Protocol::app_head_len
);
}
} else if(pending) {
if(has_end) { // finish pending messaeg
pendingStr += in.substr(0, t);
str_helper.str("");
str_helper.clear();
out = Protocol::format_message(str_helper, pendingStr, Protocol::kGetContent);
colog << str_helper.str();
pending = false;
pendingStr.clear();
} else {
pendingStr += in;
}
}
return pending ? -1 : t + Protocol::app_terminator_len;
};
static auto dispatch = [&](std::string content) -> std::string {
std::string markers = "time|name|list|relay";
// search for markers
if(content.size() < 4) return "invalid request";
if(content.compare(0,4, markers, 0, 4) == 0) {
return Protocol::pickle_message(Protocol::kResponse, cotimer.describe());
}
else if(content.compare(0,4, markers, 5, 4) == 0) {
return Protocol::pickle_message(Protocol::kResponse, server.name());
}
else if(content.compare(0,4, markers, 10, 4) == 0) {
std::vector<std::string> header;
std::vector<std::string> entries;
server.OutputDatabase(header, entries);
return Protocol::pickle_message(Protocol::kResponse, header, entries);
}
else if(content.size() >= 5 && content.compare(0,5, markers, 15, 5) == 0) { // relay80:...
int id = atoi(content.c_str() + 5);
SOCKET target = server.GetClient(id);
if(target == INVALID_SOCKET) return Protocol::pickle_message(Protocol::kResponse, "invalid relay target");
int start = content.find(":");
if(target == sender) { // to avoid buffering
return Protocol::pickle_message(Protocol::kDirect, Server::GetPeerAddr(sender), content.substr(start + 1));
}
else{
return Protocol::pickle_message(
Protocol::kResponse,
"relay status = " +
std::to_string(
server.Send(
target,
Protocol::pickle_message(Protocol::kDirect, Server::GetPeerAddr(sender), content.substr(start + 1))
)
)
);
}
}
return "invalid request";
};
std::string line(len, ' '); // may be \0
memcpy((void*)line.c_str(), buf, len);
std::string content;
std::string str = "";
int cur = 0, delta;
while(true) {
if( cur >= line.size() || (delta = parse(line.substr(cur), content)) < 0 ) break; // find a pending
cur += delta;
str = dispatch(content);
if(str.size() > 0) ret.push_back(str);
}
}
);
daemon.join();
return 0;
} | 30.643312 | 113 | 0.606527 | [
"vector"
] |
2778039ff954cdd0e176529eca9f466def5525a4 | 1,040 | hpp | C++ | Include/Line.hpp | Const-me/VectorMath | de24feb13cb89e19b721b5a50ae1b1d14f5a66b9 | [
"MIT"
] | null | null | null | Include/Line.hpp | Const-me/VectorMath | de24feb13cb89e19b721b5a50ae1b1d14f5a66b9 | [
"MIT"
] | null | null | null | Include/Line.hpp | Const-me/VectorMath | de24feb13cb89e19b721b5a50ae1b1d14f5a66b9 | [
"MIT"
] | null | null | null | #pragma once
#include "Vector3.hpp"
#include "Vector4.hpp"
#include "Normal.hpp"
namespace cvm
{
class Line
{
// e41, e42, e43 components of the 4D bi-vector
Vector3 m_tangent;
// e23, e31, e12 components of the 4D bi-vector
Normal m_moment;
public:
Line() = default;
Line( const Line& that ) = default;
Line& operator=( const Line& that ) = default;
// Construct a line from 2 points
Line( const Vector3& a, const Vector3& b ) :
m_tangent( b - a ),
m_moment( impl::cross3( (VECTOR)a, (VECTOR)b ) ) { }
// Construct a line from 2 points
Line( const Vector4& a, const Vector4& b ) :
Line( Vector3{ impl::divideByW( VECTOR( a ) ) },
Vector3{ impl::divideByW( VECTOR( b ) ) } ) { }
// Load
Line( const FLOAT3x2& line ) :
m_tangent( line.a ), m_moment( line.b ) { }
// Store
void store( FLOAT3x2& line ) const
{
m_tangent.store( line.a );
m_moment.store( line.b );
}
const Vector3& tangent() const { return m_tangent; }
const Normal& moment() const { return m_moment; }
};
} | 24.186047 | 55 | 0.632692 | [
"vector"
] |
277da9c820f73b82843cbb7fbad86e48d99077b0 | 6,770 | cc | C++ | ecs/src/model/PurchaseReservedInstancesOfferingRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | ecs/src/model/PurchaseReservedInstancesOfferingRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | ecs/src/model/PurchaseReservedInstancesOfferingRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ecs/model/PurchaseReservedInstancesOfferingRequest.h>
using AlibabaCloud::Ecs::Model::PurchaseReservedInstancesOfferingRequest;
PurchaseReservedInstancesOfferingRequest::PurchaseReservedInstancesOfferingRequest()
: RpcServiceRequest("ecs", "2014-05-26", "PurchaseReservedInstancesOffering") {
setMethod(HttpRequest::Method::Post);
}
PurchaseReservedInstancesOfferingRequest::~PurchaseReservedInstancesOfferingRequest() {}
long PurchaseReservedInstancesOfferingRequest::getResourceOwnerId() const {
return resourceOwnerId_;
}
void PurchaseReservedInstancesOfferingRequest::setResourceOwnerId(long resourceOwnerId) {
resourceOwnerId_ = resourceOwnerId;
setParameter(std::string("ResourceOwnerId"), std::to_string(resourceOwnerId));
}
std::string PurchaseReservedInstancesOfferingRequest::getClientToken() const {
return clientToken_;
}
void PurchaseReservedInstancesOfferingRequest::setClientToken(const std::string &clientToken) {
clientToken_ = clientToken;
setParameter(std::string("ClientToken"), clientToken);
}
std::string PurchaseReservedInstancesOfferingRequest::getDescription() const {
return description_;
}
void PurchaseReservedInstancesOfferingRequest::setDescription(const std::string &description) {
description_ = description;
setParameter(std::string("Description"), description);
}
std::string PurchaseReservedInstancesOfferingRequest::getPlatform() const {
return platform_;
}
void PurchaseReservedInstancesOfferingRequest::setPlatform(const std::string &platform) {
platform_ = platform;
setParameter(std::string("Platform"), platform);
}
std::string PurchaseReservedInstancesOfferingRequest::getResourceGroupId() const {
return resourceGroupId_;
}
void PurchaseReservedInstancesOfferingRequest::setResourceGroupId(const std::string &resourceGroupId) {
resourceGroupId_ = resourceGroupId;
setParameter(std::string("ResourceGroupId"), resourceGroupId);
}
std::string PurchaseReservedInstancesOfferingRequest::getRegionId() const {
return regionId_;
}
void PurchaseReservedInstancesOfferingRequest::setRegionId(const std::string ®ionId) {
regionId_ = regionId;
setParameter(std::string("RegionId"), regionId);
}
std::string PurchaseReservedInstancesOfferingRequest::getScope() const {
return scope_;
}
void PurchaseReservedInstancesOfferingRequest::setScope(const std::string &scope) {
scope_ = scope;
setParameter(std::string("Scope"), scope);
}
std::string PurchaseReservedInstancesOfferingRequest::getInstanceType() const {
return instanceType_;
}
void PurchaseReservedInstancesOfferingRequest::setInstanceType(const std::string &instanceType) {
instanceType_ = instanceType;
setParameter(std::string("InstanceType"), instanceType);
}
std::vector<PurchaseReservedInstancesOfferingRequest::Tag> PurchaseReservedInstancesOfferingRequest::getTag() const {
return tag_;
}
void PurchaseReservedInstancesOfferingRequest::setTag(const std::vector<PurchaseReservedInstancesOfferingRequest::Tag> &tag) {
tag_ = tag;
for(int dep1 = 0; dep1 != tag.size(); dep1++) {
auto tagObj = tag.at(dep1);
std::string tagObjStr = std::string("Tag") + "." + std::to_string(dep1 + 1);
setParameter(tagObjStr + ".Key", tagObj.key);
setParameter(tagObjStr + ".Value", tagObj.value);
}
}
int PurchaseReservedInstancesOfferingRequest::getPeriod() const {
return period_;
}
void PurchaseReservedInstancesOfferingRequest::setPeriod(int period) {
period_ = period;
setParameter(std::string("Period"), std::to_string(period));
}
std::string PurchaseReservedInstancesOfferingRequest::getResourceOwnerAccount() const {
return resourceOwnerAccount_;
}
void PurchaseReservedInstancesOfferingRequest::setResourceOwnerAccount(const std::string &resourceOwnerAccount) {
resourceOwnerAccount_ = resourceOwnerAccount;
setParameter(std::string("ResourceOwnerAccount"), resourceOwnerAccount);
}
std::string PurchaseReservedInstancesOfferingRequest::getOwnerAccount() const {
return ownerAccount_;
}
void PurchaseReservedInstancesOfferingRequest::setOwnerAccount(const std::string &ownerAccount) {
ownerAccount_ = ownerAccount;
setParameter(std::string("OwnerAccount"), ownerAccount);
}
long PurchaseReservedInstancesOfferingRequest::getOwnerId() const {
return ownerId_;
}
void PurchaseReservedInstancesOfferingRequest::setOwnerId(long ownerId) {
ownerId_ = ownerId;
setParameter(std::string("OwnerId"), std::to_string(ownerId));
}
std::string PurchaseReservedInstancesOfferingRequest::getPeriodUnit() const {
return periodUnit_;
}
void PurchaseReservedInstancesOfferingRequest::setPeriodUnit(const std::string &periodUnit) {
periodUnit_ = periodUnit;
setParameter(std::string("PeriodUnit"), periodUnit);
}
std::string PurchaseReservedInstancesOfferingRequest::getOfferingType() const {
return offeringType_;
}
void PurchaseReservedInstancesOfferingRequest::setOfferingType(const std::string &offeringType) {
offeringType_ = offeringType;
setParameter(std::string("OfferingType"), offeringType);
}
std::string PurchaseReservedInstancesOfferingRequest::getZoneId() const {
return zoneId_;
}
void PurchaseReservedInstancesOfferingRequest::setZoneId(const std::string &zoneId) {
zoneId_ = zoneId;
setParameter(std::string("ZoneId"), zoneId);
}
std::string PurchaseReservedInstancesOfferingRequest::getReservedInstanceName() const {
return reservedInstanceName_;
}
void PurchaseReservedInstancesOfferingRequest::setReservedInstanceName(const std::string &reservedInstanceName) {
reservedInstanceName_ = reservedInstanceName;
setParameter(std::string("ReservedInstanceName"), reservedInstanceName);
}
int PurchaseReservedInstancesOfferingRequest::getInstanceAmount() const {
return instanceAmount_;
}
void PurchaseReservedInstancesOfferingRequest::setInstanceAmount(int instanceAmount) {
instanceAmount_ = instanceAmount;
setParameter(std::string("InstanceAmount"), std::to_string(instanceAmount));
}
| 34.717949 | 127 | 0.776514 | [
"vector",
"model"
] |
959ddab50c39cfbc4b74263c142c64e3c7fac529 | 976 | cpp | C++ | JianZhi_OFFER/JZ_50.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | JianZhi_OFFER/JZ_50.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | JianZhi_OFFER/JZ_50.cpp | drt4243566/leetcode_learn | ef51f215079556895eec2252d84965cd1c3a7bf4 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
char firstUniqChar(string s) {
// 使用哈希表保存单个字符出现的次数
unordered_map<char,int> dic;
// 记录出现的字符,并且去掉重复字符
vector<char> keys;
for(char c:s){
if(dic.find(c)==dic.end()){
keys.push_back(c);
}
dic[c]++;
}
// 此时遍历Vector,
for(char c:keys){
if(dic[c]==1) return c;
}
return ' ';
}
};
// 哈希表直接储存bool类型,更加精简
class Solution2 {
public:
char firstUniqChar(string s) {
unordered_map<char,bool> dic;
for(int i=0;i<s.size();i++){
dic[s[i]] = dic.find(s[i])==dic.end();
}
for(char c:s){
if(dic[c]) return c;
}
return ' ';
}
};
int main(){
Solution sol;
string s = "1252144";
char res = sol.firstUniqChar(s);
return 0;
} | 19.918367 | 50 | 0.496926 | [
"vector"
] |
95afa61eea653e92c81bb33ec5a8bb6849795474 | 7,101 | cc | C++ | utst/utst-CommandLineTestDriver.cc | cornell-brg/mcppbs | 8fc21758e9d7b995474069622ff36fd16c3e7f63 | [
"BSD-3-Clause"
] | 4 | 2019-04-10T09:06:03.000Z | 2021-09-29T11:33:16.000Z | utst/utst-CommandLineTestDriver.cc | cornell-brg/mcppbs | 8fc21758e9d7b995474069622ff36fd16c3e7f63 | [
"BSD-3-Clause"
] | null | null | null | utst/utst-CommandLineTestDriver.cc | cornell-brg/mcppbs | 8fc21758e9d7b995474069622ff36fd16c3e7f63 | [
"BSD-3-Clause"
] | 5 | 2016-10-23T18:23:34.000Z | 2021-09-27T02:13:27.000Z | //========================================================================
// utst-CommandLineTestDriver.cc
//========================================================================
#include "utst-CommandLineTestDriver.h"
#include "utst-TestSuite.h"
#include "utst-TestLog.h"
#include <iostream>
#include <string>
#include <cstdlib>
namespace {
//----------------------------------------------------------------------
// SelectedTests
//----------------------------------------------------------------------
struct SelectedTests {
SelectedTests( const utst::TestSuite* suite_ptr )
{
m_suite_ptr = suite_ptr;
m_entire_suite_en = false;
}
const utst::TestSuite* m_suite_ptr;
std::vector<std::string> m_test_names;
bool m_entire_suite_en;
};
//----------------------------------------------------------------------
// Display usage and exit
//----------------------------------------------------------------------
void display_usage_and_exit( const std::string& name )
{
std::cout <<
"\n Usage: " << name << " [options] [suite ...] [case ...]\n"
"\n"
" --log-level <level> : Set level of detail for output\n"
" --list-tests : List all test suites and cases\n"
" --help : Output this message\n"
"\n"
" This program runs unit tests for " << name << ". Use the\n"
" --list-tests flag to see a list of all the possible test suites and\n"
" test cases. A user can select which tests to run by simply listing\n"
" the names of the desired test suites and test cases on the command\n"
" line. The default is to run all tests suites.\n"
"\n"
" Possible log levels are listed below:\n"
" minimal : Output failing checks only\n"
" moderate : Output failing checks and other log output\n"
" verbose : Output passing/failing checks and other log output\n"
"\n";
exit(1);
}
}
namespace utst {
//----------------------------------------------------------------------
// Constructors/Destructors
//----------------------------------------------------------------------
CommandLineTestDriver::CommandLineTestDriver()
{ }
CommandLineTestDriver::~CommandLineTestDriver()
{ }
//----------------------------------------------------------------------
// Adding test suites
//----------------------------------------------------------------------
void CommandLineTestDriver::add_suite( TestSuite* test_suite_ptr )
{
m_suites.push_back( test_suite_ptr );
}
//----------------------------------------------------------------------
// Running test cases
//----------------------------------------------------------------------
void CommandLineTestDriver::run( int argc, char* argv[] ) const
{
using namespace std;
// Get and display unit test name from the name of executable
string exe_name(argv[0]);
string::size_type start_pos = exe_name.rfind('/');
string::size_type end_pos = exe_name.rfind("-utst");
string base_name = exe_name.substr( start_pos+1, string::npos );
string utst_name = exe_name.substr( start_pos+1, end_pos-start_pos-1 );
// Initialize data structure to track which tests are selected
bool any_selections = false;
vector<SelectedTests> selected_tests;
for ( int i = 0; i < static_cast<int>(m_suites.size()); i++ )
selected_tests.push_back( SelectedTests(m_suites.at(i)) );
// Parse command line arguments
for ( int arg_idx = 1; arg_idx < argc; arg_idx++ ) {
string arg_str = string(argv[arg_idx]);
// --log-level
if ( (arg_str == "--log-level") && (arg_idx+1 < argc) ) {
string log_level_str = argv[++arg_idx];
if ( log_level_str == "minimal" )
TestLog::instance().set_log_level( TestLog::LogLevel::minimal );
else if ( log_level_str == "moderate" ) {
TestLog::instance().set_log_level( TestLog::LogLevel::moderate );
}
else if ( log_level_str == "verbose" ) {
TestLog::instance().set_log_level( TestLog::LogLevel::verbose );
}
else {
std::cerr << "\n Command Line Error: Unrecognized log level \""
<< log_level_str << "\"" << endl;
display_usage_and_exit(base_name);
}
}
// List tests option
else if ( arg_str == "--list-tests" ) {
for ( int i = 0; i < static_cast<int>(m_suites.size()); i++ ) {
vector<string> test_names = m_suites.at(i)->get_test_names();
if ( !test_names.empty() ) {
cout << "\n Test suite : "
<< m_suites.at(i)->get_name() << endl;
int test_names_sz = static_cast<int>(test_names.size());
for ( int j = 0; j < test_names_sz; j++ ) {
cout << " + Test case : " << test_names.at(j) << endl;
}
}
}
cout << "\n";
return;
}
// Help option
else if ( arg_str == "--help")
display_usage_and_exit(base_name);
// Test suite or test case
else {
// Although this is not a very efficient way to do this search,
// the number of test suites will probably be very small.
any_selections = true;
bool found = false;
vector<SelectedTests>::iterator itr = selected_tests.begin();
while ( !found && (itr != selected_tests.end()) ) {
if ( itr->m_suite_ptr->get_name() == arg_str ) {
itr->m_entire_suite_en = true;
found = true;
}
else if ( itr->m_suite_ptr->has_test( arg_str ) ) {
itr->m_test_names.push_back( arg_str );
found = true;
}
itr++;
}
// Display an error if the given command line argument is
// neither a test suite name nor a test case name.
if ( !found ) {
std::cerr << "\n Command Line Error: \"" << arg_str << "\" "
<< "is not a test suite or test case" << endl;
display_usage_and_exit(base_name);
}
}
}
// Output a header specifying what unit tests we are running
cout << "\n Unit Tests : " << utst_name << endl;
// If no tests were selected then run all tests in all suites
if ( !any_selections ) {
for ( int i = 0; i < static_cast<int>(m_suites.size()); i++ )
m_suites.at(i)->run_all();
}
// Otherwise just run the selected tests
else {
int selected_tests_sz = static_cast<int>(selected_tests.size());
for ( int i = 0; i < selected_tests_sz; i++ ) {
const TestSuite* suite_ptr = selected_tests.at(i).m_suite_ptr;
if ( selected_tests.at(i).m_entire_suite_en )
suite_ptr->run_all();
else
suite_ptr->run_tests( selected_tests.at(i).m_test_names );
}
}
// Final blank line
TestLog::LogLevelEnum log_level
= TestLog::instance().get_log_level();
if ( log_level == TestLog::LogLevel::minimal )
cout << endl;
}
}
| 31.420354 | 76 | 0.509787 | [
"vector"
] |
95b228f46bf0d0a06714f12efdf3f9ef8037972e | 4,849 | cpp | C++ | src/framework/db/db.cpp | ashwin-nat/HTTP-file-sharing | decd37db40b72ce6cac441039826e089ea432c5b | [
"MIT"
] | null | null | null | src/framework/db/db.cpp | ashwin-nat/HTTP-file-sharing | decd37db40b72ce6cac441039826e089ea432c5b | [
"MIT"
] | null | null | null | src/framework/db/db.cpp | ashwin-nat/HTTP-file-sharing | decd37db40b72ce6cac441039826e089ea432c5b | [
"MIT"
] | null | null | null | #include "db.hpp"
#include <mutex>
#include <stdexcept>
#include <sstream>
#ifdef SINGLETON_DB_OBJECT
#include <mutex>
#endif
/******************************************************************************/
#ifdef SINGLETON_DB_OBJECT
static std::mutex _db_mutex;
#endif
/******************************************************************************/
/* Public functions */
/**
* @brief Construct a new db handle object, open the db in the given
* path
*
* @param filename - string containing the file name
*/
db_handle :: db_handle (const std::string &filename)
{
#ifdef SINGLETON_DB_OBJECT
_db_mutex.lock();
#endif
int rc = sqlite3_open (filename.c_str(), &m_hdl);
//check open status
if (SQLITE_OK != rc) {
#ifdef SINGLETON_DB_OBJECT
_db_mutex.unlock();
#endif
const std::string errmsg = sqlite3_errmsg(m_hdl);
//raise exception here
throw std::invalid_argument(errmsg);
}
m_stmt = nullptr;
m_is_open = true;
m_ongoing_transaction = false;
}
/**
* @brief Destroy the iotcDB object, cleanup if required
*
*/
db_handle :: ~db_handle (void)
{
cleanup();
}
/**
* @brief Get the errmsg string
* @return std::string - string containing the error message
*/
std::string
db_handle :: get_errmsg (void)
{
return sqlite3_errmsg(m_hdl);
}
/**
* @brief - Prepares the sqlite3_stmt with the given statement
*
* @param str - string containing the statement that can be bound to
* @return int - sqlite3 return code
*/
int
db_handle :: prepare_stmt (
const std::string &str)
{
if(m_stmt) {
sqlite3_finalize (m_stmt);
m_stmt = nullptr;
}
return sqlite3_prepare_v2 (m_hdl, str.c_str(), -1, &m_stmt, NULL);
}
/**
* @brief - Bind the given int to the specified ? in the query
* @param offset- the nth question mark in the query (starting from 1)
* @param val - the value to be bound
* @return int - sqlite3 return code
*/
int
db_handle :: bind_int (
int offset,
int val)
{
return sqlite3_bind_int (m_stmt, offset, val);
}
/**
* @brief - Bind the given string to the specified ? in the
* query
* @param offset- the nth question mark in the query (starting from 1)
* @param str - the value to be bound
* @return int - sqlite3 return code
*/
int
db_handle :: bind_string (
int offset,
const std::string &str)
{
return sqlite3_bind_text (m_stmt, offset, str.c_str(), -1,
SQLITE_TRANSIENT);
}
/**
* @brief - Step through the given statement (get results)
*
* @return int - sqlite3 return code
*/
int
db_handle :: step (void)
{
return sqlite3_step (m_stmt);
}
/**
* @brief - Get the int value at the specified column of the result
* @param col - column number (starting at 0)
* @return int - value
*/
int
db_handle :: get_int (
int col)
{
return sqlite3_column_int (m_stmt, col);
}
/**
* @brief - Get the string value at the specified column of the result
* @param col - column number (starting at 0)
* @param result
* @return int
*/
int db_handle :: get_str (int col, std::string &result)
{
auto ret = sqlite3_column_text (m_stmt, col);
if (ret) {
std::stringstream ss;
ss << ret;
result = ss.str();
return result.length();
}
return 0;
}
/**
* @brief - Begins an sqlite transaction (for multiple inserts)
* @return int - sqlite3 return code
*/
int
db_handle :: start_transaction (void)
{
m_ongoing_transaction = true;
return sqlite3_exec(m_hdl, "BEGIN", nullptr, nullptr, nullptr);
}
/**
* @brief - Ends an sqlite transaction (for multiple requests)
* @return int - sqlite3 return code
*/
int
db_handle :: end_transaction (void)
{
m_ongoing_transaction = false;
return sqlite3_exec(m_hdl, "COMMIT", nullptr, nullptr, nullptr);
}
/**
* @brief - Executes the given string query
* @param query - the string containing the query
* @return int - sqlite3 return code
*/
int
db_handle :: exec_query (
const std::string &query)
{
return sqlite3_exec (m_hdl, query.c_str(), nullptr, nullptr, nullptr);
}
/**
* @brief - Reset a prepared statement
* @return int - sqlite3 return code
*/
int
db_handle :: reset_stmt (void)
{
return sqlite3_reset (m_stmt);
}
/******************************************************************************/
/* Private functions */
/**
* @brief - Performs cleanup, frees resources, closes handles
*
*/
void
db_handle :: cleanup (void)
{
if (m_is_open) {
if (m_ongoing_transaction) {
end_transaction();
}
if (m_stmt) {
sqlite3_finalize (m_stmt);
}
sqlite3_close (m_hdl);
#ifdef SINGLETON_DB_OBJECT
_db_mutex.unlock();
#endif
m_is_open = false;
}
} | 22.872642 | 80 | 0.60363 | [
"object"
] |
95b23372968bce052bce7a7c000b20a42371932a | 3,439 | cpp | C++ | src/core/debug.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | src/core/debug.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | src/core/debug.cpp | chokomancarr/chokoengine2 | 2825f2b95d24689f4731b096c8be39cc9a0f759a | [
"Apache-2.0"
] | null | null | null | #include "chokoengine.hpp"
#ifdef PLATFORM_WIN
#include <DbgHelp.h>
#else
#include <execinfo.h>
#include <cxxabi.h>
#endif
#include <thread>
CE_BEGIN_NAMESPACE
namespace {
uint _stacktrace(uint count, void** frames) {
return
#ifdef PLATFORM_WIN
CaptureStackBackTrace(0, count, frames, NULL);
#else
backtrace(frames, count);
#endif
}
#ifdef PLATFORM_WIN
HANDLE winHandle;
#endif
bool _initstacktrace() {
#ifdef PLATFORM_WIN
winHandle = GetCurrentProcess();
return SymInitialize(winHandle, NULL, true);
#endif
}
std::vector<std::string> _dumpstacktrace() {
void* frames[20];
uint count = _stacktrace(20, frames);
auto names = std::vector<std::string>(count);
#ifdef PLATFORM_WIN
auto handle = GetCurrentProcess();
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
PSYMBOL_INFO sym = (PSYMBOL_INFO)buffer;
sym->SizeOfStruct = sizeof(SYMBOL_INFO);
sym->MaxNameLen = MAX_SYM_NAME;
DWORD64 off = 0;
for (uint a = 0; a < count; a++) {
DWORD64 frame = (DWORD64)frames[a];
std::stringstream stream;
stream << std::hex << frame;
if (SymFromAddr(handle, frame, &off, sym)) {
names[a] = std::string((char*)sym->Name)
+ " (0x" + stream.str() + ")";
}
else {
names[a] = "0x" + stream.str() + " (no pdb loaded)";
}
}
#endif
return names;
}
void DumpStackTrace() {
std::cerr << "-------- dumping stack trace --------" << std::endl;
if (!_initstacktrace()) {
std::cerr << "cannot load symbols!" << std::endl;
//return;
}
const auto str = _dumpstacktrace();
for (auto& s : str) {
std::cerr << s << std::endl;
}
}
}
std::ofstream Debug::logStream;
bool Debug::Init() {
return true;
}
void Debug::Message(const std::string& caller, const std::string& msg, TerminalColor col) {
std::stringstream ss;
ss << std::this_thread::get_id();
std::cout << "[i t=" + std::to_string(Time::actualMillis()) + " thread=" + ss.str() + "] " + IO::ColorOutput(caller + ": " + msg, col) + "\n";
std::flush(std::cout);
}
void Debug::Warning(const std::string& caller, const std::string& msg) {
std::stringstream ss;
ss << std::this_thread::get_id();
std::cout << IO::ColorOutput("[w t=" + std::to_string(Time::actualMillis()) + " thread=" + ss.str() + "] ", TerminalColor::Yellow) + caller + ": " + msg + "\n";
std::flush(std::cout);
}
void Debug::Error(const std::string& caller, const std::string& msg) {
std::stringstream ss;
ss << std::this_thread::get_id();
std::cerr << IO::ColorOutput("[e t=" + std::to_string(Time::actualMillis()) + " thread=" + ss.str() + + "] ", TerminalColor::Red) + caller + ": " + msg + "\n";
std::flush(std::cout);
#ifdef PLATFORM_WIN
DumpStackTrace();
#endif
}
std::vector<uintptr_t> Debug::StackTrace(uint count) {
std::vector<uintptr_t> result(count, 0);
#ifdef PLATFORM_WIN
CaptureStackBackTrace(0, count, (void**)result.data(), NULL);
#else
backtrace((void**)result.data(), count);
#endif
return result;
}
uint Debug::StackTrace(uint count, uintptr_t* result) {
#ifdef PLATFORM_WIN
return CaptureStackBackTrace(0, count, (void**)result, NULL);
#else
return backtrace((void**)result, count);
#endif
}
std::string Debug::DemangleSymbol(const char* c) {
#ifdef PLATFORM_WIN
return std::string(c);
#else
int st = 0;
auto dc = abi::__cxa_demangle(c, 0, 0, &st);
if (!st) {
std::string res(dc);
free(dc);
return res;
}
else {
return std::string(c);
}
#endif
}
CE_END_NAMESPACE
| 24.741007 | 161 | 0.647863 | [
"vector"
] |
95b7792d37d55772393c190a6e4a62bd8e3bc50d | 21,133 | cpp | C++ | src/CrFileVerInfo.cpp | Vertigo093i/Far-CrFileVerInfo2 | 1167e9ece47df9719033a3e127a5f9318b5417b7 | [
"BSD-3-Clause"
] | 1 | 2016-03-31T19:11:57.000Z | 2016-03-31T19:11:57.000Z | src/CrFileVerInfo.cpp | Vertigo093i/Far-CrFileVerInfo2 | 1167e9ece47df9719033a3e127a5f9318b5417b7 | [
"BSD-3-Clause"
] | null | null | null | src/CrFileVerInfo.cpp | Vertigo093i/Far-CrFileVerInfo2 | 1167e9ece47df9719033a3e127a5f9318b5417b7 | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
*
* Creware File Version Info v1.3 plugin for FAR Manager 1.70+
*
* Copyright (c) 2005 Creware (http://www.creware.com, support@creware.com)
* Copyright (c) 2006 Alexander Ogorodnikov (anodyne@mail.ru)
* Copyright (c) 2010 Andrew Nefedkin (andrew.nefedkin@gmail.com)
*
* Displays file version information stored in the VERSIONINFO resource
*
******************************************************************************/
#define WIN32_LEAN_AND_MEAN
#include <plugin.hpp>
#if FARMANAGERVERSION_MAJOR >= 3
#include "guid.h"
#include "version.h"
#endif
#define PLUGIN_TITLE TEXT("Version Info")
#ifndef EXP_NAME
#if FARMANAGERVERSION_MAJOR >= 3
#define EXP_NAME(p) p##W
#elif FARMANAGERVERSION_MAJOR == 2
#define EXP_NAME(p) _export p##W
#else
#define EXP_NAME(p) _export p
#endif
#endif
PluginStartupInfo Info;
FarStandardFunctions FSF;
typedef struct TAG_DIALOG
{
TCHAR *Title;
int nLines;
TCHAR **Lines;
} DIALOG, *PDIALOG;
PDIALOG DialogCreate(const TCHAR* Title)
{
PDIALOG pDlg = (PDIALOG) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DIALOG) + (lstrlen(Title) + 1) * sizeof(TCHAR));
pDlg->Title = (TCHAR *) (pDlg + sizeof(DIALOG));
lstrcpy(pDlg->Title, Title);
return pDlg;
}
BOOL DialogAddLine(PDIALOG pDlg, TCHAR* psz)
{
HANDLE hHeap = GetProcessHeap();
void* p;
if (pDlg->nLines)
{
p = HeapReAlloc(hHeap, HEAP_ZERO_MEMORY, pDlg->Lines, (pDlg->nLines + 1) * sizeof(TCHAR *));
}
else
{
p = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR *));
}
if (p == NULL) return FALSE;
pDlg->Lines = (TCHAR **) p;
pDlg->Lines[pDlg->nLines] = (TCHAR*) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, (lstrlen(psz) + 1) * sizeof(TCHAR));
lstrcpy(pDlg->Lines[pDlg->nLines], psz);
pDlg->nLines++;
return TRUE;
}
TCHAR* DialogAddLinePlaceholder(PDIALOG pDlg, SIZE_T nChars)
{
HANDLE hHeap = GetProcessHeap();
void* p;
if (pDlg->nLines)
{
p = HeapReAlloc(hHeap, HEAP_ZERO_MEMORY, pDlg->Lines, (pDlg->nLines + 1) * sizeof(TCHAR *));
}
else
{
p = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR *));
}
if (p == NULL) return NULL;
pDlg->Lines = (TCHAR **) p;
pDlg->Lines[pDlg->nLines] = (TCHAR *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, nChars * sizeof(TCHAR));
return pDlg->Lines[pDlg->nLines++];
}
intptr_t DialogShow(PDIALOG pDlg)
{
if ( pDlg->nLines == 0 ) return -1;
TCHAR **Msg = (TCHAR **) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (pDlg->nLines + 2) * sizeof(TCHAR *));
int ndx = 0;
if (Msg == NULL) return -2;
Msg[ndx++] = pDlg->Title;
for ( int i = 0; i < pDlg->nLines; i++ )
{
Msg[ndx++] = pDlg->Lines[i];
}
Msg[ndx++] = TEXT("\x01");
#if FARMANAGERVERSION_MAJOR >= 3
return Info.Message(&PLUGIN_GUID, NULL, FMSG_LEFTALIGN | FMSG_MB_OK, NULL, Msg, ndx, 0);
#else
return Info.Message(Info.ModuleNumber, FMSG_LEFTALIGN | FMSG_MB_OK, NULL, Msg, ndx, 0);
#endif
}
void DialogFree(PDIALOG pDlg)
{
HANDLE hHeap = GetProcessHeap();
for ( int i = 0; i < pDlg->nLines; i++ )
{
HeapFree(hHeap, 0, pDlg->Lines[i]);
}
if (pDlg->Lines) HeapFree(hHeap, 0, pDlg->Lines);
HeapFree(hHeap, 0, pDlg);
}
void MsgBox(const TCHAR* pszMsg, const TCHAR* pszTitle, BOOL bError = FALSE)
{
const TCHAR *Msg[] = {
pszTitle,
pszMsg,
TEXT("\x01")
};
#if FARMANAGERVERSION_MAJOR >= 3
Info.Message(&PLUGIN_GUID, nullptr, (bError ? FMSG_WARNING : 0) | FMSG_LEFTALIGN | FMSG_MB_OK, NULL, Msg, ARRAYSIZE(Msg), 0);
#else
Info.Message(Info.ModuleNumber, (bError ? FMSG_WARNING : 0) | FMSG_LEFTALIGN | FMSG_MB_OK, NULL, Msg, ARRAYSIZE(Msg), 0);
#endif
}
int GetLanguageName(LCID Locale, LPTSTR lpLCData, int cchData)
{
static TCHAR pszLangIndependent[] = TEXT("language independent");
if(Locale == 0)
{
if(cchData != 0) lstrcpy(lpLCData, pszLangIndependent);
return sizeof(pszLangIndependent);
}
return GetLocaleInfo(Locale, LOCALE_SLANGUAGE, lpLCData, cchData);
}
void ProcessFile(const TCHAR *szFilePath, const TCHAR *szFileName)
{
LPVOID pData = NULL;
DWORD dwHandle = 0;
DWORD dwLength = GetFileVersionInfoSize(szFilePath, &dwHandle);
static PDIALOG pDlg = NULL;
if (dwLength)
{
pDlg = DialogCreate(szFileName);
HANDLE hHeap = GetProcessHeap();
if ( (pData = HeapAlloc(hHeap, HEAP_ZERO_MEMORY, dwLength)) != NULL )
{
VS_FIXEDFILEINFO* pFFI = NULL;
UINT siz = 0;
/*BOOL bResult =*/ GetFileVersionInfo(szFilePath, dwHandle, dwLength, pData);
if (VerQueryValue(pData, TEXT("\\"), (LPVOID*)&pFFI, &siz))
{
TCHAR sz[128];
DWORD dwFlags;
TCHAR *pszString;
FSF.snprintf(sz, 128, TEXT("File version %d.%d.%d.%d"),
HIWORD(pFFI->dwFileVersionMS),
LOWORD(pFFI->dwFileVersionMS),
HIWORD(pFFI->dwFileVersionLS),
LOWORD(pFFI->dwFileVersionLS) );
DialogAddLine(pDlg, sz);
FSF.snprintf(sz, 128, TEXT("Product version %d.%d.%d.%d"),
HIWORD(pFFI->dwProductVersionMS),
LOWORD(pFFI->dwProductVersionMS),
HIWORD(pFFI->dwProductVersionLS),
LOWORD(pFFI->dwProductVersionLS) );
DialogAddLine(pDlg, sz);
switch(pFFI->dwFileType)
{
case VFT_APP: pszString = TEXT("application"); break;
case VFT_DLL: pszString = TEXT("dynamic-link library"); break;
case VFT_DRV: pszString = TEXT("device driver"); break;
case VFT_FONT: pszString = TEXT("font"); break;
case VFT_VXD: pszString = TEXT("virtual device"); break;
case VFT_STATIC_LIB: pszString = TEXT("static-link library"); break;
default: pszString = TEXT("unknown");
}
FSF.snprintf(sz, 128, TEXT("File type %s"), pszString);
DialogAddLine(pDlg, sz);
if (pFFI->dwFileType == VFT_DRV)
{
switch(pFFI->dwFileSubtype)
{
case VFT2_DRV_PRINTER: pszString = TEXT("printer driver");
case VFT2_DRV_KEYBOARD: pszString = TEXT("keyboard driver");
case VFT2_DRV_LANGUAGE: pszString = TEXT("language driver");
case VFT2_DRV_DISPLAY: pszString = TEXT("display driver");
case VFT2_DRV_MOUSE: pszString = TEXT("mouse driver");
case VFT2_DRV_NETWORK: pszString = TEXT("network driver");
case VFT2_DRV_SYSTEM: pszString = TEXT("system driver");
case VFT2_DRV_INSTALLABLE: pszString = TEXT("installable driver");
case VFT2_DRV_SOUND: pszString = TEXT("sound driver");
case VFT2_DRV_COMM: pszString = TEXT("communications driver");
case VFT2_DRV_INPUTMETHOD: pszString = TEXT("input method editor");
case VFT2_DRV_VERSIONED_PRINTER: pszString = TEXT("versioned printer driver");
default: pszString = TEXT("unknown");
}
FSF.snprintf(sz, 128, TEXT("File subtype %s"), pszString);
DialogAddLine(pDlg, sz);
}
else if (pFFI->dwFileType == VFT_FONT)
{
switch(pFFI->dwFileSubtype)
{
case VFT2_FONT_RASTER: pszString = TEXT("raster font");
case VFT2_FONT_VECTOR: pszString = TEXT("vector font");
case VFT2_FONT_TRUETYPE: pszString = TEXT("TrueType font");
default: pszString = TEXT("unknown");
}
FSF.snprintf(sz, 128, TEXT("File subtype %s"), pszString);
DialogAddLine(pDlg, sz);
}
else if (pFFI->dwFileType == VFT_VXD)
{
FSF.snprintf(sz, 128, TEXT("Device ID 0x%04X"), pFFI->dwFileSubtype);
DialogAddLine(pDlg, sz);
}
dwFlags = pFFI->dwFileFlags & pFFI->dwFileFlagsMask;
if (dwFlags != 0)
{
lstrcpy(sz, TEXT("File flags "));
if (dwFlags & VS_FF_DEBUG) lstrcat(sz, TEXT(" DEBUG"));
if (dwFlags & VS_FF_INFOINFERRED) lstrcat(sz, TEXT(" INFOINFERRED"));
if (dwFlags & VS_FF_PATCHED) lstrcat(sz, TEXT(" PATCHED"));
if (dwFlags & VS_FF_PRERELEASE) lstrcat(sz, TEXT(" PRERELEASE"));
if (dwFlags & VS_FF_PRIVATEBUILD) lstrcat(sz, TEXT(" PRIVATEBUILD"));
if (dwFlags & VS_FF_SPECIALBUILD) lstrcat(sz, TEXT(" SPECIALBUILD"));
DialogAddLine(pDlg, sz);
}
switch(pFFI->dwFileOS)
{
case VOS_DOS: pszString = TEXT("MS-DOS"); break;
case VOS_OS216: pszString = TEXT("OS/2 (16 bit)"); break;
case VOS_OS232: pszString = TEXT("OS/2 (32 bit)"); break;
case VOS_NT:
case VOS_NT_WINDOWS32: pszString = TEXT("Windows NT/2000/XP/2003"); break;
case VOS_WINCE: pszString = TEXT("Windows CE"); break;
case VOS__WINDOWS16: pszString = TEXT("Windows (16 bit)"); break;
case VOS__PM16: pszString = TEXT("PM (16 bit)"); break;
case VOS__PM32: pszString = TEXT("PM (32 bit)"); break;
case VOS__WINDOWS32: pszString = TEXT("Windows (32 bit)"); break;
case VOS_DOS_WINDOWS16: pszString = TEXT("Windows (16 bit) with MS-DOS"); break;
case VOS_DOS_WINDOWS32: pszString = TEXT("Windows (32 bit) with MS-DOS"); break;
case VOS_OS216_PM16: pszString = TEXT("OS/2 with PM (16 bit)"); break;
case VOS_OS232_PM32: pszString = TEXT("OS/2 with PM (32 bit)"); break;
default: pszString = TEXT("unknown");
}
FSF.snprintf(sz, 128, TEXT("Operating system %s"), pszString);
DialogAddLine(pDlg, sz);
if (pFFI->dwFileDateLS | pFFI->dwFileDateMS)
{
FILETIME ft;
FILETIME ftLocal;
ft.dwHighDateTime = pFFI->dwFileDateMS;
ft.dwLowDateTime = pFFI->dwFileDateLS;
if (FileTimeToLocalFileTime(&ft, &ftLocal))
{
SYSTEMTIME stCreate;
FileTimeToSystemTime(&ftLocal, &stCreate);
FSF.snprintf(sz, 128, TEXT("File date %02d/%02d/%d %02d:%02d:%02d.%03d"),
stCreate.wDay, stCreate.wMonth, stCreate.wYear,
stCreate.wHour, stCreate.wMinute, stCreate.wSecond,
stCreate.wMilliseconds);
DialogAddLine(pDlg, sz);
}
else
{
DialogAddLine(pDlg, TEXT("File date invalid"));
}
}
// the pszStringName buffer must fit at least this string:
// \StringFileInfo\12345678\OriginalFilename + 22 chars just in case
TCHAR pszStringName[1 + 14 + 1 + 8 + 1 + 16 + 1 + 22];
lstrcpy(pszStringName, TEXT("\\StringFileInfo\\"));
BOOL bStringTableFound = FALSE;
// variable information block
struct LANGANDCODEPAGE {
WORD wLanguage;
WORD wCodePage;
} *pLangAndCodePage;
if(VerQueryValue(pData, TEXT("\\VarFileInfo\\Translation"), (LPVOID*) &pLangAndCodePage, &siz))
{
static const TCHAR *pszPrompt = TEXT("Language ");
int cchLang = 0, i, cLang = siz / sizeof(LANGANDCODEPAGE);
if ( cLang > 0 )
{
for ( i = 0; i < cLang; i++ )
cchLang += GetLanguageName(pLangAndCodePage[i].wLanguage, NULL, 0);
TCHAR *pszLang = DialogAddLinePlaceholder(pDlg, lstrlen(pszPrompt) + cchLang + cLang - 1);
TCHAR *pszDest = pszLang;
lstrcpy(pszDest, pszPrompt);
pszDest += lstrlen(pszPrompt);
for ( i = 0; i < cLang; i++ )
{
if ( i > 0 )
{
pszDest[-1] = TEXT(',');
pszDest = CharNext(pszDest);
*pszDest = TEXT(' ');
}
pszDest += GetLanguageName(pLangAndCodePage[i].wLanguage, pszDest, cchLang);
if ( !bStringTableFound )
{
FSF.snprintf(&pszStringName[16], 8, TEXT("%04x%04x"), pLangAndCodePage[i].wLanguage, pLangAndCodePage[i].wCodePage);
if ( VerQueryValue(pData, pszStringName, (LPVOID *) &pszString, &siz) )
{
bStringTableFound = TRUE;
}
}
}
#ifndef UNICODE
CharToOem(pszLang, pszLang);
#endif
}
else
{
lstrcpy(sz, pszPrompt);
lstrcat(sz, TEXT("unknown"));
DialogAddLine(pDlg, sz);
}
}
// string information block
static const struct KEYVALUEPAIR {
TCHAR *pszKey;
TCHAR *pszValue;
} KeyVal[] =
{
// .NET assembly version
TEXT("Assembly Version"), TEXT("Assembly version "),
TEXT("FileVersion"), TEXT("File version "),
TEXT("ProductVersion"), TEXT("Product version "),
TEXT("FileDescription"), TEXT("File description "),
TEXT("InternalName"), TEXT("Internal name "),
TEXT("OriginalFilename"), TEXT("Original filename "),
TEXT("PrivateBuild"), TEXT("Private build "),
TEXT("SpecialBuild"), TEXT("Special build "),
TEXT("ProductName"), TEXT("Product name "),
TEXT("CompanyName"), TEXT("Company name "),
// Found in some Adobe products (i.e. Flash Player installer)
TEXT("CompanyWebsite"), TEXT("Company website "),
TEXT("LegalCopyright"), TEXT("Legal copyright "),
TEXT("LegalTrademarks"), TEXT("Legal trademarks "),
TEXT("Comments"), TEXT("Comments "),
};
if ( !bStringTableFound )
{
// Try some common translations until first one is found
TCHAR pszLangCP[][9] =
{
TEXT("040904E4"), // English (US) and multilingual character set
TEXT("040904B0"), // English (US) and Unicode character set
TEXT("FFFFFFFF"), // system default language and current ANSI code page
TEXT("FFFF04B0"), // system default language and Unicode character set
TEXT("000004E4"), // no language and multilingual character set
TEXT("000004B0") // no language and Unicode character set
};
FSF.snprintf(pszLangCP[2], 8, TEXT("%04X%04X"), GetSystemDefaultLangID(), GetACP());
FSF.snprintf(pszLangCP[3], 8, TEXT("%04X04B0"), GetSystemDefaultLangID());
for ( int i = 0; i < ARRAYSIZE(pszLangCP); i++ )
{
lstrcpy(&pszStringName[16], pszLangCP[i]);
bStringTableFound = VerQueryValue(pData, pszStringName, (LPVOID*) &pszString, &siz);
if ( bStringTableFound )
break;
}
}
if ( bStringTableFound )
{
DialogAddLine(pDlg, TEXT("\x01"));
pszStringName[16 + 8] = TEXT('\\');
for ( int i = 0; i < ARRAYSIZE(KeyVal); i++ )
{
lstrcpy(&pszStringName[16 + 9], KeyVal[i].pszKey);
if ( VerQueryValue(pData, pszStringName, (LPVOID*) &pszString, &siz) )
{
#ifndef UNICODE
TCHAR *pszSrc = pszString;
while ( *pszSrc )
{
// '\xA9' - copyright, '\xAE' - registered trademark
if ( *pszSrc == TEXT('\xA9') || *pszSrc == TEXT('\xAE') )
siz += 2;
pszSrc = CharNext(pszSrc);
}
#endif
int cchValue = lstrlen(KeyVal[i].pszValue);
TCHAR* pszLine = DialogAddLinePlaceholder(pDlg, cchValue + siz);
TCHAR *pszDest = pszLine;
lstrcpy(pszDest, KeyVal[i].pszValue);
pszDest += cchValue;
#ifdef UNICODE
lstrcpy(pszDest, pszString);
#else
pszSrc = pszString;
while ( *pszSrc )
{
if ( *pszSrc == TEXT('\xA9') )
{
*pszDest = TEXT('(');
pszDest = CharNext(pszDest);
*pszDest = TEXT('C');
pszDest = CharNext(pszDest);
*pszDest = TEXT(')');
}
else if ( *pszSrc == TEXT('\xAE') )
{
*pszDest = TEXT('(');
pszDest = CharNext(pszDest);
*pszDest = TEXT('R');
pszDest = CharNext(pszDest);
*pszDest = TEXT(')');
}
else
{
*pszDest = *pszSrc;
}
pszSrc = CharNext(pszSrc);
pszDest = CharNext(pszDest);
}
#endif
#ifndef UNICODE
CharToOem(pszLine, pszLine);
#endif
}
}
}
DialogShow(pDlg);
}
HeapFree(hHeap, 0, pData);
}
DialogFree(pDlg);
}
else
{
MsgBox(TEXT("No version information available"), szFileName);
}
}
void ProcessPanelItem()
{
PanelInfo PInfo;
#if FARMANAGERVERSION_MAJOR >= 3
PInfo.StructSize = sizeof(PanelInfo);
Info.PanelControl(PANEL_ACTIVE, FCTL_GETPANELINFO, 0, &PInfo);
#elif FARMANAGERVERSION_MAJOR == 2
Info.Control(PANEL_ACTIVE, FCTL_GETPANELINFO, 0, (LONG_PTR) &PInfo);
#else
Info.Control(INVALID_HANDLE_VALUE, FCTL_GETPANELINFO, &PInfo);
#endif
if ( PInfo.PanelType != PTYPE_FILEPANEL )
{
MsgBox(TEXT("Only file panels are supported"), PLUGIN_TITLE, TRUE);
return;
}
if ( !PInfo.ItemsNumber || PInfo.CurrentItem < 0 )
{
return;
}
#if FARMANAGERVERSION_MAJOR >= 3
intptr_t nPDirSize = Info.PanelControl(PANEL_ACTIVE, FCTL_GETPANELDIRECTORY, 0, NULL);
#elif FARMANAGERVERSION_MAJOR == 2
int nPDirSize = Info.Control(PANEL_ACTIVE, FCTL_GETPANELDIR, 0, NULL);
#else
int nPDirSize = lstrlen(PInfo.CurDir);
#endif
if ( nPDirSize )
{
HANDLE hHeap = GetProcessHeap();
#if FARMANAGERVERSION_MAJOR >= 2
#if FARMANAGERVERSION_MAJOR >= 3
size_t nPPItemSize = Info.PanelControl(PANEL_ACTIVE, FCTL_GETCURRENTPANELITEM, 0, NULL);
#else
int nPPItemSize = Info.Control(PANEL_ACTIVE, FCTL_GETCURRENTPANELITEM, 0, NULL);
#endif
PluginPanelItem *PPItem = (PluginPanelItem *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, nPPItemSize);
#if FARMANAGERVERSION_MAJOR >= 3
FarGetPluginPanelItem gpi = { sizeof(FarGetPluginPanelItem), nPPItemSize, PPItem };
Info.PanelControl(PANEL_ACTIVE, FCTL_GETCURRENTPANELITEM, 0, &gpi);
if ( (PPItem->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY )
{
FarPanelDirectory *PDir = (FarPanelDirectory *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, nPDirSize);
PDir->StructSize = sizeof(FarPanelDirectory);
Info.PanelControl(PANEL_ACTIVE, FCTL_GETPANELDIRECTORY, (int) nPDirSize, PDir);
const TCHAR *pszFileName = PPItem->FileName;
TCHAR *pszFilePath = (TCHAR *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR) * (lstrlen(PDir->Name) + 1 + lstrlen(pszFileName) + 1));
lstrcpy(pszFilePath, PDir->Name);
HeapFree(hHeap, 0, PDir);
#else
Info.Control(PANEL_ACTIVE, FCTL_GETCURRENTPANELITEM, 0, (LONG_PTR) PPItem);
if ( (PPItem->FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY )
{
const TCHAR *pszFileName = PPItem->FindData.lpwszFileName;
TCHAR *pszFilePath = (TCHAR *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR) * (nPDirSize + 1 + lstrlen(pszFileName) + 1));
Info.Control(PANEL_ACTIVE, FCTL_GETPANELDIR, nPDirSize, (LONG_PTR) pszFilePath);
#endif // FARMANAGERVERSION_MAJOR >= 3
#else
TCHAR *pszCurDir = (TCHAR *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR) * nPDirSize + 1);
OemToChar(PInfo.CurDir, pszCurDir);
if ( (PInfo.PanelItems[PInfo.CurrentItem].FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY )
{
TCHAR *pszFileName = PInfo.PanelItems[PInfo.CurrentItem].FindData.cFileName;
TCHAR *pszFilePath = (TCHAR *) HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(TCHAR) * (nPDirSize + 1 + lstrlen(pszFileName) + 1));
lstrcpy(pszFilePath, pszCurDir);
#endif // FARMANAGERVERSION_MAJOR >= 2
if ( lstrlen(pszFilePath) > 0 )
{
FSF.AddEndSlash(pszFilePath);
}
lstrcat(pszFilePath, pszFileName);
ProcessFile(pszFilePath, pszFileName);
HeapFree(hHeap, 0, pszFilePath);
}
#if FARMANAGERVERSION_MAJOR >= 2
HeapFree(hHeap, 0, PPItem);
#else
HeapFree(hHeap, 0, pszCurDir);
#endif
}
}
void WINAPI EXP_NAME(SetStartupInfo)(const PluginStartupInfo *Info)
{
::Info = *Info;
::FSF = *Info->FSF;
::Info.FSF = &FSF;
}
#if FARMANAGERVERSION_MAJOR >= 3
void WINAPI GetGlobalInfoW(GlobalInfo *Info)
{
Info->StructSize = sizeof(GlobalInfo);
Info->MinFarVersion = MAKEFARVERSION(3, 0, 0, 2871, VS_RELEASE);
Info->Version = PLUGIN_VERSION;
Info->Guid = PLUGIN_GUID;
Info->Title = PLUGIN_TITLE;
Info->Description = PLUGIN_DESC;
Info->Author = PLUGIN_AUTHOR;
}
#elif FARMANAGERVERSION_MAJOR == 2
int WINAPI GetMinFarVersionW()
{
return MAKEFARVERSION(2, 0, 789); // 1145
}
#endif
void WINAPI EXP_NAME(GetPluginInfo)(PluginInfo *Info)
{
static TCHAR* PluginMenuStrings[1];
static TCHAR* CommandPrefix = TEXT("crver");
Info->StructSize = sizeof(PluginInfo);
//Info->Flags = PF_EDITOR;
PluginMenuStrings[0] = PLUGIN_TITLE;
#if FARMANAGERVERSION_MAJOR >= 3
Info->PluginMenu.Guids = &PLUGIN_MENU_GUID;
Info->PluginMenu.Strings = PluginMenuStrings;
Info->PluginMenu.Count = ARRAYSIZE(PluginMenuStrings);
#else
Info->PluginMenuStrings = PluginMenuStrings;
Info->PluginMenuStringsNumber = ARRAYSIZE(PluginMenuStrings);
#endif
Info->CommandPrefix = CommandPrefix;
}
#if FARMANAGERVERSION_MAJOR >= 3
HANDLE WINAPI OpenW(const OpenInfo *Info)
{
if ( Info->OpenFrom == OPEN_COMMANDLINE )
{
TCHAR *cmd = (TCHAR *) Info->Data;
#else
HANDLE WINAPI EXP_NAME(OpenPlugin)(int OpenFrom, INT_PTR Item)
{
if ( OpenFrom == OPEN_COMMANDLINE )
{
TCHAR *cmd = (TCHAR *) Item;
#endif
cmd = FSF.Trim(cmd);
if ( lstrlen(cmd) )
{
FSF.Unquote(cmd);
MsgBox(cmd, PLUGIN_TITLE);
}
else
{
ProcessPanelItem();
}
}
else
{
ProcessPanelItem();
}
#if FARMANAGERVERSION_MAJOR >= 3
return nullptr;
#else
return INVALID_HANDLE_VALUE;
#endif
}
#if defined(__GNUC__)
#ifdef __cplusplus
extern "C"{
#endif
BOOL WINAPI DllMainCRTStartup(HANDLE hDll, DWORD dwReason, LPVOID lpReserved);
#ifdef __cplusplus
};
#endif
BOOL WINAPI DllMainCRTStartup(HANDLE hDll, DWORD dwReason, LPVOID lpReserved)
{
(void) lpReserved;
(void) dwReason;
(void) hDll;
return TRUE;
}
#endif
| 28.713315 | 139 | 0.642644 | [
"vector"
] |
95b974cc088a18c1126cd3ea70ecfb1b0dbbaf78 | 5,028 | cpp | C++ | Solution/Quadtree_tester.cpp | Aniket71999/DropBombAlgo | 069f373aa22cb18254733d9bf858de603d78dd03 | [
"Apache-2.0"
] | null | null | null | Solution/Quadtree_tester.cpp | Aniket71999/DropBombAlgo | 069f373aa22cb18254733d9bf858de603d78dd03 | [
"Apache-2.0"
] | null | null | null | Solution/Quadtree_tester.cpp | Aniket71999/DropBombAlgo | 069f373aa22cb18254733d9bf858de603d78dd03 | [
"Apache-2.0"
] | null | null | null | #ifndef QUADTREE_TESTER_H
#define QUADTREE_TESTER_H
#ifndef nullptr
#define nullptr 0
#endif
#include "Exception.h"
#include "Tester.h"
#include "Quadtree.h"
#include "Quadtree_node.h"
#include "Quadtree_node_tester.h"
#include <iostream>
template <typename Type>
class Quadtree_tester:public Tester< Quadtree<Type> > {
using Tester< Quadtree<Type> >::object;
using Tester< Quadtree<Type> >::command;
public:
Quadtree_tester( Quadtree<Type> *obj = 0 ):Tester< Quadtree<Type> >( obj ) {
}
void process(); };
template <typename Type>
void Quadtree_tester<Type>::process() {
if ( command == "size" ) {
int expected_size;
std::cin >> expected_size;
int actual_size = object->size();
if ( actual_size == expected_size ) {
std::cout << "Okay" << std::endl;
} else {
std::cout << "Failure in size(): expecting the value '" << expected_size << "' but got '" << actual_size << "'" << std::endl;
}
} else if ( command == "empty" ) {
bool expected_empty;
std::cin >> expected_empty;
bool actual_empty = object->empty();
if ( actual_empty == expected_empty ) {
std::cout << "Okay" << std::endl;
} else {
std::cout << "Failure in empty(): expecting the value '" << expected_empty << "' but got '" << actual_empty << "'" << std::endl; } } else if ( command == "min_x" ) {
Type expected_min_x;
std::cin >> expected_min_x;
Type actual_min_x = object->min_x();
if ( actual_min_x == expected_min_x ) {
std::cout << "Okay" << std::endl; } else {
std::cout << "Failure in min_x(): expecting the value '" << expected_min_x << "' but got '" << actual_min_x << "'" << std::endl; }
} else if ( command == "min_y" ) { Type expected_min_y;
std::cin >> expected_min_y;
Type actual_min_y = object->min_y();
if ( actual_min_y == expected_min_y ) {
std::cout << "Okay" << std::endl; } else {
std::cout << "Failure in min_y(): expecting the value '" << expected_min_y << "' but got '" << actual_min_y << "'" << std::endl; }
} else if ( command == "max_x" ) { Type expected_max_x;
std::cin >> expected_max_x;
Type actual_max_x = object->max_x();
if ( actual_max_x == expected_max_x ) {
std::cout << "Okay" << std::endl;
} else {
std::cout << "Failure in max_x(): expecting the value '" << expected_max_x << "' but got '" << actual_max_x << "'" << std::endl;
}
} else if ( command == "max_y" ) {
Type expected_max_y;
std::cin >> expected_max_y;
Type actual_max_y = object->max_y();
if ( actual_max_y == expected_max_y ) {
std::cout << "Okay" << std::endl;
} else {
std::cout << "Failure in max_y(): expecting the value '" << expected_max_y << "' but got '" << actual_max_y << "'" << std::endl; }
} else if ( command == "sum_x" ) { Type expected_sum_x;
std::cin >> expected_sum_x;
Type actual_sum_x = object->sum_x();
if ( actual_sum_x == expected_sum_x ) {
std::cout << "Okay" << std::endl;
} else {
std::cout << "Failure in sum_x(): expecting the value '" << expected_sum_x << "' but got '" << actual_sum_x << "'" << std::endl;
}
} else if ( command == "sum_y" ) {
Type expected_sum_y;
std::cin >> expected_sum_y;
Type actual_sum_y = object->sum_y();
if ( actual_sum_y == expected_sum_y ) {
std::cout << "Okay" << std::endl;
} else {
std::cout << "Failure in sum_y(): expecting the value '" << expected_sum_y << "' but got '" << actual_sum_y << "'" << std::endl;
}
} else if ( command == "root" ) {
Quadtree_node<Type> *actual_root = object->root();
if ( actual_root == 0 ) {
std::cout << "Failure in root(): expecting a non-zero root pointer" << std::endl;
} else {
std::cout << "Okay" << std::endl;
Quadtree_node_tester<Type> tester( actual_root );
tester.run();
}
} else if ( command == "root0" ) {
if ( object->root() == 0 ) {
std::cout << "Okay" << std::endl;
} else {
std::cout << "Failure in root(): expecting a 0 root pointer" << std::endl;
}
} else if ( command == "member" ) {
Type element_x;
Type element_y;
bool membership;
std::cin >> element_x;
std::cin >> element_y;
std::cin >> membership;
if ( object->member( element_x, element_y ) == membership ) {
std::cout << "Okay" << std::endl;
} else {
if ( membership ) {
std::cout << "Failure in member(): expecting the value (" << element_x << "," << element_y << ") to be in the quadtree" << std::endl;
} else {
std::cout << "Failure in member(): not expecting the value (" << element_x << "," << element_y << ") to be in the quadtree" << std::endl;
}
}
} else if ( command == "insert" ) { Type x, y;
std::cin >> x;
std::cin >> y;
object->insert( x, y );
std::cout << "Okay" << std::endl;
} else if ( command == "clear" ) { object->clear();
std::cout << "Okay" << std::endl;
} else if ( command == "cout" ) {
std::cout << *object << std::endl;
} else {
std::cout << command << ": Command not found." << std::endl;
} }
#endif
| 38.976744 | 170 | 0.585322 | [
"object"
] |
95bcc4a0fee507c07d846a3967ed6b23039a91bb | 12,441 | cpp | C++ | utils/TestAnimation.cpp | nullpo24/ArOgre | f4c229663f5f3b2761191e20b78863a3efe1c071 | [
"MIT"
] | 3 | 2016-05-29T01:13:11.000Z | 2020-01-03T03:06:22.000Z | utils/TestAnimation.cpp | nullpo24/ArOgre | f4c229663f5f3b2761191e20b78863a3efe1c071 | [
"MIT"
] | null | null | null | utils/TestAnimation.cpp | nullpo24/ArOgre | f4c229663f5f3b2761191e20b78863a3efe1c071 | [
"MIT"
] | 4 | 2018-08-03T14:36:07.000Z | 2020-11-07T06:54:08.000Z | #include "PCH.h"
#include "TestAnimation.h"
//////////////////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
//////////////////////////////////////////////////////////////////////////////////////////////
TestAnimation::TestAnimation()
: mCrystal(0),
mNumModels(0),
mAnimChop(0)
{
}
//////////////////////////////////////////////////////////////////////////////////////////////
TestAnimation::~TestAnimation()
{
if(mCrystal) delete mCrystal;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// CREATE SCENE
//////////////////////////////////////////////////////////////////////////////////////////////
void TestAnimation::createScene()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////
// FRAME LISTENER
//////////////////////////////////////////////////////////////////////////////////////////////
void TestAnimation::createFrameListener()
{
ArBaseApplication::createFrameListener();
// Create main menu
if(!mShowWarning)
createMainMenu();
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool TestAnimation::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
bool ret=ArBaseApplication::frameRenderingQueued(evt);
bool detected;
Ogre::Vector3 newPos;
Ogre::Quaternion newQua;
if(mCrystal)
{
detected=mDetector->detectBoard(newPos, newQua);
mCrystal->update(detected, newPos, newQua);
mGround->update(mHideGround, newPos, newQua);
for(unsigned int i=0; i<mNumModels; i++)
{
// update sneaking animation based on speed
mAnimStates[i]->addTime(mAnimSpeeds[i] * evt.timeSinceLastFrame);
mModelNodes[i]->setVisible(detected);
if (mAnimStates[i]->getTimePosition() >= mAnimChop) // when it's time to loop...
{
/* We need reposition the scene node origin, since the animation includes translation.
Position is calculated from an offset to the end position, and rotation is calculated
from how much the animation turns the character. */
Ogre::Quaternion rot(Ogre::Degree(-60), Ogre::Vector3::UNIT_Y); // how much the animation turns the character
// find current end position and the offset
Ogre::Vector3 currEnd = mModelNodes[i]->getOrientation() * mSneakEndPos + mModelNodes[i]->getPosition();
Ogre::Vector3 offset = rot * mModelNodes[i]->getOrientation() * -mSneakStartPos;
mModelNodes[i]->setPosition(currEnd + offset);
mModelNodes[i]->rotate(rot);
mAnimStates[i]->setTimePosition(0); // reset animation time
}
}
}
return ret;
}
//////////////////////////////////////////////////////////////////////////////////////////////
// KEY LISTENER
//////////////////////////////////////////////////////////////////////////////////////////////
bool TestAnimation::keyPressed ( const OIS::KeyEvent& arg )
{
if(arg.key==OIS::KC_F1)
{
mTrayMgr->destroyAllWidgets();
createHideMenu();
}
return ArBaseApplication::keyPressed ( arg );
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool TestAnimation::keyReleased ( const OIS::KeyEvent& arg )
{
return ArBaseApplication::keyReleased ( arg );
}
//////////////////////////////////////////////////////////////////////////////////////////////
// MOUSE LISTENER
//////////////////////////////////////////////////////////////////////////////////////////////
bool TestAnimation::mouseMoved(const OIS::MouseEvent &arg)
{
return ArBaseApplication::mouseMoved(arg);
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool TestAnimation::mousePressed(const OIS::MouseEvent &arg,OIS::MouseButtonID id)
{
return ArBaseApplication::mousePressed(arg, id);
}
//////////////////////////////////////////////////////////////////////////////////////////////
bool TestAnimation::mouseReleased(const OIS::MouseEvent &arg,OIS::MouseButtonID id)
{
return ArBaseApplication::mouseReleased(arg, id);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// SDKTRAY LISTENER
//////////////////////////////////////////////////////////////////////////////////////////////
void TestAnimation::buttonHit ( OgreBites::Button* button )
{
if(button->getName()=="bttWarning")
{
mTrayMgr->destroyAllWidgets();
createMainMenu();
}
else if(button->getName()=="bttHide")
{
mTrayMgr->destroyAllWidgets();
}
else if(button->getName()=="bttExitModel")
{
mTrayMgr->destroyAllWidgets();
Ogre::Real markerSize=mDetector->getMarkerSize();
// models scene
mCrystal=new ArOgre::ArModel(mSceneMgr, "arCrystal", "arNodeCrystal", "mesh_crystal.mesh", -1, markerSize);
mCrystal->getEntity()->setCastShadows(true);
setupModels();
// particle effect
Ogre::ParticleSystem::setDefaultNonVisibleUpdateTimeout(5); // set nonvisible timeout
Ogre::ParticleSystem* ps;
Ogre::SceneNode* nodePS;
// create a blue nimbus around the crystal
ps = mSceneMgr->createParticleSystem("Nimbus", "Examples/BlueNimbus");
nodePS=mCrystal->getModelNode()->createChildSceneNode();
nodePS->attachObject(ps);
nodePS->scale(0.5f, 0.5f, 0.5f);
// create plane, diferent plane for diferent model
mPlane=new Ogre::Plane(Ogre::Vector3::UNIT_Y, 0);
Ogre::MeshManager::getSingleton().createPlane("groundPlane",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
(*mPlane), 1, 1, 20, 20, true, 1, 4, 2, Ogre::Vector3::UNIT_Z);
// create entity plane
mGround=new ArOgre::ArModel(mSceneMgr, "ground", "ground1", "groundPlane", -1, 0.05);
mGround->getModelNode()->scale(9,0,6.25f);
mGround->getModelNode()->translate(0,0.0005f,0);
mGround->getEntity()->setMaterialName("Examples/BumpyMetal");
// setup scene light
mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f));
mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_MODULATIVE);
mSceneMgr->setShadowColour(Ogre::ColourValue(0.75f, 0.75f, 0.75f));
mBackground->enableShadows(mCrystal->getMarkerNode());
// point light
Ogre::Light* pointLight = mSceneMgr->createLight("pointLight");
pointLight->setType(Ogre::Light::LT_POINT);
pointLight->setPosition(Ogre::Vector3(0.0f, 0.085f, 0.0f));
pointLight->setDiffuseColour(Ogre::ColourValue(0.3f, 0.3f, 0.9f));
Ogre::SceneNode *nodeLight=mCrystal->getModelNode()->createChildSceneNode();
nodeLight->attachObject(pointLight);
// menu hide
createHideMenu();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
void TestAnimation::sliderMoved ( OgreBites::Slider* slider )
{
if(slider->getName()=="mSliderM")
mNumModels=slider->getValue();
else
mAnimChop=slider->getValue();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void TestAnimation::checkBoxToggled ( OgreBites::CheckBox* box )
{
mHideGround=!box->isChecked();
}
//////////////////////////////////////////////////////////////////////////////////////////////
void TestAnimation::createMainMenu()
{
mTrayMgr->showCursor();
OgreBites::TextBox* tb=
mTrayMgr->createTextBox(OgreBites::TL_CENTER, "tb", "Test Animation", 320, 200);
tb->setText("TEST ANIMATION\n\n\n"
"_-> A demo of the skeletal animation feature, including spline animation.\n"
"_-> Press F1 to show or hide the option menu."
);
mSldModel=mTrayMgr->createLongSlider(OgreBites::TL_CENTER, "mSliderM", "Num Models", 150, 50, 1, 20, 20);
mSldChop=mTrayMgr->createLongSlider(OgreBites::TL_CENTER, "mSliderC", "Anim Chop ", 150, 50, 5, 10, 6);
mTrayMgr->createSeparator(OgreBites::TL_CENTER, "spt", 150);
mTrayMgr->createButton(OgreBites::TL_CENTER, "bttExitModel", "Accept", 150);
mSldModel->setValue(9);
mSldChop->setValue(8);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void TestAnimation::createHideMenu()
{
OgreBites::CheckBox* cbHide=
mTrayMgr->createCheckBox(OgreBites::TL_BOTTOMLEFT, "cbHide", "Hide ground", 150.0f);
cbHide->setChecked(!mGround->getEntity()->isVisible());
}
//////////////////////////////////////////////////////////////////////////////////////////////
// SCENE MODELS
//////////////////////////////////////////////////////////////////////////////////////////////
void TestAnimation::setupModels()
{
tweakSneakAnim();
Ogre::SceneNode* sn = NULL;
Ogre::Entity* ent = NULL;
Ogre::AnimationState* as = NULL;
for(unsigned int i=0; i<mNumModels; i++)
{
// create scene nodes for the models at regular angular intervals
sn = mCrystal->getModelNode()->createChildSceneNode();
sn->yaw(Ogre::Radian(Ogre::Math::TWO_PI * (float)i / (float)mNumModels));
sn->translate(0, 0, -10, Ogre::Node::TS_LOCAL);
mModelNodes.push_back(sn);
// create and attach a jaiqua entity
ent = mSceneMgr->createEntity("Jaiqua" + Ogre::StringConverter::toString(i + 1), "jaiqua.mesh");
sn->attachObject(ent);
ent->setCastShadows(true);
// enable the entity's sneaking animation at a random speed and loop it manually since translation is involved
as = ent->getAnimationState("Sneak");
as->setEnabled(true);
as->setLoop(false);
mAnimSpeeds.push_back(Ogre::Math::RangeRandom(0.5, 1.5));
mAnimStates.push_back(as);
}
// create name and value for skinning mode
Ogre::StringVector names;
names.push_back("Skinning");
Ogre::String value = "Software";
// change the value if hardware skinning is enabled
Ogre::Pass* pass = ent->getSubEntity(0)->getMaterial()->getBestTechnique()->getPass(0);
if (pass->hasVertexProgram() && pass->getVertexProgram()->isSkeletalAnimationIncluded()) value = "Hardware";
}
void TestAnimation::tweakSneakAnim()
{
// get the skeleton, animation, and the node track iterator
Ogre::SkeletonPtr skel = Ogre::SkeletonManager::getSingleton().load("jaiqua.skeleton",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
Ogre::Animation* anim = skel->getAnimation("Sneak");
Ogre::Animation::NodeTrackIterator tracks = anim->getNodeTrackIterator();
while (tracks.hasMoreElements()) // for every node track...
{
Ogre::NodeAnimationTrack* track = tracks.getNext();
// get the keyframe at the chopping point
Ogre::TransformKeyFrame oldKf(0, 0);
track->getInterpolatedKeyFrame(mAnimChop, &oldKf);
// drop all keyframes after the chopping point
while (track->getKeyFrame(track->getNumKeyFrames()-1)->getTime() >= mAnimChop - 0.3f)
track->removeKeyFrame(track->getNumKeyFrames()-1);
// create a new keyframe at chopping point, and get the first keyframe
Ogre::TransformKeyFrame* newKf = track->createNodeKeyFrame(mAnimChop);
Ogre::TransformKeyFrame* startKf = track->getNodeKeyFrame(0);
Ogre::Bone* bone = skel->getBone(track->getHandle());
if (bone->getName() == "Spineroot") // adjust spine root relative to new location
{
mSneakStartPos = startKf->getTranslate() + bone->getInitialPosition();
mSneakEndPos = oldKf.getTranslate() + bone->getInitialPosition();
mSneakStartPos.y = mSneakEndPos.y;
newKf->setTranslate(oldKf.getTranslate());
newKf->setRotation(oldKf.getRotation());
newKf->setScale(oldKf.getScale());
}
else // make all other bones loop back
{
newKf->setTranslate(startKf->getTranslate());
newKf->setRotation(startKf->getRotation());
newKf->setScale(startKf->getScale());
}
}
}
#ifdef __cplusplus
extern "C" {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
#else
int main(int argc, char *argv[])
#endif
{
// Create application object
TestAnimation app;
try
{
app.go();
}
catch( Ogre::Exception& e )
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occured: " <<
e.getFullDescription().c_str() << std::endl;
#endif
}
return 0;
}
#ifdef __cplusplus
}
#endif
| 34.084932 | 145 | 0.566594 | [
"mesh",
"object",
"model"
] |
95c791da3c78cc757d134a5af34722b90bfb8675 | 2,656 | cpp | C++ | DXMUI/Canvas/Elements/ImageElement.cpp | Ulvmane/DXMUI | 999d30c1d21777f382cbf37d7aa2c701d5951ac3 | [
"MIT"
] | null | null | null | DXMUI/Canvas/Elements/ImageElement.cpp | Ulvmane/DXMUI | 999d30c1d21777f382cbf37d7aa2c701d5951ac3 | [
"MIT"
] | null | null | null | DXMUI/Canvas/Elements/ImageElement.cpp | Ulvmane/DXMUI | 999d30c1d21777f382cbf37d7aa2c701d5951ac3 | [
"MIT"
] | null | null | null | #include "ImageElement.h"
#include "D3D11_Interface\DXMRenderer.h"
#include <DDSTextureLoader.h>
#include <WICTextureLoader.h>
#include "Utility\DXMUI_Util.h"
#include "D3D11_Interface\DXM_D3D11_Interface.h"
#include "Parser\Styles\DXUIStyle.h"
#include <assert.h>
DXMUI::ImageElement::ImageElement(const char* aPath)
{
myPath = aPath;
std::wstring wPath = std::wstring(myPath.begin(), myPath.end());
#undef _XM_NO_INTRINSICS_
HRESULT result = S_FALSE;
result = DirectX::CreateDDSTextureFromFile(DXM_D3D11_Interface::GetDevice(),wPath.c_str(),0, &myTexture);
if (FAILED(result))
{
result = DirectX::CreateWICTextureFromFile(DXM_D3D11_Interface::GetDevice(), wPath.c_str(), 0, &myTexture);
}
if (SUCCEEDED(result))
{
ID3D11Texture2D* pTextureInterface = 0;
ID3D11Resource* resource;
myTexture->GetResource(&resource);
resource->QueryInterface<ID3D11Texture2D>(&pTextureInterface);
D3D11_TEXTURE2D_DESC textureDesc;
pTextureInterface->GetDesc(&textureDesc);
auto clientRect = RECT();
GetClientRect(DXM_D3D11_Interface::GetHWND(), &clientRect);
auto scaleX = float{ textureDesc.Width / static_cast<float>(clientRect.right - clientRect.left)};
auto scaleY = float{ textureDesc.Height / static_cast<float>(clientRect.bottom - clientRect.top)};
myHeight = scaleY;
myWidth = scaleX;
mySurface.myElementBufferData.myColor = Color{ 1,1,1,1 };
mySurface.myElementBufferData.myPivot = Vector2{ 0.f,0.f };
mySurface.myElementBufferData.myPosition = Vector2{ 0.5f, 0.5f };
mySurface.myElementBufferData.mySize = Vector2{ scaleX,scaleY };
mySurface.myElementBufferData.myTextureRect = TextureRect{ 0,0,1,1 };
mySurface.myElementBufferData.myHasTexture = true;
mySurface.myTexture.myWriteToGPU = true;
mySurface.myTexture.myTexture = myTexture;
DXM_SafeRelease(&pTextureInterface);
DXM_SafeRelease(&resource);
}
}
DXMUI::ImageElement::~ImageElement()
{
DXM_SafeRelease(&myTexture);
}
void DXMUI::ImageElement::Render()
{
DXMRenderer::AddDrawSurface(mySurface);
}
void DXMUI::ImageElement::SetPosition(const float aX, const float aY)
{
mySurface.myElementBufferData.myPosition = Vector2{ aX, aY };
}
DXMUI::Vector2 DXMUI::ImageElement::GetPosition()
{
return mySurface.myElementBufferData.myPosition;
}
void DXMUI::ImageElement::SetStyle(const DXUIStyle& aStyle)
{
mySurface.myElementBufferData.myColor = aStyle.myColor;
mySurface.myElementBufferData.mySize.x *= aStyle.mySize.x;
mySurface.myElementBufferData.mySize.y *= aStyle.mySize.y;
myWidth *= aStyle.mySize.x;
myHeight *= aStyle.mySize.y;
myBorder = aStyle.myBorder;
myPadding = aStyle.myPadding;
myMargin = aStyle.myMargin;
}
| 28.869565 | 109 | 0.763931 | [
"render"
] |
95cefe445c9a08e6cfcb7bcd467c07aa871a2c20 | 14,070 | cpp | C++ | src/cpp/SPL/Core/ParallelRegionChecker.cpp | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 10 | 2021-02-19T20:19:24.000Z | 2021-09-16T05:11:50.000Z | src/cpp/SPL/Core/ParallelRegionChecker.cpp | xguerin/openstreams | 7000370b81a7f8778db283b2ba9f9ead984b7439 | [
"Apache-2.0"
] | 7 | 2021-02-20T01:17:12.000Z | 2021-06-08T14:56:34.000Z | src/cpp/SPL/Core/ParallelRegionChecker.cpp | IBMStreams/OSStreams | c6287bd9ec4323f567d2faf59125baba8604e1db | [
"Apache-2.0"
] | 4 | 2021-02-19T18:43:10.000Z | 2022-02-23T14:18:16.000Z | /*
* Copyright 2021 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <SPL/Core/ParallelRegionChecker.h> // Include this one first
#include <SPL/CodeGen/CompositeDefinition.h>
#include <SPL/CodeGen/CompositeOperatorInstance.h>
#include <SPL/CodeGen/OperatorIR.h>
#include <SPL/CodeGen/SPLAnnotation.h>
#include <SPL/Core/CompilerError.h>
#include <SPL/Core/ExportSpec.h>
#include <SPL/Core/ImportSpec.h>
#include <SPL/Core/OperatorGraph.h>
#include <SPL/Core/OperatorGraphNode.h>
#include <SPL/Core/OperatorModelImpl.h>
#include <SPL/Core/PathSearch.h>
#include <SPL/FrontEnd/FrontEndDriver.h>
#include <SPL/Utility/SysOut.h>
#include <deque>
#include <string>
#include <vector>
using namespace std;
using namespace std::tr1;
using namespace SPL;
using namespace SPL::Operator;
ParallelRegionChecker::ParallelRegionChecker()
: _path(PathSearch::instance())
{}
void ParallelRegionChecker::checkImportExportOperators(const OperatorGraph& graph)
{
// Walk all nodes in the graph looking for import/export specs and make sure none feed an operator that is in a parallel region
uint32_t numNodes = graph.numNodes();
for (uint32_t i = 0; i < numNodes; ++i) {
const OperatorGraphNode& node = graph.getNode(i);
const PrimitiveOperatorInstance* ir = node.getOperatorIR();
assert(NULL != ir);
uint32_t numInputPorts = node.getNumberOfInputs();
for (uint32_t j = 0; j < numInputPorts; ++j) {
if (node.isInputPortImported(j)) {
const vector<const ImportSpec*>& importSpecs = node.getImportSpecs(j);
for (vector<const ImportSpec*>::const_iterator it = importSpecs.begin();
it != importSpecs.end(); ++it) {
const ImportSpec& is = **it;
const PrimitiveOperatorInstance& importIR = is.getOperatorIR();
if (ir->isInParallelRegion()) {
if (importIR.isInParallelRegion()) {
if (importIR.isInParallelRegion()) {
const string& operRegionName = ir->parallelRegionName();
const string& importRegionName = importIR.parallelRegionName();
if (importRegionName != operRegionName) {
SysOut::errorln(SPL_CORE_IMPORT_EXPORT_CROSSES_PARALLEL_REGION,
ir->getLocation());
SysOut::detailsErrorln(SPL_CORE_IMPORT_DEFINITION,
importIR.getLocation());
}
}
} else {
SysOut::errorln(SPL_CORE_IMPORT_EXPORT_CROSSES_PARALLEL_REGION,
ir->getLocation());
SysOut::detailsErrorln(SPL_CORE_IMPORT_DEFINITION,
importIR.getLocation());
}
} else if (importIR.isInParallelRegion()) {
SysOut::errorln(SPL_CORE_IMPORT_EXPORT_CROSSES_PARALLEL_REGION,
ir->getLocation());
SysOut::detailsErrorln(SPL_CORE_IMPORT_DEFINITION, importIR.getLocation());
}
}
}
}
uint32_t numOutputPorts = node.getNumberOfOutputs();
for (uint32_t k = 0; k < numOutputPorts; ++k) {
if (node.isOutputPortExported(k)) {
const vector<const ExportSpec*>& exportSpecs = node.getExportSpecs(k);
for (vector<const ExportSpec*>::const_iterator it = exportSpecs.begin();
it != exportSpecs.end(); ++it) {
const ExportSpec& es = **it;
const PrimitiveOperatorInstance& exportIR = es.getOperatorIR();
if (ir->isInParallelRegion()) {
if (exportIR.isInParallelRegion()) {
const string& operRegionName = ir->parallelRegionName();
const string& exportRegionName = exportIR.parallelRegionName();
if (exportRegionName != operRegionName) {
SysOut::errorln(SPL_CORE_IMPORT_EXPORT_CROSSES_PARALLEL_REGION,
ir->getLocation());
SysOut::detailsErrorln(SPL_CORE_EXPORT_DEFINITION,
exportIR.getLocation());
}
} else {
SysOut::errorln(SPL_CORE_IMPORT_EXPORT_CROSSES_PARALLEL_REGION,
ir->getLocation());
SysOut::detailsErrorln(SPL_CORE_EXPORT_DEFINITION,
exportIR.getLocation());
}
} else if (exportIR.isInParallelRegion()) {
SysOut::errorln(SPL_CORE_IMPORT_EXPORT_CROSSES_PARALLEL_REGION,
ir->getLocation());
SysOut::detailsErrorln(SPL_CORE_EXPORT_DEFINITION, exportIR.getLocation());
}
}
}
}
}
}
void ParallelRegionChecker::checkForImportExport(const CompositeOperatorInstance& composite)
{
// Walk all the nested composites to see if any Import or Export operators are annotates with @parallel
const vector<const CompositeOperatorInstance*>& composites = composite.getCompositeInstances();
for (vector<const CompositeOperatorInstance*>::const_iterator it1 = composites.begin();
it1 != composites.end(); ++it1) {
const CompositeOperatorInstance& comp = **it1;
checkForImportExport(comp);
}
const vector<const PrimitiveOperatorInstance*>& primitives = composite.getPrimitiveInstances();
for (vector<const PrimitiveOperatorInstance*>::const_iterator it2 = primitives.begin();
it2 != primitives.end(); ++it2) {
const PrimitiveOperatorInstance& primitive = **it2;
if (primitive.isParallelRegion()) {
const string& kind = primitive.getKind();
if (kind == "spl.adapter::Import" || kind == "spl.adapter::Export") {
SysOut::errorln(SPL_CORE_NO_ANNOTATE_OPERATOR(
"parallel", kind == "spl.adapter::Import" ? "Import" : "Export"),
primitive.getLocation());
}
}
}
}
bool ParallelRegionChecker::portIsExpectingPunctuation(const OperatorGraphNode& gn, uint32_t port)
{
const OperatorModel& om = findOperatorModel(gn);
const InputPorts& inputPorts = om.getInputPorts();
const Operator::InputPort& p = inputPorts.getPortAt(port);
if (p.getWindowPunctuationInputMode() == WindowPunctuationInputMode::Expecting) {
return true;
} else if (p.getWindowPunctuationInputMode() == WindowPunctuationInputMode::Oblivious) {
return false;
}
// Need to check the window bound
const PrimitiveOperatorInstance* ir = gn.getOperatorIR();
assert(ir);
const PrimitiveOperatorInstance::Window* w = ir->getWindow(port);
if (w && w->getEvictionPolicy() == PrimitiveOperatorInstance::Window::Punct) {
return true;
}
return false;
}
void ParallelRegionChecker::checkForPunctExpectingPortsDownstreamFromParallelRegions(
const OperatorGraph& graph)
{
// Find all the input ports that expect punctuation
typedef pair<const OperatorGraphNode*, uint32_t> OperatorNode_Port;
deque<OperatorNode_Port> iports;
for (uint32_t j = 0; j < graph.numNodes(); j++) {
const OperatorGraphNode& gn = graph.getNode(j);
for (uint32_t i = 0; i < gn.getNumberOfInputs(); i++) {
// Is the input port expecting punctuation?
if (portIsExpectingPunctuation(gn, i))
iports.push_back(make_pair(&gn, i));
}
}
// Okay, we now know all inport ports where we care about punctuation
// Walk through them and check for any that re fed by a parallel region
typedef vector<OperatorGraphNode::ConnectionInfo> Connections;
while (!iports.empty()) {
OperatorNode_Port current = iports.front();
iports.pop_front();
const OperatorGraphNode& gn = *current.first;
uint32_t portNum = current.second;
const PrimitiveOperatorInstance* ir = gn.getOperatorIR();
// See if there is a parallel region upstream that either has no punctuation-generating operator in between,
// or is not an adjacent parallel region
const Connections& ups = gn.getUpstreamConnections(portNum);
// We should only have one input stream or the check for multiple streams feeding
// a punct-expecting port would/will catch it
if (ups.size() != 1)
continue;
const OperatorGraphNode* outputOperator = &ups[0].getOperator();
uint32_t outputPort = ups[0].getPort();
const OutputPorts* ops = &findOperatorModel(*outputOperator).getOutputPorts();
// Walk the connections until we loop, end, find a generating port, or find a problem
unordered_map<const OperatorGraphNode*, bool> seen; // remember what operators we've seen
while (seen.find(outputOperator) == seen.end()) {
// Keep track that we've been here
seen[outputOperator] = true;
// First make sure that the upstream op is not from a parallel region
const PrimitiveOperatorInstance* upsIR = outputOperator->getOperatorIR();
assert(NULL != upsIR);
if (upsIR->isInParallelRegion()) {
// The upstream op is in a parallel region. Is the current node?
if (ir->isInParallelRegion()) {
// So is the current node
// Are they in the same parallel region?
if (upsIR->parallelRegionName() != ir->parallelRegionName()) {
// No. So we have adjacent parallel regions, which means any punctuation is dropped by the
// splitters in the upstream region
SysOut::errorln(SPL_CORE_PUNCT_PORT_CONNECTED_TO_ADJACENT_PARALLEL_REGION(
gn.getName(), portNum),
gn.getOperatorIR()->getLocation());
break;
}
} else {
// A non-parallel region being fed by a non-adjacent parallel region...this is bad
SysOut::errorln(
SPL_CORE_PUNCT_PORT_CONNECTED_TO_POTENTIAL_MULTIPLE_STREAMS_DUE_TO_PARALLEL_REGION(
gn.getName(), portNum),
gn.getOperatorIR()->getLocation());
break;
}
}
// If the output port is punct generating we are happy
if (ops->getPortAt(outputPort).getWindowPunctuationOutputMode() ==
WindowPunctuationOutputMode::Generating)
break;
// The following is an error but will be reported by the punctuation checker
if (ops->getPortAt(outputPort).getWindowPunctuationOutputMode() ==
WindowPunctuationOutputMode::Free)
break;
// Check the input to this operator
// Punctuation Preserving Ports must have only 1 input that preserves markers
uint32_t portToCheck = 0;
if (outputOperator->getNumberOfInputs() > 1) {
// We have to figure out which port to check
const OutputPort& outputPort1 = ops->getPortAt(portNum);
assert(outputPort1.hasWindowPunctuationInputPort());
portToCheck = outputPort1.windowPunctuationInputPort();
}
const Connections& ups1 = outputOperator->getUpstreamConnections(portToCheck);
// An error diagnosed by the punctuation checker
if (ups1.size() != 1)
break;
// We now have exactly one stream of input
// Recursively check THIS stream
outputOperator = &ups1[0].getOperator();
outputPort = ups1[0].getPort();
ops = &findOperatorModel(*outputOperator).getOutputPorts();
ir = upsIR;
}
}
}
void ParallelRegionChecker::check(const OperatorGraph& graph)
{
CompositeDefinition const* mainComposite = FrontEndDriver::instance().getMainComposite();
if (NULL == mainComposite)
return;
CompositeOperatorInstance const* compOperInstanceIR = mainComposite->getImplicitInstance();
assert(NULL != compOperInstanceIR);
// Check to see if an Import or Export operator are annotated with @parallel
checkForImportExport(*compOperInstanceIR);
checkImportExportOperators(graph);
checkForPunctExpectingPortsDownstreamFromParallelRegions(graph);
}
const Operator::OperatorModel& ParallelRegionChecker::findOperatorModel(const OperatorGraphNode& gn)
{
// Find the name in the 'kind' of the context
const string& name = gn.getModel().getContext().getKind();
const Operator::OperatorModel* om = _path.findOperatorModel(name, NULL);
assert(om);
return *om;
}
| 47.373737 | 131 | 0.597797 | [
"vector"
] |
95d5f503289ddf4da987b09c73a5b950e9af8ac5 | 19,762 | cpp | C++ | slicerendermanager.cpp | avinfinity/UnmanagedCodeSnippets | 2bd848db88d7b271209ad30017c8f62307319be3 | [
"MIT"
] | null | null | null | slicerendermanager.cpp | avinfinity/UnmanagedCodeSnippets | 2bd848db88d7b271209ad30017c8f62307319be3 | [
"MIT"
] | null | null | null | slicerendermanager.cpp | avinfinity/UnmanagedCodeSnippets | 2bd848db88d7b271209ad30017c8f62307319be3 | [
"MIT"
] | null | null | null | #include "slicerendermanager.h"
#include "openglhelper.h"
#include "QMatrix4x4"
#include "iostream"
#include "QDebug"
#include "atomic"
namespace imt{
namespace volume{
SliceRenderManager::SliceRenderManager(imt::volume::VolumeInfo *volume , PLANETYPE planeType) : mVolume( volume ) , mPlaneType(planeType)
{
mIsInitialized = false;
mHasNewData = false;
mWte = 0;
}
void SliceRenderManager::setInfo( GLint surfaceSliceProgram, int nSurfaceVBOs, GLuint *surfaceVBOs, GLuint surfaceVAO, int nTris )
{
//mSurfaceSliceProgram = surfaceSliceProgram;
//mSurfaceVBOs = surfaceVBOs;
//mNumSurfaceVBOs = nSurfaceVBOs;
//mSurfaceVAO = surfaceVAO;
//mNumTriangles = nTris;
//GL_CHECK(glBindVertexArray(mSurfaceVAO));
//GL_CHECK(glBindVertexArray(0));
}
void SliceRenderManager::setSurface( std::vector< Eigen::Vector3f >& vertices, std::vector< unsigned int >& faces )
{
std::cout << " setting surface data " << std::endl;
mSurfaceVertices = vertices;
mSurfaceIndices = faces;
mHasNewData = true;
}
void SliceRenderManager::updateSurface()
{
mVertexRenderData.resize(mVolume->mVertices.size());
int nVertices = mVolume->mVertices.size();
if ( mVolume->mWallthickness.size() != mVolume->mVertices.size() )
{
mVolume->mWallthickness.resize( mVolume->mVertices.size() );
std::fill( mVolume->mWallthickness.begin() , mVolume->mWallthickness.end() , -1 );
}
if (mVolume->mVertexColors.size() != mVolume->mVertices.size())
{
mVolume->mVertexColors.resize(mVolume->mVertices.size());
std::fill(mVolume->mVertexColors.begin(), mVolume->mVertexColors.end(), Eigen::Vector3f(1, 1, 1));
}
for (int vv = 0; vv < nVertices; vv++)
{
mVertexRenderData[vv].mVertex = mVolume->mVertices[vv];
mVertexRenderData[vv].mVertexNormal = mVolume->mVertexNormals[vv];
mVertexRenderData[vv].mVertexColor = mVolume->mVertexColors[vv];
mVertexRenderData[vv].mWallThickness = mVolume->mWallthickness[vv];
if (vv > 10000 && vv < 10010)
{
std::cout << vv << " -- " << mVertexRenderData[vv].mVertexColor.transpose() << " " << mVertexRenderData[vv].mWallThickness << std::endl;
}
}
mSurfaceIndices = mVolume->mFaceIndices;
mHasNewData = true;
}
void SliceRenderManager::setOrthoProjectionMatrix( const QMatrix4x4& orthoProjMat )
{
mOrthoProjMat = orthoProjMat;
}
void SliceRenderManager::setCamera( TrackBallCamera *camera )
{
mCamera = camera;
}
void SliceRenderManager::setPlaneType(int planeType, Eigen::Vector3f& planeCoeff, int w, int h)
{
mCoeff = planeCoeff;
//std::cout << mCoeff << std::endl;
if (mWidth != w || mHeight != mHeight || planeType != mPlaneType)
{
mPlaneType = planeType;
mWidth = w;
mHeight = h;
Eigen::Vector2f xLimits, yLimits, zLimits;
xLimits(0) = mVolume->mVolumeOrigin(0);
yLimits(0) = mVolume->mVolumeOrigin(1);
zLimits(0) = mVolume->mVolumeOrigin(2);
xLimits(1) = mVolume->mVolumeOrigin(0) + mVolume->mVoxelStep( 0 ) * mVolume->mWidth;
yLimits(1) = mVolume->mVolumeOrigin(1) + mVolume->mVoxelStep( 1 ) * mVolume->mHeight;
zLimits(1) = mVolume->mVolumeOrigin(2) + mVolume->mVoxelStep( 2 ) * mVolume->mDepth;
buildProjectionmatrix( xLimits , yLimits , zLimits );
}
}
void SliceRenderManager::setViewPort(int w, int h)
{
mWidth = w;
mHeight = h;
}
void SliceRenderManager::setNumTriangles(int numTris)
{
mNumTriangles = numTris;
}
void SliceRenderManager::init()
{
initializeOpenGLFunctions();
mIsInitialized = true;
GL_CHECK(glGenBuffers(3, mSurfaceVBOs));
GL_CHECK(glGenBuffers(2, mSliceVBO));
GL_CHECK(glGenVertexArrays(2, mSurfaceVAO));
mFeedbackBuffer = mSurfaceVBOs[2];
GL_CHECK(glGenQueries(1, &mFeedBackQuery));
initializeShaders();
}
bool SliceRenderManager::isInitialized()
{
return mIsInitialized;
}
void SliceRenderManager::setDefaultFBO(GLint fbo)
{
mDefaultFBO = fbo;
}
void SliceRenderManager::initializeShaders()
{
QFile file1(":/crosssectionvert.glsl"), file2(":/crosssectionfbgeom.glsl"), file3(":/crosssectionfrag.glsl");
if (!file1.open(QIODevice::ReadOnly))
{
qDebug() << "Cannot open file for reading: ( mesh cross section vertex ) "
<< qPrintable(file1.errorString()) << endl;
return;
}
if (!file2.open(QIODevice::ReadOnly))
{
qDebug() << "Cannot open file for reading: ( mesh cross section geometry ) "
<< qPrintable(file2.errorString()) << endl;
return;
}
if (!file3.open(QIODevice::ReadOnly))
{
qDebug() << "Cannot open file for reading: ( mesh cross section fragment ) "
<< qPrintable(file3.errorString()) << endl;
return;
}
QString vertShaderSrc = file1.readAll();
QString geomShaderSrc = file2.readAll();
QString fragShaderSrc = file3.readAll();
GLuint vertexShader = compileShaders(GL_VERTEX_SHADER, vertShaderSrc.toStdString().c_str());
GLuint geomShader = compileShaders(GL_GEOMETRY_SHADER, geomShaderSrc.toStdString().c_str());
GLuint fragmentShader = compileShaders(GL_FRAGMENT_SHADER, fragShaderSrc.toStdString().c_str());
GLint program = glCreateProgram();
GL_CHECK(glBindAttribLocation(program, 0, "vert"));
GL_CHECK(glBindAttribLocation(program, 1, "normal"));
GL_CHECK(glBindAttribLocation(program, 2, "color"));
GL_CHECK(glBindAttribLocation(program, 3, "wallThickness"));
GL_CHECK(glAttachShader(program, vertexShader));
GL_CHECK(glAttachShader(program, geomShader));
GL_CHECK(glAttachShader(program, fragmentShader));
GL_CHECK(glLinkProgram(program));
GLint status;
GL_CHECK(glGetProgramiv(program, GL_LINK_STATUS, &status));
if (status == GL_FALSE)
{
GLchar emsg[1024];
GL_CHECK(glGetProgramInfoLog(program, sizeof(emsg), 0, emsg));
fprintf(stderr, "Error linking GLSL program : %s\n", emsg);
return;
}
mSurfaceSliceProgram = program;
QFile file4(":/crosssectionvert.glsl"), file5(":/crosssectionfbgeom.glsl");
if (!file4.open(QIODevice::ReadOnly))
{
qDebug() << "Cannot open file for reading: ( mesh cross section vertex ) "
<< qPrintable(file4.errorString()) << endl;
return;
}
if (!file5.open(QIODevice::ReadOnly))
{
qDebug() << "Cannot open file for reading: ( mesh cross section geometry ) "
<< qPrintable(file5.errorString()) << endl;
return;
}
vertShaderSrc = file4.readAll();
geomShaderSrc = file5.readAll();
program = glCreateProgram();
//qDebug() << geomShaderSrc << endl;
vertexShader = compileShaders(GL_VERTEX_SHADER, vertShaderSrc.toStdString().c_str());
geomShader = compileShaders(GL_GEOMETRY_SHADER, geomShaderSrc.toStdString().c_str());
GL_CHECK(glBindAttribLocation(program, 0, "vert"));
GL_CHECK(glBindAttribLocation(program, 1, "normal"));
GL_CHECK(glBindAttribLocation(program, 2, "color"));
GL_CHECK(glBindAttribLocation(program, 3, "wallThickness"));
GL_CHECK(glAttachShader(program, vertexShader));
GL_CHECK(glAttachShader(program, geomShader));
GL_CHECK(glLinkProgram(program));
status;
GL_CHECK(glGetProgramiv(program, GL_LINK_STATUS, &status));
if ( status == GL_FALSE )
{
GLchar emsg[1024];
GL_CHECK(glGetProgramInfoLog(program, sizeof(emsg), 0, emsg));
fprintf(stderr, "Error linking GLSL program : %s\n", emsg);
return;
}
mVolumeSliceTFProgram = program;
//declare transform feedback varying name
static const char *const vars[] = {
"intersectionPoint", "intersectionNormal", "intersectionColor"
};
std::cout << " variable count : " << sizeof(vars) / sizeof(vars[0]) << std::endl;
GL_CHECK( glTransformFeedbackVaryings(mVolumeSliceTFProgram, 3, vars, GL_INTERLEAVED_ATTRIBS) );
GL_CHECK( glLinkProgram(mVolumeSliceTFProgram) );
}
GLuint SliceRenderManager::compileShaders(GLenum shaderType, const char *shaderSource)
{
GLuint shader = glCreateShader(shaderType);
GL_CHECK(glShaderSource(shader, 1, &shaderSource, NULL));
GL_CHECK(glCompileShader(shader));
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLchar emsg[10024];
glGetShaderInfoLog(shader, sizeof(emsg), 0, emsg);
QString errMsg = QString("Error compiling GLSL shader (%s): %s\n") + emsg;
qDebug() << " error in compiling shaders , file : " << __FILE__ << " : line : " << __LINE__ << errMsg << endl;
}
return shader;
}
void SliceRenderManager::setChangedData()
{
updateSurface();
}
void SliceRenderManager::render()
{
if (!mIsInitialized)
return;
GL_CHECK( glBindVertexArray( mSurfaceVAO[0] ) );
if ( mHasNewData )
{
GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, mSurfaceVBOs[0]));
GL_CHECK(glBufferData(GL_ARRAY_BUFFER, mVertexRenderData.size() * sizeof(VertexData),
(void *)mVertexRenderData.data(), GL_STATIC_DRAW));
//update points
GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mSurfaceVBOs[1]));
GL_CHECK(glBufferData(GL_ELEMENT_ARRAY_BUFFER, mSurfaceIndices.size() * sizeof(GLuint),
mSurfaceIndices.data(), GL_STATIC_DRAW));
//update faces
GL_CHECK(glEnableVertexAttribArray(0));
GL_CHECK(glEnableVertexAttribArray(1));
GL_CHECK(glEnableVertexAttribArray(2));
GL_CHECK(glEnableVertexAttribArray(3));
GL_CHECK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), 0));
int offset = 3 * sizeof(float);
GL_CHECK(glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), (void*)offset));
offset += 3 * sizeof(float);
GL_CHECK(glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), (void*)offset));
offset += 3 * sizeof(float);
GL_CHECK(glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(VertexData), (void*)offset));
mHasNewData = false;
GL_CHECK(glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, mFeedbackBuffer));
GL_CHECK(glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 1024 * 1024 * 100, NULL, GL_DYNAMIC_COPY));
GL_CHECK(glBindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, mFeedbackBuffer, 0, 1024 * 1024 * 100));
}
computeSlice();
renderSlice();
}
void computeOppositeEndsOnPlane( std::vector< Eigen::Vector3f >& edgeEnds, std::vector< Eigen::Vector3f >& edgeNormals, std::vector< Eigen::Vector3f >& colors ,
std::vector< SliceRenderManager::VertexData >& vertexData ,
RTCDevice& device, RTCScene& scene, float vstep)
{
#if 0
vertexData.resize(edgeEnds.size());
float maxLength = FLT_MAX;
float nearV = vstep * 0.01;
int numVertices = edgeEnds.size();
std::atomic<int > nValidIntersection;
nValidIntersection = 0;
#pragma omp parallel for
for (int vv = 0; vv < numVertices + 8; vv += 8)
{
RTCRay8 ray;
for (int ii = 0; ii < 8; ii++)
{
int id;
if ((vv + ii) >= numVertices)
{
id = numVertices - 1;
}
else
{
id = vv + ii;
}
ray.orgx[ii] = edgeEnds[id](0);
ray.orgy[ii] = edgeEnds[id](1);
ray.orgz[ii] = edgeEnds[id](2);
}
for (int ii = 0; ii < 8; ii++)
{
Eigen::Vector3f dir;
int id;
if ((vv + ii) >= numVertices)
{
id = numVertices - 1;
}
else
{
id = vv + ii;
}
//std::cout << edgeNormals[id].transpose() << std::endl;
ray.dirx[ii] = -edgeNormals[id](0);
ray.diry[ii] = -edgeNormals[id](1);
ray.dirz[ii] = -edgeNormals[id](2);
ray.geomID[ii] = RTC_INVALID_GEOMETRY_ID;
ray.instID[ii] = RTC_INVALID_GEOMETRY_ID;
ray.primID[ii] = RTC_INVALID_GEOMETRY_ID;
ray.tnear[ii] = nearV;
ray.tfar[ii] = maxLength;
ray.mask[ii] = 0xFFFFFFFF;
ray.time[ii] = 0.f;
}
__aligned(32) int valid8[8] = { -1, -1, -1, -1, -1, -1, -1, -1 };
rtcIntersect8(valid8, scene, ray);
for (int ii = 0; ii < 8; ii++)
{
if ((vv + ii) >= numVertices)
{
continue;
}
if (ray.primID[ii] != RTC_INVALID_GEOMETRY_ID)
{
vertexData[vv + ii].mVertex(0) = ray.orgx[ii];
vertexData[vv + ii].mVertex(1) = ray.orgy[ii];
vertexData[vv + ii].mVertex(2) = ray.orgz[ii];
vertexData[vv + ii].mWallThickness = ray.tfar[ii];
vertexData[vv + ii].mVertexNormal(0) = ray.dirx[ii];
vertexData[vv + ii].mVertexNormal(1) = ray.diry[ii];
vertexData[vv + ii].mVertexNormal(2) = ray.dirz[ii];
vertexData[vv + ii].mVertexColor = colors[vv + ii];
nValidIntersection++;
if (vertexData[vv + ii].mWallThickness > vstep * 100)
{
vertexData[vv + ii].mWallThickness = -1;
vertexData[vv + ii].mVertexColor = Eigen::Vector3f(1, 1, 1);
}
}
else
{
vertexData[vv + ii].mWallThickness = -1;
vertexData[vv + ii].mVertexColor = Eigen::Vector3f(1, 1, 1);
}
}
}
std::cout << " num valid intersections : " << nValidIntersection << std::endl;
#endif
}
void SliceRenderManager::computeSlice()
{
GL_CHECK(glUseProgram(mVolumeSliceTFProgram));
#if 1
if (mSurfaceIndices.size() > 0 )
{
GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, mSurfaceVBOs[0]));
// Bind transform feedback and target buffer
GL_CHECK( glBindTransformFeedback(GL_TRANSFORM_FEEDBACK, 0) );
GL_CHECK(glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, mFeedbackBuffer));
GL_CHECK( glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) );
GLint planeNormalLoc = glGetUniformLocation( mVolumeSliceTFProgram, "planeNormal");
GLint planeCoeffLoc = glGetUniformLocation( mVolumeSliceTFProgram, "planeCoeff");
GLint planeTypeLoc = glGetUniformLocation( mVolumeSliceTFProgram, "pType");
GLint mvpMatrix = glGetUniformLocation(mVolumeSliceTFProgram, "mvpMatrix");
GL_CHECK( glUniform3f(planeCoeffLoc, mCoeff(0), mCoeff(1), mCoeff(2)));
GL_CHECK( glUniform1i(planeTypeLoc, mPlaneType));
GL_CHECK(glUniformMatrix4fv(mvpMatrix, 1, false, mCamera->getModelViewProjectionMatrix().data()));
// Begin transform feedback
GL_CHECK( glBeginQueryIndexed( GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN,0 , mFeedBackQuery) );
GL_CHECK( glBeginTransformFeedback(GL_LINES));
GL_CHECK( glDrawElements( GL_TRIANGLES , mSurfaceIndices.size() , GL_UNSIGNED_INT , (GLuint *)NULL ) );
GL_CHECK( glEndTransformFeedback() );
GL_CHECK( glEndQueryIndexed(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN , 0) );
GLuint numWrittenPrimitives;
GL_CHECK( glGetQueryObjectuiv(mFeedBackQuery, GL_QUERY_RESULT, &numWrittenPrimitives ) );
numWrittenPrimitives *= 3;
// std::cout << " num preimitives : " << numWrittenPrimitives << std::endl;
std::vector< Eigen::Vector3f > vertices(numWrittenPrimitives), normals(numWrittenPrimitives), colors(numWrittenPrimitives);
Eigen::Vector3f* vdata = ( Eigen::Vector3f* ) glMapBuffer( GL_TRANSFORM_FEEDBACK_BUFFER , GL_READ_ONLY );
for ( int pp = 0; pp < numWrittenPrimitives; pp++)
{
vertices[pp] = vdata[3 * pp];
normals[pp] = vdata[3 * pp + 1];
colors[pp] = vdata[3 * pp + 2];
}
GL_CHECK( glUnmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER) );
if ( numWrittenPrimitives > 0 )
{
std::vector< Eigen::Vector3f > otherEnds(numWrittenPrimitives), otherEndNormals(numWrittenPrimitives);
std::vector< bool > oppositeEndFound( numWrittenPrimitives , false );
mSliceVertexData.resize(numWrittenPrimitives);
computeOppositeEndsOnPlane( vertices, normals, colors , mSliceVertexData , mWte->mDevice, mWte->mScene, mVolume->mVoxelStep(0) );
}
}
#endif
GL_CHECK(glUseProgram(0));
}
void SliceRenderManager::renderSlice()
{
if (mSliceVertexData.size() == 0)
return;
GL_CHECK(glUseProgram(mSurfaceSliceProgram));
GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mDefaultFBO));
//GL_CHECK(glEnable(GL_LINE_SMOOTH));
GL_CHECK( glDisable(GL_CULL_FACE) );
GL_CHECK(glBindVertexArray(mSurfaceVAO[1]));
GL_CHECK( glBindBuffer(GL_ARRAY_BUFFER, mSliceVBO[0]));
GL_CHECK( glBufferData( GL_ARRAY_BUFFER, mSliceVertexData.size() * sizeof(VertexData),
(void *)mSliceVertexData.data(), GL_DYNAMIC_DRAW ) );
std::vector< unsigned int > indexArr(mSliceVertexData.size());
for (int ii = 0; ii < indexArr.size(); ii++)
{
indexArr[ii] = ii;
}
GL_CHECK( glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mSliceVBO[1]));
GL_CHECK( glBufferData( GL_ELEMENT_ARRAY_BUFFER, indexArr.size() * sizeof(unsigned int),
(void *)indexArr.data(), GL_DYNAMIC_DRAW));
//update faces
GL_CHECK(glEnableVertexAttribArray(0));
GL_CHECK(glEnableVertexAttribArray(1));
GL_CHECK(glEnableVertexAttribArray(2));
GL_CHECK(glEnableVertexAttribArray(3));
GL_CHECK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), 0));
int offset = 3 * sizeof(float);
GL_CHECK(glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), (void*)offset));
offset += 3 * sizeof(float);
GL_CHECK(glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), (void*)offset));
offset += 3 * sizeof(float);
GL_CHECK(glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, sizeof(VertexData), (void*)offset));
#if 1
GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
GLint mvpMatrix = glGetUniformLocation(mSurfaceSliceProgram, "mvpMatrix");
GL_CHECK(glUniformMatrix4fv(mvpMatrix, 1, false, mCamera->getModelViewProjectionMatrix().data()));
GL_CHECK( glDrawElements( GL_LINES , mSliceVertexData.size() , GL_UNSIGNED_INT , 0 ) );
#endif
GL_CHECK(glUseProgram(0));
GL_CHECK(glBindVertexArray(0));
}
void SliceRenderManager::setWallthicknessEstimator( imt::volume::WallthicknessEstimator *wte )
{
mWte = wte;
}
void SliceRenderManager::registerKeyPressEvent( QKeyEvent* e )
{
}
void SliceRenderManager::registerKeyReleaseEvent( QKeyEvent* e)
{
}
void SliceRenderManager::registerMousePressEvent( QMouseEvent *event )
{
}
void SliceRenderManager::registerMouseReleaseEvent( QMouseEvent *event )
{
}
void SliceRenderManager::registerMouseMoveEvent( QMouseEvent *event )
{
}
void SliceRenderManager::registerWheelEvent( QWheelEvent * event )
{
}
void SliceRenderManager::buildProjectionmatrix( const Eigen::Vector2f& xLimits , const Eigen::Vector2f& yLimits , const Eigen::Vector2f& zLimits)
{
float leftV, rightV, bottomV, topV, nearV, farV;
if (mPlaneType == XY)
{
leftV = xLimits(0);
rightV = xLimits(1);
bottomV = yLimits(0);
topV = yLimits(1);
nearV = zLimits(0);
farV = zLimits(1);
}
else if (mPlaneType == YZ)
{
leftV = yLimits(0);
rightV = yLimits(1);
bottomV = zLimits(0);
topV = zLimits(1);
nearV = xLimits(0);
farV = xLimits(1);
}
else
{
leftV = zLimits(0);
rightV = zLimits(1);
bottomV = xLimits(0);
topV = xLimits(1);
nearV = yLimits(0);
farV = yLimits(1);
}
QMatrix4x4 orthoProjMat;
orthoProjMat.frustum( leftV , rightV , bottomV , topV , nearV , farV );
mOrthoProjMat = orthoProjMat;
}
void SliceRenderManager::setLimits( const Eigen::Vector3f& minLimits , const Eigen::Vector3f& maxLimits )
{
mMinLimits = minLimits;
mMaxLimits = maxLimits;
Eigen::Vector2f xLimits(minLimits(0), maxLimits(0)), yLimits(minLimits(1), maxLimits(1)), zLimits(minLimits(2), maxLimits(2));
buildProjectionmatrix(xLimits, yLimits, zLimits);
}
}
} | 24.889169 | 162 | 0.669821 | [
"mesh",
"geometry",
"render",
"vector",
"transform"
] |
95e9a43841795db3329e6ce9d432a903d4665b54 | 1,193 | cpp | C++ | aws-cpp-sdk-cloudhsmv2/source/model/DeleteHsmRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-cloudhsmv2/source/model/DeleteHsmRequest.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-cloudhsmv2/source/model/DeleteHsmRequest.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/cloudhsmv2/model/DeleteHsmRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::CloudHSMV2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DeleteHsmRequest::DeleteHsmRequest() :
m_clusterIdHasBeenSet(false),
m_hsmIdHasBeenSet(false),
m_eniIdHasBeenSet(false),
m_eniIpHasBeenSet(false)
{
}
Aws::String DeleteHsmRequest::SerializePayload() const
{
JsonValue payload;
if(m_clusterIdHasBeenSet)
{
payload.WithString("ClusterId", m_clusterId);
}
if(m_hsmIdHasBeenSet)
{
payload.WithString("HsmId", m_hsmId);
}
if(m_eniIdHasBeenSet)
{
payload.WithString("EniId", m_eniId);
}
if(m_eniIpHasBeenSet)
{
payload.WithString("EniIp", m_eniIp);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DeleteHsmRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "BaldrApiService.DeleteHsm"));
return headers;
}
| 18.353846 | 90 | 0.726739 | [
"model"
] |
95ea33e818774005a2fdfa0adc73f68b58f9799b | 3,290 | cpp | C++ | Code/BBearEditor/Engine/2D/BBCanvas.cpp | xiaoxianrouzhiyou/BBearEditor | 0f1b779d87c297661f9a1e66d0613df43f5fe46b | [
"MIT"
] | 26 | 2021-06-30T02:19:30.000Z | 2021-07-23T08:38:46.000Z | Code/BBearEditor/Engine/2D/BBCanvas.cpp | lishangdian/BBearEditor-2.0 | 1f4b463ef756ed36cc15d10abae822efc400c4d7 | [
"MIT"
] | null | null | null | Code/BBearEditor/Engine/2D/BBCanvas.cpp | lishangdian/BBearEditor-2.0 | 1f4b463ef756ed36cc15d10abae822efc400c4d7 | [
"MIT"
] | 3 | 2021-09-01T08:19:30.000Z | 2021-12-28T19:06:40.000Z | #include "BBCanvas.h"
#include "BBSpriteObject2D.h"
#include "Geometry/BBBoundingBox2D.h"
#include "2D/BBClipArea2D.h"
#include "Render/BBMaterial.h"
#include "Scene/BBSceneManager.h"
#define IterateSprite2DSet(x) \
for (QList<BBSpriteObject2D*>::Iterator itr = m_SpriteObject2DSet.begin(); itr != m_SpriteObject2DSet.end(); itr++) {x;}
BBCanvas::BBCanvas(int x, int y, int nWidth, int nHeight)
: BBGameObject(x, y, nWidth, nHeight)
{
m_pAABBBoundingBox2D = new BBAABBBoundingBox2D(x, y, nWidth / 2.0, nHeight / 2.0);
m_pClipArea2D = new BBClipArea2D(x, y, nWidth / 2.0, nHeight / 2.0);
resize(800.0f, 600.0f);
}
BBCanvas::~BBCanvas()
{
BB_SAFE_DELETE(m_pAABBBoundingBox2D);
BB_SAFE_DELETE(m_pClipArea2D);
IterateSprite2DSet(delete *itr);
}
void BBCanvas::init()
{
m_pAABBBoundingBox2D->init();
m_pClipArea2D->init();
IterateSprite2DSet(init());
}
void BBCanvas::render()
{
m_pAABBBoundingBox2D->render(this);
m_pClipArea2D->render(this);
IterateSprite2DSet((*itr)->render(this));
}
void BBCanvas::resize(float fWidth, float fHeight)
{
m_UniformInfo[0] = fWidth / 2.0f;
m_UniformInfo[1] = fHeight / 2.0f;
m_UniformInfo[2] = 0.0f;
m_UniformInfo[3] = 0.0f;
}
/**
* @brief BBCanvas::setPosition screen coordinate
* @param position
* @param bUpdateLocalTransform
*/
void BBCanvas::setPosition(const QVector3D &position, bool bUpdateLocalTransform)
{
BBGameObject::setPosition(position, bUpdateLocalTransform);
m_pAABBBoundingBox2D->setPosition(position, bUpdateLocalTransform);
m_pClipArea2D->setPosition(position, bUpdateLocalTransform);
IterateSprite2DSet((*itr)->setPosition(position, bUpdateLocalTransform));
}
void BBCanvas::setRotation(int nAngle, const QVector3D &axis, bool bUpdateLocalTransform)
{
BBGameObject::setRotation(nAngle, axis, bUpdateLocalTransform);
BBGameObject::setRotation(QVector3D(0, 0, m_Rotation.z()));
m_pAABBBoundingBox2D->setRotation(nAngle, axis, bUpdateLocalTransform);
m_pClipArea2D->setRotation(nAngle, axis, bUpdateLocalTransform);
IterateSprite2DSet((*itr)->setRotation(nAngle, axis, bUpdateLocalTransform));
}
void BBCanvas::setRotation(const QVector3D &rotation, bool bUpdateLocalTransform)
{
BBGameObject::setRotation(rotation, bUpdateLocalTransform);
m_pAABBBoundingBox2D->setRotation(rotation, bUpdateLocalTransform);
m_pClipArea2D->setRotation(rotation, bUpdateLocalTransform);
IterateSprite2DSet((*itr)->setRotation(rotation, bUpdateLocalTransform));
}
void BBCanvas::setScale(const QVector3D &scale, bool bUpdateLocalTransform)
{
BBGameObject::setScale(scale, bUpdateLocalTransform);
IterateSprite2DSet((*itr)->setScale(scale, bUpdateLocalTransform));
// m_pBoundingBox2D->setScale(scale, bUpdateLocalTransform);
}
void BBCanvas::setActivity(bool bActive)
{
IterateSprite2DSet((*itr)->setActivity(bActive));
// m_pBoundingBox2D->setActivity(bActive);
setVisibility(bActive);
}
void BBCanvas::setVisibility(bool bVisible)
{
// m_pBoundingBox2D->setVisibility(bVisible);
}
bool BBCanvas::hit(int x, int y)
{
return m_pAABBBoundingBox2D->hit(x, y);
}
void BBCanvas::addSpriteObject2D(BBSpriteObject2D *pSpriteObject2D)
{
m_SpriteObject2DSet.append(pSpriteObject2D);
}
| 30.747664 | 120 | 0.745593 | [
"geometry",
"render"
] |
95ea4086e3dd812ec9d73ababcef97b5e9df82eb | 497 | cpp | C++ | 334/P334/P334/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | 334/P334/P334/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | 334/P334/P334/main.cpp | swy20190/Leetcode-Cracker | 3b80eacfa63983d5fcc50442f0813296d5c1af94 | [
"MIT"
] | null | null | null | #include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int len = nums.size();
if (len < 3) {
return false;
}
int num_max = INT_MAX;
int num_min = INT_MAX;
for (int i = 0; i < len; i++) {
if (nums[i] < num_min) {
num_min = nums[i];
}
else if (nums[i] > num_min && nums[i] < num_max) {
num_max = nums[i];
}
else if (nums[i] > num_max) {
return true;
}
}
return false;
}
}; | 17.75 | 53 | 0.571429 | [
"vector"
] |
95ee3d34a168e337b5a78a7801123d79c24c5ea9 | 1,876 | hpp | C++ | include/shiguredo/mp4/box/sidx.hpp | kounoike/cpp-mp4 | 65703c1402242afcc1e4d822d9828e79f3dcec01 | [
"Apache-2.0"
] | 23 | 2020-12-29T07:17:30.000Z | 2022-03-25T09:18:37.000Z | include/shiguredo/mp4/box/sidx.hpp | kounoike/cpp-mp4 | 65703c1402242afcc1e4d822d9828e79f3dcec01 | [
"Apache-2.0"
] | 2 | 2021-01-12T06:02:42.000Z | 2021-05-19T01:44:22.000Z | include/shiguredo/mp4/box/sidx.hpp | kounoike/cpp-mp4 | 65703c1402242afcc1e4d822d9828e79f3dcec01 | [
"Apache-2.0"
] | 2 | 2021-05-04T02:15:17.000Z | 2022-02-19T14:45:00.000Z | #pragma once
#include <cstdint>
#include <istream>
#include <string>
#include <vector>
#include "shiguredo/mp4/box.hpp"
#include "shiguredo/mp4/box_type.hpp"
namespace shiguredo::mp4::bitio {
class Reader;
class Writer;
} // namespace shiguredo::mp4::bitio
namespace shiguredo::mp4::box {
struct SidxReferenceParameters {
const bool reference_type;
const std::uint32_t reference_size;
const std::uint32_t subsegument_duration;
const bool starts_with_sap;
const std::uint8_t sap_type;
const std::uint32_t sap_delta_time;
};
class SidxReference {
public:
SidxReference() = default;
explicit SidxReference(const SidxReferenceParameters&);
std::string toString() const;
std::uint64_t writeData(bitio::Writer*) const;
std::uint64_t readData(bitio::Reader*);
private:
bool m_reference_type;
std::uint32_t m_reference_size;
std::uint32_t m_subsegument_duration;
bool m_starts_with_sap;
std::uint8_t m_sap_type;
std::uint32_t m_sap_delta_time;
};
struct SidxParameters {
const std::uint8_t version = 0;
const std::uint32_t flags = 0x000000;
const std::uint32_t reference_id;
const std::uint32_t timescale;
const std::uint64_t earliest_presentation_time;
const std::uint64_t first_offset;
const std::vector<SidxReference> references;
};
BoxType box_type_sidx();
class Sidx : public FullBox {
public:
Sidx();
explicit Sidx(const SidxParameters&);
std::string toStringOnlyData() const override;
std::uint64_t writeData(std::ostream&) const override;
std::uint64_t getDataSize() const override;
std::uint64_t readData(std::istream&) override;
private:
std::uint32_t m_reference_id;
std::uint32_t m_timescale;
std::uint64_t m_earliest_presentation_time;
std::uint64_t m_first_offset;
std::uint16_t m_reserved = 0;
std::vector<SidxReference> m_references;
};
} // namespace shiguredo::mp4::box
| 23.160494 | 57 | 0.753731 | [
"vector"
] |
95fc77f08b17c5a4e3be78037634b6cbec9fff6f | 5,396 | cpp | C++ | Gem/Code/Source/Components/NetworkAiComponent.cpp | CodeLikeCXK/o3de-multiplayersample | 9828062945f33277946e0215202731b1b8b913ca | [
"Apache-2.0",
"MIT"
] | null | null | null | Gem/Code/Source/Components/NetworkAiComponent.cpp | CodeLikeCXK/o3de-multiplayersample | 9828062945f33277946e0215202731b1b8b913ca | [
"Apache-2.0",
"MIT"
] | null | null | null | Gem/Code/Source/Components/NetworkAiComponent.cpp | CodeLikeCXK/o3de-multiplayersample | 9828062945f33277946e0215202731b1b8b913ca | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Source/Components/NetworkAiComponent.h>
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/Serialization/SerializeContext.h>
#include <Source/Components/NetworkPlayerMovementComponent.h>
#include <Source/Components/NetworkWeaponsComponent.h>
#include <AzCore/Time/ITime.h>
#include <Multiplayer/Components/NetBindComponent.h>
namespace MultiplayerSample
{
constexpr static float SecondsToMs = 1000.f;
void NetworkAiComponent::Reflect(AZ::ReflectContext* context)
{
if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
{
serializeContext->Class<NetworkAiComponent, NetworkAiComponentBase>()->Version(1);
}
NetworkAiComponentBase::Reflect(context);
}
void NetworkAiComponent::OnInit()
{
}
void NetworkAiComponent::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
{
}
void NetworkAiComponent::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
{
}
void NetworkAiComponent::TickMovement(NetworkPlayerMovementComponentController& movementController, float deltaTime)
{
// TODO: Execute this tick only if this component is owned by this endpoint (currently ticks on server only)
float deltaTimeMs = deltaTime * SecondsToMs;
m_remainingTimeMs -= deltaTimeMs;
if (m_remainingTimeMs <= 0)
{
// Determine a new directive after 500 to 9500 ms
m_remainingTimeMs = m_lcg.GetRandomFloat() * (m_actionIntervalMaxMs - m_actionIntervalMinMs) + m_actionIntervalMinMs;
m_turnRate = 1.f / m_remainingTimeMs;
// Randomize new target yaw and pitch and compute the delta from the current yaw and pitch respectively
m_targetYawDelta = -movementController.m_viewYaw + (m_lcg.GetRandomFloat() * 2.f - 1.f);
m_targetPitchDelta = -movementController.m_viewPitch + (m_lcg.GetRandomFloat() - 0.5f);
// Randomize the action and strafe direction (used only if we decide to strafe)
m_action = static_cast<Action>(m_lcg.GetRandom() % static_cast<int>(Action::COUNT));
m_strafingRight = static_cast<bool>(m_lcg.GetRandom() % 2);
}
// Translate desired motion into inputs
// Interpolate the current view yaw and pitch values towards the desired values
movementController.m_viewYaw += m_turnRate * deltaTimeMs * m_targetYawDelta;
movementController.m_viewPitch += m_turnRate * deltaTimeMs * m_targetPitchDelta;
// Reset keyboard movement inputs decided on the previous frame
movementController.m_forwardDown = false;
movementController.m_backwardDown = false;
movementController.m_leftDown = false;
movementController.m_rightDown = false;
movementController.m_sprinting = false;
movementController.m_jumping = false;
movementController.m_crouching = false;
switch (m_action)
{
case Action::Default:
movementController.m_forwardDown = true;
break;
case Action::Sprinting:
movementController.m_forwardDown = true;
movementController.m_sprinting = true;
break;
case Action::Jumping:
movementController.m_forwardDown = true;
movementController.m_jumping = true;
break;
case Action::Crouching:
movementController.m_forwardDown = true;
movementController.m_crouching = true;
break;
case Action::Strafing:
if (m_strafingRight)
{
movementController.m_rightDown = true;
}
else
{
movementController.m_leftDown = true;
}
break;
default:
break;
}
}
void NetworkAiComponent::TickWeapons(NetworkWeaponsComponentController& weaponsController, float deltaTime)
{
// TODO: Execute this tick only if this component is owned by this endpoint (currently ticks on server only)
m_timeToNextShot -= deltaTime * SecondsToMs;
if (m_timeToNextShot <= 0)
{
if (m_shotFired)
{
// Fire weapon between 100 and 10000 ms from now
m_timeToNextShot = m_lcg.GetRandomFloat() * (m_fireIntervalMaxMs - m_fireIntervalMinMs) + m_fireIntervalMinMs;
m_shotFired = false;
weaponsController.m_weaponFiring = false;
}
else
{
weaponsController.m_weaponFiring = true;
m_shotFired = true;
}
}
}
void NetworkAiComponent::ConfigureAi(
float fireIntervalMinMs, float fireIntervalMaxMs, float actionIntervalMinMs, float actionIntervalMaxMs, uint64_t seed)
{
m_fireIntervalMinMs = fireIntervalMinMs;
m_fireIntervalMaxMs = fireIntervalMaxMs;
m_actionIntervalMinMs = actionIntervalMinMs;
m_actionIntervalMaxMs = actionIntervalMaxMs;
m_lcg.SetSeed(seed);
}
}
| 38 | 158 | 0.659377 | [
"3d"
] |
95fe5c52f11617d6c712bffa5982b9476c47bd2a | 3,280 | cpp | C++ | src/gradient/gradient.cpp | Toxe/mandelbrot-sfml-imgui | e9375290a475a264c5b57e7678851ffae752d3b0 | [
"MIT"
] | 6 | 2021-04-14T15:49:46.000Z | 2022-03-05T12:39:31.000Z | src/gradient/gradient.cpp | Toxe/mandelbrot-sfml-imgui | e9375290a475a264c5b57e7678851ffae752d3b0 | [
"MIT"
] | null | null | null | src/gradient/gradient.cpp | Toxe/mandelbrot-sfml-imgui | e9375290a475a264c5b57e7678851ffae752d3b0 | [
"MIT"
] | null | null | null | #include "gradient.h"
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <limits>
#include <regex>
#include <stdexcept>
#include <string>
#include <vector>
#include <fmt/ostream.h>
#include <spdlog/spdlog.h>
#include <SFML/Graphics/Color.hpp>
const std::string gradients_directory = "assets/gradients";
// Compare two float values for "enough" equality.
bool equal_enough(float a, float b) noexcept
{
constexpr float epsilon = std::numeric_limits<float>::epsilon();
a = std::abs(a);
b = std::abs(b);
return std::abs(a - b) <= std::max(a, b) * epsilon;
}
Gradient load_gradient(const std::string& name)
{
auto path = std::filesystem::path{gradients_directory} / (name + ".gradient");
spdlog::debug("loading gradient: {}", path);
Gradient gradient{name};
gradient.colors.push_back(GradientColor{0.0f, 0.0f, 0.0f, 0.0f});
gradient.colors.push_back(GradientColor{1.0f, 1.0f, 1.0f, 1.0f});
std::ifstream in{path};
std::string line;
if (!in.is_open())
throw std::runtime_error("unable to open gradient file");
const std::regex re{R"(([0-9]*\.?[0-9]+):\s*([0-9]*\.?[0-9]+),\s*([0-9]*\.?[0-9]+),\s*([0-9]*\.?[0-9]+)$)"};
std::smatch m;
while (std::getline(in, line)) {
if (std::regex_match(line, m, re)) {
float pos = std::stof(m[1]);
auto col = std::find(gradient.colors.begin(), gradient.colors.end(), pos);
if (col != gradient.colors.end())
*col = GradientColor{pos, std::stof(m[2]), std::stof(m[3]), std::stof(m[4])};
else
gradient.colors.push_back({pos, std::stof(m[2]), std::stof(m[3]), std::stof(m[4])});
}
}
std::sort(gradient.colors.begin(), gradient.colors.end());
return gradient;
}
sf::Color color_from_gradient_range(const GradientColor& left, const GradientColor& right, const float pos) noexcept
{
const float relative_pos_between_colors = (pos - left.pos) / (right.pos - left.pos);
return sf::Color{static_cast<sf::Uint8>(255.0f * std::lerp(left.r, right.r, relative_pos_between_colors)),
static_cast<sf::Uint8>(255.0f * std::lerp(left.g, right.g, relative_pos_between_colors)),
static_cast<sf::Uint8>(255.0f * std::lerp(left.b, right.b, relative_pos_between_colors))};
}
sf::Color color_from_gradient(const Gradient& gradient, const float pos) noexcept
{
const auto end = gradient.colors.cend();
const auto it = std::adjacent_find(gradient.colors.cbegin(), end,
[&](const GradientColor& left, const GradientColor& right) { return left.pos <= pos && pos <= right.pos; });
if (it != end)
return color_from_gradient_range(*it, *(it + 1), pos);
else
return sf::Color::Black;
}
std::vector<Gradient> load_available_gradients()
{
std::vector<Gradient> available_gradients;
for (const auto& p : std::filesystem::directory_iterator(gradients_directory))
available_gradients.push_back(load_gradient(p.path().filename().replace_extension("").string()));
std::sort(available_gradients.begin(), available_gradients.end(),
[](const Gradient& a, const Gradient& b) { return a.name_ < b.name_; });
return available_gradients;
}
| 33.469388 | 116 | 0.639634 | [
"vector"
] |
2508159986e0edeeed16264af415ebae047604ce | 3,624 | cpp | C++ | benchmarks/benchmark_feature_cached_string.cpp | jandom/hawktracer | e53b07bc812c4cfe8f6253ddb48ac43de8fa74a8 | [
"MIT"
] | 116 | 2018-05-04T14:51:58.000Z | 2022-02-08T23:47:28.000Z | benchmarks/benchmark_feature_cached_string.cpp | jandom/hawktracer | e53b07bc812c4cfe8f6253ddb48ac43de8fa74a8 | [
"MIT"
] | 58 | 2018-05-04T15:00:15.000Z | 2020-11-06T11:34:11.000Z | benchmarks/benchmark_feature_cached_string.cpp | beila/hawktracer | d427c6a66097787f4e5431e1cae0278f1f03ca4c | [
"MIT"
] | 32 | 2018-05-05T12:05:56.000Z | 2021-12-06T02:18:05.000Z | #include <hawktracer/timeline.h>
#include <hawktracer/feature_cached_string.h>
#include <benchmark/benchmark.h>
#include <vector>
#include <string>
#include <queue>
std::vector<std::string> generate_unique_strings(size_t str_length)
{
std::vector<std::string> ret;
std::queue<std::string> q;
q.push("");
while (!q.empty())
{
std::string cur_s = q.front();
q.pop();
for (char c = 'A'; c <= 'a'; c++)
{
std::string new_s = cur_s + c;
if (new_s.length() == str_length)
{
ret.emplace_back(std::move(new_s));
}
else
{
q.emplace(std::move(new_s));
}
}
}
return ret;
}
static void FeatureCachedStringAddMapping(benchmark::State& state)
{
HT_Timeline* timeline = ht_timeline_create(1024, HT_FALSE, HT_TRUE, NULL, NULL);
ht_feature_cached_string_enable(timeline, HT_FALSE);
auto unique_strings = generate_unique_strings(4);
size_t ctr = 0;
for (auto _ : state)
{
ht_feature_cached_string_add_mapping(timeline, unique_strings[ctr++ % unique_strings.size()].c_str());
}
ht_timeline_destroy(timeline);
}
BENCHMARK(FeatureCachedStringAddMapping);
static void FeatureCachedStringPushMapping_1185921_strings(benchmark::State& state)
{
HT_Timeline* timeline = ht_timeline_create(1024, HT_FALSE, HT_TRUE, NULL, NULL);
ht_feature_cached_string_enable(timeline, HT_FALSE);
auto unique_strings = generate_unique_strings(3);
for (size_t i = 0; i < unique_strings.size(); i++)
{
ht_feature_cached_string_add_mapping(timeline, unique_strings[i].c_str());
}
for (auto _ : state)
{
ht_feature_cached_string_push_map(timeline);
}
ht_timeline_destroy(timeline);
}
BENCHMARK(FeatureCachedStringPushMapping_1185921_strings);
static void FeatureCachedStringAddPushMappingDifferentLabels(benchmark::State& state)
{
HT_Timeline* timeline = ht_timeline_create(1024, HT_FALSE, HT_TRUE, NULL, NULL);
ht_feature_cached_string_enable(timeline, HT_FALSE);
auto unique_strings = generate_unique_strings(4);
size_t ctr = 0;
for (auto _ : state)
{
ht_feature_cached_string_add_mapping(timeline, unique_strings[ctr++ % unique_strings.size()].c_str());
ht_feature_cached_string_push_map(timeline);
}
ht_timeline_destroy(timeline);
}
BENCHMARK(FeatureCachedStringAddPushMappingDifferentLabels);
static void FeatureCachedStringAddPushMappingTheSameLabel(benchmark::State& state)
{
HT_Timeline* timeline = ht_timeline_create(1024, HT_FALSE, HT_TRUE, NULL, NULL);
ht_feature_cached_string_enable(timeline, HT_FALSE);
for (auto _ : state)
{
ht_feature_cached_string_add_mapping(timeline, "label");
ht_feature_cached_string_push_map(timeline);
}
ht_timeline_destroy(timeline);
}
BENCHMARK(FeatureCachedStringAddPushMappingTheSameLabel);
static void FeatureCachedStringAddMappingDynamic(benchmark::State& state)
{
HT_Timeline* timeline = ht_timeline_create(1024, HT_FALSE, HT_TRUE, NULL, NULL);
ht_feature_cached_string_enable(timeline, HT_FALSE);
std::string s(1024*1024, 'a');
char char_ctr = 'a';
size_t pos_ctr = 0;
for (auto _ : state)
{
//s[pos_ctr] = char_ctr;
char_ctr++;
if (char_ctr == 'z'+1)
{
char_ctr = 'a';
pos_ctr++;
}
ht_feature_cached_string_add_mapping_dynamic(timeline, "lab");
}
ht_timeline_destroy(timeline);
}
BENCHMARK(FeatureCachedStringAddMappingDynamic);
| 29.225806 | 110 | 0.68074 | [
"vector"
] |
250c5378b2d19feb0cbff83dbf35774bdce933d7 | 632 | cc | C++ | yc252/1077.cc | c-yan/yukicoder | cdbbd65402177225dd989df7fe01f67908484a69 | [
"MIT"
] | null | null | null | yc252/1077.cc | c-yan/yukicoder | cdbbd65402177225dd989df7fe01f67908484a69 | [
"MIT"
] | null | null | null | yc252/1077.cc | c-yan/yukicoder | cdbbd65402177225dd989df7fe01f67908484a69 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <algorithm>
#define rep(i, a) for (int i = (int)0; i < (int)a; ++i)
template<class T> inline void chmin(T& a, T b) { if (a > b) { a = b; } }
using ll = long long;
using namespace std;
int main()
{
ll N;
scanf("%lld", &N);
vector<ll> Y(N), a(N);
rep(i, N) {
scanf("%lld", &Y[i]);
a[i] = Y[i];
}
sort(a.begin(), a.end());
a.erase(unique(a.begin(), a.end()), a.end());
vector<ll> dp(a.size(), 0);
rep(i, N){
ll t = 1LL << 60;
rep(j, a.size()){
chmin(t, dp[j] + abs(Y[i] - a[j]));
dp[j] = t;
}
}
printf("%lld\n", *min_element(dp.begin(), dp.end()));
return 0;
}
| 20.387097 | 72 | 0.52057 | [
"vector"
] |
251585a3936d7babc3479ab12d746d3a610f28b2 | 504 | cpp | C++ | leetcode/714. Best Time to Buy and Sell Stock with Transaction Fee.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | 1 | 2018-09-13T12:16:42.000Z | 2018-09-13T12:16:42.000Z | leetcode/714. Best Time to Buy and Sell Stock with Transaction Fee.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | null | null | null | leetcode/714. Best Time to Buy and Sell Stock with Transaction Fee.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | null | null | null | class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int n = prices.size();
if(n == 0) {
return 0;
}
int currBuy = -prices[0];
int currSell = 0;
for(int i = 2; i <= n; i++) {
int nextBuy = max(currSell - prices[i - 1], currBuy);
int nextSell = max(currBuy - fee + prices[i - 1], currSell);
currSell = nextSell;
currBuy = nextBuy;
}
return currSell;
}
};
| 26.526316 | 72 | 0.470238 | [
"vector"
] |
251b6b0f5d4e3b179f044abd07bc66b5126aa703 | 7,854 | cc | C++ | content/browser/indexed_db/indexed_db_database_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | content/browser/indexed_db/indexed_db_database_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/indexed_db/indexed_db_database_unittest.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/indexed_db/indexed_db_database.h"
#include <gtest/gtest.h>
#include "base/auto_reset.h"
#include "base/logging.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/in_process_webkit/indexed_db_database_callbacks.h"
#include "content/browser/indexed_db/indexed_db.h"
#include "content/browser/indexed_db/indexed_db_backing_store.h"
#include "content/browser/indexed_db/indexed_db_callbacks_wrapper.h"
#include "content/browser/indexed_db/indexed_db_cursor.h"
#include "content/browser/indexed_db/indexed_db_database.h"
#include "content/browser/indexed_db/indexed_db_factory.h"
#include "content/browser/indexed_db/indexed_db_fake_backing_store.h"
#include "content/browser/indexed_db/indexed_db_transaction.h"
#include "content/browser/indexed_db/webidbdatabase_impl.h"
using WebKit::WebIDBDatabaseError;
namespace content {
TEST(IndexedDBDatabaseTest, BackingStoreRetention) {
scoped_refptr<IndexedDBFakeBackingStore> backing_store =
new IndexedDBFakeBackingStore();
EXPECT_TRUE(backing_store->HasOneRef());
IndexedDBFactory* factory = 0;
scoped_refptr<IndexedDBDatabase> db =
IndexedDBDatabase::Create(ASCIIToUTF16("db"),
backing_store.get(),
factory,
ASCIIToUTF16("uniqueid"));
EXPECT_FALSE(backing_store->HasOneRef()); // local and db
db = NULL;
EXPECT_TRUE(backing_store->HasOneRef()); // local
}
class MockIDBCallbacks : public IndexedDBCallbacksWrapper {
public:
static scoped_refptr<MockIDBCallbacks> Create() {
return make_scoped_refptr(new MockIDBCallbacks());
}
virtual void OnError(const IndexedDBDatabaseError& error) OVERRIDE {}
virtual void OnSuccess(const std::vector<string16>& value) OVERRIDE {}
virtual void OnSuccess(scoped_refptr<IndexedDBCursor> cursor,
const IndexedDBKey& key,
const IndexedDBKey& primary_key,
std::vector<char>* value) OVERRIDE {}
virtual void OnSuccess(scoped_refptr<IndexedDBDatabase> db,
const IndexedDBDatabaseMetadata& metadata) OVERRIDE {
was_success_db_called_ = true;
}
virtual void OnSuccess(const IndexedDBKey& key) OVERRIDE {}
virtual void OnSuccess(std::vector<char>* value) OVERRIDE {}
virtual void OnSuccess(std::vector<char>* value,
const IndexedDBKey& key,
const IndexedDBKeyPath& key_path) OVERRIDE {}
virtual void OnSuccess(int64 value) OVERRIDE {}
virtual void OnSuccess() OVERRIDE {}
virtual void OnSuccess(const IndexedDBKey& key,
const IndexedDBKey& primary_key,
std::vector<char>* value) OVERRIDE {}
virtual void OnSuccessWithPrefetch(
const std::vector<IndexedDBKey>& keys,
const std::vector<IndexedDBKey>& primary_keys,
const std::vector<std::vector<char> >& values) OVERRIDE {}
private:
virtual ~MockIDBCallbacks() { EXPECT_TRUE(was_success_db_called_); }
MockIDBCallbacks()
: IndexedDBCallbacksWrapper(NULL), was_success_db_called_(false) {}
bool was_success_db_called_;
};
class FakeIDBDatabaseCallbacks : public IndexedDBDatabaseCallbacksWrapper {
public:
static scoped_refptr<FakeIDBDatabaseCallbacks> Create() {
return make_scoped_refptr(new FakeIDBDatabaseCallbacks());
}
virtual void OnVersionChange(int64 old_version, int64 new_version) OVERRIDE {}
virtual void OnForcedClose() OVERRIDE {}
virtual void OnAbort(int64 transaction_id,
const IndexedDBDatabaseError& error) OVERRIDE {}
virtual void OnComplete(int64 transaction_id) OVERRIDE {}
private:
friend class base::RefCounted<FakeIDBDatabaseCallbacks>;
virtual ~FakeIDBDatabaseCallbacks() {}
FakeIDBDatabaseCallbacks() : IndexedDBDatabaseCallbacksWrapper(NULL) {}
};
TEST(IndexedDBDatabaseTest, ConnectionLifecycle) {
scoped_refptr<IndexedDBFakeBackingStore> backing_store =
new IndexedDBFakeBackingStore();
EXPECT_TRUE(backing_store->HasOneRef()); // local
IndexedDBFactory* factory = 0;
scoped_refptr<IndexedDBDatabase> db =
IndexedDBDatabase::Create(ASCIIToUTF16("db"),
backing_store.get(),
factory,
ASCIIToUTF16("uniqueid"));
EXPECT_FALSE(backing_store->HasOneRef()); // local and db
scoped_refptr<MockIDBCallbacks> request1 = MockIDBCallbacks::Create();
scoped_refptr<FakeIDBDatabaseCallbacks> connection1 =
FakeIDBDatabaseCallbacks::Create();
const int64 transaction_id1 = 1;
db->OpenConnection(request1,
connection1,
transaction_id1,
IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION);
EXPECT_FALSE(backing_store->HasOneRef()); // db, connection count > 0
scoped_refptr<MockIDBCallbacks> request2 = MockIDBCallbacks::Create();
scoped_refptr<FakeIDBDatabaseCallbacks> connection2 =
FakeIDBDatabaseCallbacks::Create();
const int64 transaction_id2 = 2;
db->OpenConnection(request2,
connection2,
transaction_id2,
IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION);
EXPECT_FALSE(backing_store->HasOneRef()); // local and connection
db->Close(connection1);
EXPECT_FALSE(backing_store->HasOneRef()); // local and connection
db->Close(connection2);
EXPECT_TRUE(backing_store->HasOneRef());
EXPECT_FALSE(db->BackingStore().get());
db = NULL;
}
class MockIDBDatabaseCallbacks : public IndexedDBDatabaseCallbacksWrapper {
public:
static scoped_refptr<MockIDBDatabaseCallbacks> Create() {
return make_scoped_refptr(new MockIDBDatabaseCallbacks());
}
virtual void OnVersionChange(int64 old_version, int64 new_version) OVERRIDE {}
virtual void OnForcedClose() OVERRIDE {}
virtual void OnAbort(int64 transaction_id,
const IndexedDBDatabaseError& error) OVERRIDE {
was_abort_called_ = true;
}
virtual void OnComplete(int64 transaction_id) OVERRIDE {}
private:
MockIDBDatabaseCallbacks()
: IndexedDBDatabaseCallbacksWrapper(NULL), was_abort_called_(false) {}
virtual ~MockIDBDatabaseCallbacks() { EXPECT_TRUE(was_abort_called_); }
bool was_abort_called_;
};
TEST(IndexedDBDatabaseTest, ForcedClose) {
scoped_refptr<IndexedDBFakeBackingStore> backing_store =
new IndexedDBFakeBackingStore();
EXPECT_TRUE(backing_store->HasOneRef());
IndexedDBFactory* factory = 0;
scoped_refptr<IndexedDBDatabase> backend =
IndexedDBDatabase::Create(ASCIIToUTF16("db"),
backing_store.get(),
factory,
ASCIIToUTF16("uniqueid"));
EXPECT_FALSE(backing_store->HasOneRef()); // local and db
scoped_refptr<MockIDBDatabaseCallbacks> connection =
MockIDBDatabaseCallbacks::Create();
WebIDBDatabaseImpl web_database(backend, connection);
scoped_refptr<MockIDBCallbacks> request = MockIDBCallbacks::Create();
const int64 upgrade_transaction_id = 3;
backend->OpenConnection(request,
connection,
upgrade_transaction_id,
IndexedDBDatabaseMetadata::DEFAULT_INT_VERSION);
const int64 transaction_id = 123;
const std::vector<int64> scope;
web_database.createTransaction(
transaction_id, 0, scope, indexed_db::TRANSACTION_READ_ONLY);
web_database.forceClose();
EXPECT_TRUE(backing_store->HasOneRef()); // local
}
} // namespace content
| 39.074627 | 80 | 0.705118 | [
"vector"
] |
251e2ef4ad8ea329b7db34bfd8a4c55929518724 | 954 | cpp | C++ | boboleetcode/Play-Leetcode-master/0989-Add-to-Array-Form-of-Integer/cpp-0989/main2.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/0989-Add-to-Array-Form-of-Integer/cpp-0989/main2.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/0989-Add-to-Array-Form-of-Integer/cpp-0989/main2.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/add-to-array-form-of-integer/
/// Author : liuyubobobo
/// Time : 2019-02-13
#include <iostream>
#include <vector>
using namespace std;
/// Array and number addition
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
vector<int> addToArrayForm(vector<int>& A, int K) {
vector<int> res;
int carry = 0, i = A.size() - 1;
while(i >= 0 || K){
int t = K % 10 + carry;
K /= 10;
if(i >= 0) t += A[i];
res.push_back(t % 10);
carry = t / 10;
i --;
}
if(carry) res.push_back(1);
reverse(res.begin(), res.end());
return res;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec) cout << e;
cout << endl;
}
int main() {
vector<int> A1 = {0};
int K1 = 0;
print_vec(Solution().addToArrayForm(A1, K1));
return 0;
} | 18 | 72 | 0.513627 | [
"vector"
] |
251ea235d37cec19cc05da0fa078bbb377454cb3 | 3,245 | hpp | C++ | platooning_control/include/platoon_control_worker.hpp | harderthan/carma-platform | 29921896a761a866db9cfee473f02a481d8bb9c9 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | null | null | null | platooning_control/include/platoon_control_worker.hpp | harderthan/carma-platform | 29921896a761a866db9cfee473f02a481d8bb9c9 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | null | null | null | platooning_control/include/platoon_control_worker.hpp | harderthan/carma-platform | 29921896a761a866db9cfee473f02a481d8bb9c9 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | 1 | 2021-06-01T21:05:20.000Z | 2021-06-01T21:05:20.000Z | #pragma once
#include <ros/ros.h>
#include <cav_msgs/MobilityOperation.h>
#include <cav_msgs/MobilityRequest.h>
#include <cav_msgs/MobilityResponse.h>
#include <cav_msgs/PlanType.h>
#include "pid_controller.hpp"
#include "pure_pursuit.hpp"
#include <boost/optional.hpp>
namespace platoon_control
{
struct PlatoonLeaderInfo{
// Static ID is permanent ID for each vehicle
std::string staticId;
// Current BSM Id for each CAV
std::string bsmId;
// Vehicle real time command speed in m/s
double commandSpeed;
// Actual vehicle speed in m/s
double vehicleSpeed;
// Vehicle current down track distance on the current route in m
double vehiclePosition;
// The local time stamp when the host vehicle update any informations of this member
long timestamp;
// leader index in the platoon
int leaderIndex;
// Number of vehicles in front
int NumberOfVehicleInFront;
// PlatoonMember(std::string staticId, std::string bsmId, double commandSpeed, double vehicleSpeed, double vehiclePosition, long timestamp): staticId(staticId),
// bsmId(bsmId), commandSpeed(commandSpeed), vehicleSpeed(vehicleSpeed), timestamp(timestamp) {}
};
// Leader info: platoonmember + leader index + number of vehicles in front
class PlatoonControlWorker
{
public:
PlatoonControlWorker();
double getLastSpeedCommand() const;
// Update speed commands based on the list of platoon members
void generateSpeed(const cav_msgs::TrajectoryPlanPoint& point);
void generateSteer(const cav_msgs::TrajectoryPlanPoint& point);
// set platoon leader
void setLeader(const PlatoonLeaderInfo& leader);
void setCurrentSpeed(double speed);
double speedCmd;
double currentSpeed;
double adjustmentCap = 10.0;
double lastCmdSpeed = 0.0;
double speedCmd_ = 0;
double steerCmd_ = 0;
PlatoonLeaderInfo platoon_leader;
// platooning_desired_time_headway"
double timeHeadway = 2.0;
// platooning standstillheadway"
double standStillHeadway = 12.0;
void setCurrentPose(const geometry_msgs::PoseStampedConstPtr& msg)
{
current_pose = msg->pose;
}
// geometry pose
geometry_msgs::Pose current_pose;
private:
// pid controller object
PIDController pid_ctrl_;
// pure pursuit controller object
PurePursuit pp_;
double maxAccel = 2.5; // m/s/s
double desiredTimeGap = 1.0; // s
double desiredGap_ = 0.0;
long CMD_TIMESTEP = 100;
double getCurrentDowntrackDistance(const cav_msgs::TrajectoryPlanPoint& point);
double dist_to_front_vehicle;
bool enableMaxAdjustmentFilter = leaderSpeedCapEnabled;
bool leaderSpeedCapEnabled = true;
bool enableLocalSpeedLimitFilter = speedLimitCapEnabled;
bool speedLimitCapEnabled = true;
bool enableMaxAccelFilter = maxAccelCapEnabled;
bool maxAccelCapEnabled = true;
};
} | 25.351563 | 172 | 0.651156 | [
"geometry",
"object"
] |
2520cb84064afc1022be8f1414cd751d79a0b2ca | 1,889 | cpp | C++ | Codeforces/1491/e.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | 14 | 2019-08-14T00:43:10.000Z | 2021-12-16T05:43:31.000Z | Codeforces/1491/e.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | null | null | null | Codeforces/1491/e.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | 6 | 2020-12-30T03:30:17.000Z | 2022-03-11T03:40:02.000Z | #include <bits/stdc++.h>
#define endl "\n"
#define moo cout
using namespace std;
int N, c[200000], fib[30], rfib[1000000];
vector<int> graph[200000];
bool no[200000];
int dfs(int id, int par){
if(no[id]) return 0;
c[id] = 1;
for(int i : graph[id]){
if(i != par){
c[id] += dfs(i, id);
}
}
return c[id];
}
void dfs2(int id, int par, vector<int> &v){
if(no[id]) return;
v.push_back(id);
for(int i : graph[id]){
if(i != par){
dfs2(i, id, v);
}
}
}
bool fibt(vector<int> &cur){
if((int)cur.size() < 4) return true;
int cfib = rfib[cur.size()];
bool ret = false;
dfs(cur[0], -1);
for(int i : cur){
for(int j : graph[i]){
if(c[i] < c[j] || no[j]) continue;
if(c[j] == fib[cfib-1] || c[j] == fib[cfib-2]){
vector<int> nxt1, nxt2;
dfs2(j, i, nxt1);
for(int k : nxt1) no[k] = true;
for(int k : cur){
if(!no[k]) nxt2.push_back(k);
}
int ok = true;
ok &= fibt(nxt2);
for(int k : nxt1) no[k] = false;
for(int k : nxt2) no[k] = true;
ok &= fibt(nxt1);
for(int k : nxt2) no[k] = false;
ret |= ok;
goto found;
}
}
}
found:
return ret;
}
int32_t main(){
cin.tie(0) -> sync_with_stdio(0);
cin >> N;
for(int i = 0; i < N-1; i++){
int u, v; cin >> u >> v;
graph[u-1].push_back(v-1);
graph[v-1].push_back(u-1);
}
fib[0] = fib[1] = 1;
for(int i = 2; i < 30; i++){
fib[i] = fib[i-1] + fib[i-2];
rfib[fib[i]] = i;
}
vector<int> cur;
for(int i = 0; i < N; i++) cur.push_back(i);
moo << (fibt(cur) ? "yES" : "nO") << endl;
}
| 23.911392 | 59 | 0.420328 | [
"vector"
] |
252dac00c10697d7343c8650316645a3a541c63f | 4,139 | cpp | C++ | Emscripten/ParticleSystem/Vector.cpp | leefsmp/Particle-System | 810482f9bdfda25c5a7761de3946892ebd76f8de | [
"MIT"
] | 38 | 2016-08-02T14:23:05.000Z | 2021-12-02T12:43:11.000Z | Emscripten/ParticleSystem/Vector.cpp | leefsmp/Particle-System | 810482f9bdfda25c5a7761de3946892ebd76f8de | [
"MIT"
] | 2 | 2016-09-29T12:33:23.000Z | 2018-03-02T17:59:03.000Z | Emscripten/ParticleSystem/Vector.cpp | leefsmp/Particle-System | 810482f9bdfda25c5a7761de3946892ebd76f8de | [
"MIT"
] | 5 | 2016-09-29T12:26:15.000Z | 2018-10-23T09:07:27.000Z | #include "Vector.h"
#include <math.h>
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector::Vector() {
this->x = 0;
this->y = 0;
this->z = 0;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector::Vector(const Vector& v) {
this->x = v.x;
this->y = v.y;
this->z = v.z;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector::Vector(const double x, const double y, const double z) {
this->x = x;
this->y = y;
this->z = z;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
void Vector::set(const double x, const double y, const double z) {
this->x = x;
this->y = y;
this->z = z;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
void Vector::set(const Vector& v) {
this->set(v.x, v.y, v.z);
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
double Vector::getX() const {
return x;
}
double Vector::getY() const {
return y;
}
double Vector::getZ() const {
return z;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
double Vector::magnitude() const {
return sqrt(x * x + y * y + z * z);
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector Vector::asUnitVector () const {
double m = this->magnitude();
Vector v(x/m, y/m, z/m);
return v;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector Vector::scaled(const double scaleFactor) const {
double m = this->magnitude();
Vector v(
x * scaleFactor / m,
y * scaleFactor / m,
z * scaleFactor / m);
return v;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector Vector::multiply(const double scaleFactor) const {
Vector res(
x * scaleFactor,
y * scaleFactor,
z * scaleFactor);
return res;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector Vector::add(const Vector& v) const {
Vector res(x + v.x, y + v.y, z + v.z);
return res;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector Vector::vectorTo(const Vector& v) const {
Vector res(v.x - x, v.y - y, v.z - z);
return res;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
bool Vector::withinSphere (
const Vector* center, const double radius) const {
double magnitudeSqr =
(x - center->x) * (x - center->x) +
(y - center->y) * (y - center->y) +
(z - center->z) * (z - center->z);
return magnitudeSqr < radius * radius;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector Vector::copy() const {
Vector v(x, y, z);
return v;
}
///////////////////////////////////////////////////////////////////
//
//
///////////////////////////////////////////////////////////////////
Vector Vector::fromArray(const double* data) {
Vector v(data[0], data[1], data[2]);
return v;
}
| 22.252688 | 68 | 0.258275 | [
"vector"
] |
25311bfd0f416bcfd946d2eb2418c9db20240e27 | 83,144 | cxx | C++ | inetsrv/query/apps/ci/ci.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/query/apps/ci/ci.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/query/apps/ci/ci.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation, 1997 - 2001. All Rights Reserved.
//
// PROGRAM: ci.cxx
//
// PURPOSE: Illustrates a minimal query using Indexing Service.
// Uses CIMakeICommand and CITextToFullTree helper functions.
//
// PLATFORM: Windows 2000
//
//--------------------------------------------------------------------------
#define UNICODE
#define DBINITCONSTANTS
#include <stdio.h>
#include <wchar.h>
#include <windows.h>
#include <oledberr.h>
#include <oledb.h>
#include <cmdtree.h>
#include <ntquery.h>
#include <mlang.h>
#include <ciodm.h>
#include "ci.hxx"
// This is found in disptree.cxx
extern void DisplayCommandTree( DBCOMMANDTREE * pNode, ULONG iLevel = 0 );
// These are found in isrch.cxx
extern HRESULT DoISearch( WCHAR const * pwcRestriction,
WCHAR const * pwcFilename,
BOOL fPrintFile,
BOOL fDefineCPP,
LCID lcid,
ULONG ulDialect );
extern HINSTANCE PrepareForISearch();
extern void DoneWithISearch( HINSTANCE h );
const ULONG MAX_CATALOGS = 8;
//
// These properties (func and class) are emitted by the C++ filter (cxxflt.dll)
//
CIPROPERTYDEF aCPPProperties[] =
{
{
L"FUNC",
DBTYPE_WSTR | DBTYPE_BYREF,
{
{ 0x8dee0300, 0x16c2, 0x101b, 0xb1, 0x21, 0x08, 0x00, 0x2b, 0x2e, 0xcd, 0xa9 },
DBKIND_GUID_NAME,
L"func"
}
},
{
L"CLASS",
DBTYPE_WSTR | DBTYPE_BYREF,
{
{ 0x8dee0300, 0x16c2, 0x101b, 0xb1, 0x21, 0x08, 0x00, 0x2b, 0x2e, 0xcd, 0xa9 },
DBKIND_GUID_NAME,
L"class"
}
}
};
unsigned cCPPProperties = sizeof aCPPProperties /
sizeof aCPPProperties[0];
//+---------------------------------------------------------------------------
//
// Class: XBStr
//
// Purpose: Smart BSTR class
//
//----------------------------------------------------------------------------
class XBStr
{
public:
XBStr(BSTR p = 0) : _p( p ) {}
XBStr ( XBStr & x ): _p( x.Acquire() ) {}
~XBStr() { SysFreeString( _p ); }
BOOL IsNull() const { return ( 0 == _p ); }
void Set ( BSTR pOleStr ) { _p = pOleStr; }
BSTR Acquire()
{
BSTR pTemp = _p;
_p = 0;
return pTemp;
}
BSTR GetPointer() const { return _p; }
void Free() { SysFreeString( Acquire() ); }
private:
BSTR _p;
};
//+-------------------------------------------------------------------------
//
// Template: XInterface
//
// Synopsis: Template for managing ownership of interfaces
//
//--------------------------------------------------------------------------
template<class T> class XInterface
{
public:
XInterface( T * p = 0 ) : _p( p ) {}
~XInterface() { if ( 0 != _p ) _p->Release(); }
T * operator->() { return _p; }
T * GetPointer() const { return _p; }
IUnknown ** GetIUPointer() { return (IUnknown **) &_p; }
T ** GetPPointer() { return &_p; }
void ** GetQIPointer() { return (void **) &_p; }
T * Acquire() { T * p = _p; _p = 0; return p; }
BOOL IsNull() { return ( 0 == _p ); }
private:
T * _p;
};
//+-------------------------------------------------------------------------
//
// Template: XPtr
//
// Synopsis: Template for managing ownership of memory
//
//--------------------------------------------------------------------------
template<class T> class XPtr
{
public:
XPtr( unsigned c ) : _p(0) { if ( 0 != c ) _p = new T [ c ]; }
~XPtr() { Free(); }
void SetSize( unsigned c ) { Free(); _p = new T [ c ]; }
void Set ( T * p ) { _p = p; }
T * Get() const { return _p ; }
void Free() { delete [] Acquire(); }
T & operator[]( unsigned i ) { return _p[i]; }
T const & operator[]( unsigned i ) const { return _p[i]; }
T * Acquire() { T * p = _p; _p = 0; return p; }
BOOL IsNull() const { return ( 0 == _p ); }
private:
T * _p;
};
//+-------------------------------------------------------------------------
//
// Template: CResString
//
// Synopsis: Class for loading string resources
//
//--------------------------------------------------------------------------
class CResString
{
public:
CResString() { _awc[ 0 ] = 0; }
CResString( UINT strIDS ) { Load( strIDS ); }
WCHAR const * Get() const { return _awc; }
BOOL Load( UINT strIDS )
{
_awc[ 0 ] = 0;
LoadString( 0, strIDS, _awc, sizeof _awc / sizeof WCHAR );
return ( 0 != _awc[ 0 ] );
}
private:
WCHAR _awc[ 200 ];
};
//+-------------------------------------------------------------------------
//
// Function: FormatError
//
// Synopsis: Formats an error code into a string
//
// Arguments: [sc] - An Indexing Service or Win32 HRESULT
// [pwc] - Where to write the error string
// [cwc] - Count of characters in pwc
// [lcid] - Locale for the error string
//
//--------------------------------------------------------------------------
void FormatError(
SCODE sc,
WCHAR * pwc,
ULONG cwc,
LCID lcid )
{
// FormatMessage works best when based on thread locale.
LCID SaveLCID = GetThreadLocale();
BOOL fLocaleSet = SetThreadLocale( lcid );
// Is this an Indexing Service error? These errors are in query.dll.
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle( L"query.dll" ),
sc,
0,
pwc,
cwc,
0 ) )
{
// Is this a Win32 error? These are in kernel32.dll
const ULONG facWin32 = ( FACILITY_WIN32 << 16 );
ULONG Win32Error = sc;
if ( (Win32Error & facWin32) == facWin32 )
Win32Error &= ~( 0x80000000 | facWin32 );
if ( ! FormatMessage( FORMAT_MESSAGE_FROM_HMODULE,
GetModuleHandle( L"kernel32.dll" ),
Win32Error,
0,
pwc,
cwc,
0 ) )
{
// It's not from Indexing Service or Win32; display a default error
CResString str( IDS_UNKNOWNERROR );
wcscpy( pwc, str.Get() );
}
}
// Restore the original thread locale
if ( fLocaleSet )
SetThreadLocale( SaveLCID );
} //FormatError
//+-------------------------------------------------------------------------
//
// Function: DisplayError
//
// Synopsis: Prints an error message from a string resource
//
// Arguments: [uiError] - The error message resource id
// [pwcArgument] - A string argument for the error message
// [hr] - The error code
// [lcid] - Locale for the error string
//
//--------------------------------------------------------------------------
HRESULT DisplayError(
UINT uiError,
WCHAR const * pwcArgument,
HRESULT hr,
LCID lcid )
{
WCHAR awcError[ 200 ];
FormatError( hr, awcError, sizeof awcError / sizeof WCHAR, lcid );
CResString str( uiError );
wprintf( str.Get(), pwcArgument, hr, awcError );
return hr;
} //DisplayError
//+-------------------------------------------------------------------------
//
// Function: DisplayWin32Error
//
// Synopsis: Prints an error message taken from GetLastError()
//
// Arguments: [uiError] - The string resource to use for the error
// [pwcArgument] - A string argument for the error message
// [lcid] - Locale for the error string
//
//--------------------------------------------------------------------------
HRESULT DisplayWin32Error(
UINT uiError,
WCHAR const * pwcArgument,
LCID lcid )
{
HRESULT hr = HRESULT_FROM_WIN32( GetLastError() );
DisplayError( uiError, pwcArgument, hr, lcid );
return hr;
} //DisplayWin32Error
void DisplayStat( DWORD dw, UINT uiMsg )
{
CResString str( uiMsg );
wprintf( L"%8d %ws\n", dw, str.Get() );
} //DisplayStat
void DisplayStat( WCHAR const *pwcMsg, UINT uiMsg )
{
CResString str( uiMsg );
wprintf( L"%ws: %ws\n", str.Get(), pwcMsg );
} //DisplayStat
void DisplayStat( UINT uiMsg )
{
CResString str( uiMsg );
wprintf( L"%ws\n", str.Get() );
} //DisplayStat
//+-------------------------------------------------------------------------
//
// Function: Usage
//
// Synopsis: Displays information about how to use the app and exits
//
//--------------------------------------------------------------------------
void Usage()
{
HRSRC hrc = FindResource( 0, (LPCWSTR) IDR_USAGE, RT_RCDATA );
if ( 0 != hrc )
{
HGLOBAL hg = LoadResource( 0, hrc );
if ( 0 != hg )
{
void * pv = LockResource( hg );
if ( 0 != pv )
wprintf( L"%ws\n", pv );
}
}
exit( -1 );
} //Usage
//+-------------------------------------------------------------------------
//
// Function: LocaleToCodepage
//
// Synopsis: Finds the best matching codepage given a locale id.
//
// Arguments: [lcid] - Locale to check
//
// Returns: The best matching codepage.
//
//--------------------------------------------------------------------------
ULONG LocaleToCodepage( LCID lcid )
{
ULONG codepage;
int cwc = GetLocaleInfo( lcid,
LOCALE_RETURN_NUMBER |
LOCALE_IDEFAULTANSICODEPAGE,
(WCHAR *) &codepage,
sizeof ULONG / sizeof WCHAR );
// If an error occurred, return the Ansi code page
if ( 0 == cwc )
return CP_ACP;
return codepage;
} //LocaleToCodepage
//+-------------------------------------------------------------------------
//
// Function: GetLocaleString
//
// Synopsis: Looks up a locale string given an LCID
//
// Arguments: [lcid] - The lcid to look up
//
// Returns: The matching string (in a static buffer, caller beware).
//
//--------------------------------------------------------------------------
WCHAR const * GetLocaleString( LCID lcid )
{
static WCHAR awcLocale[ 100 ];
wcscpy( awcLocale, L"Neutral" );
XInterface<IMultiLanguage> xMultiLang;
HRESULT hr = CoCreateInstance( CLSID_CMultiLanguage,
0,
CLSCTX_INPROC_SERVER,
IID_IMultiLanguage,
xMultiLang.GetQIPointer() );
if ( SUCCEEDED( hr ) )
{
BSTR bstrLocale;
hr = xMultiLang->GetRfc1766FromLcid( lcid, &bstrLocale );
if ( SUCCEEDED( hr ) )
{
wcscpy( awcLocale, bstrLocale );
SysFreeString( bstrLocale );
}
}
return awcLocale;
} //GetLocaleString
//+-------------------------------------------------------------------------
//
// Function: LcidFromHttpAcceptLanguage
//
// Synopsis: Looks up an LCID given an HTTP Accept Language string
//
// Arguments: [pwc] - The string to look up
//
// Returns: The matching LCID.
//
//--------------------------------------------------------------------------
LCID LcidFromHttpAcceptLanguage( WCHAR const * pwc )
{
// Default to the system locale
LCID lcid = GetSystemDefaultLCID();
if ( 0 != pwc )
{
// Check for an integer constant in hex or decimal, then try as a
// string.
if ( ( L'0' == pwc[0] ) &&
( L'X' == towupper( pwc[1] ) ) )
{
int x = wcslen( pwc );
WCHAR *pwcEnd;
return wcstoul( pwc, &pwcEnd, 16 );
}
else
{
BOOL fInteger = TRUE;
for ( WCHAR const * p = pwc; ( 0 != *p ); p++ )
{
if ( !iswdigit( *p ) )
{
fInteger = FALSE;
break;
}
}
if ( fInteger )
return _wtol( pwc );
}
XInterface<IMultiLanguage> xMultiLang;
HRESULT hr = CoCreateInstance( CLSID_CMultiLanguage,
0,
CLSCTX_INPROC_SERVER,
IID_IMultiLanguage,
xMultiLang.GetQIPointer() );
if ( SUCCEEDED( hr ) )
{
BSTR bstr = SysAllocString( pwc );
if ( 0 != bstr )
{
hr = xMultiLang->GetLcidFromRfc1766( &lcid, bstr );
SysFreeString( bstr );
if ( S_FALSE == hr ||
E_FAIL == hr )
{
if ( !_wcsicmp( pwc, L"neutral" ) ||
!_wcsicmp( pwc, L"neutr" ) )
lcid = 0;
else
Usage();
}
else if ( FAILED( hr ) )
{
Usage();
}
}
}
}
return lcid;
} //LcidFromHttpAcceptLanguage
//+-------------------------------------------------------------------------
//
// Function: SetCommandProperties
//
// Synopsis: Sets the DBPROP_USEEXTENDEDDBTYPES property to TRUE, so
// data is returned in PROPVARIANTs, as opposed to the
// default, which is OLE automation VARIANTs. PROPVARIANTS
// allow a superset of VARIANT data types. Use of these
// types avoids costly coercions.
//
// Also sets the DBPROP_USECONTENTINDEX property to TRUE, so
// the index will always be used to resolve the query (as
// opposed to enumerating all the files on the disk), even
// if the index is out of date. This is set optionally.
//
// Both of these properties are unique to Indexing Service's
// OLE DB implementation.
//
// Arguments: [pICommand] - The ICommand used to set the property
// [fForceUseContentIndex] - TRUE to always use index
// FALSE to allow directory enumeration
// [lcid] - The locale of the query
// [cMaxHits] - The maximum number of rows to return, 0 for all.
// [fFirstHits] - TRUE for first N hits, FALSE for best N hits.
//
// Returns: HRESULT result of setting the properties
//
//--------------------------------------------------------------------------
HRESULT SetCommandProperties(
ICommand * pICommand,
BOOL fForceUseContentIndex,
LCID lcid,
ULONG cMaxHits,
BOOL fFirstHits )
{
static const DBID dbcolNull = { { 0,0,0, { 0,0,0,0,0,0,0,0 } },
DBKIND_GUID_PROPID, 0 };
static const GUID guidQueryExt = DBPROPSET_QUERYEXT;
DBPROP aProp[2];
// Use extened types in accessor bindings -- it's faster and more accurate
aProp[0].dwPropertyID = DBPROP_USEEXTENDEDDBTYPES;
aProp[0].dwOptions = DBPROPOPTIONS_OPTIONAL;
aProp[0].dwStatus = 0;
aProp[0].colid = dbcolNull;
aProp[0].vValue.vt = VT_BOOL;
aProp[0].vValue.boolVal = VARIANT_TRUE;
// Should we force use of the index? Otherwise, enumeration will be slow.
aProp[1] = aProp[0];
aProp[1].dwPropertyID = DBPROP_USECONTENTINDEX;
aProp[1].vValue.boolVal = fForceUseContentIndex ? VARIANT_TRUE : VARIANT_FALSE;
DBPROPSET aPropSet[3];
aPropSet[0].rgProperties = &aProp[0];
aPropSet[0].cProperties = 2;
aPropSet[0].guidPropertySet = guidQueryExt;
const GUID guidMSIDXS_ROWSETEXT = DBPROPSET_MSIDXS_ROWSETEXT;
DBPROP aRowsetExtProp[1];
aPropSet[1].rgProperties = &aRowsetExtProp[0];
aPropSet[1].cProperties = 1;
aPropSet[1].guidPropertySet = guidMSIDXS_ROWSETEXT;
// Set the default locale of the query
aRowsetExtProp[0] = aProp[0];
aRowsetExtProp[0].dwPropertyID = MSIDXSPROP_COMMAND_LOCALE_STRING;
aRowsetExtProp[0].vValue.vt = VT_BSTR;
aRowsetExtProp[0].vValue.bstrVal = SysAllocString( GetLocaleString( lcid ) );
if ( 0 == aRowsetExtProp[0].vValue.bstrVal )
return E_OUTOFMEMORY;
DBPROP aRowsetProp[1];
aPropSet[2].rgProperties = &aRowsetProp[0];
aPropSet[2].cProperties = 1;
aPropSet[2].guidPropertySet = DBPROPSET_ROWSET;
// Set the first or best maximum number of result rows
aRowsetProp[0] = aProp[0];
aRowsetProp[0].dwPropertyID = fFirstHits ? DBPROP_FIRSTROWS : DBPROP_MAXROWS;
aRowsetProp[0].vValue.vt = VT_I4;
aRowsetProp[0].vValue.lVal = (LONG) cMaxHits;
XInterface<ICommandProperties> xICommandProperties;
HRESULT hr = pICommand->QueryInterface( IID_ICommandProperties,
xICommandProperties.GetQIPointer() );
if ( SUCCEEDED( hr ) )
{
hr = xICommandProperties->SetProperties( 3,
aPropSet ); // the properties
}
// Free the locale string
HRESULT hr2 = VariantClear( &aRowsetExtProp[0].vValue );
if ( SUCCEEDED( hr ) && FAILED( hr2 ) )
hr = hr2;
return hr;
} //SetCommandProperties
//+-------------------------------------------------------------------------
//
// Function: Render
//
// Synopsis: Prints an item in a safearray
//
// Arguments: [vt] - type of the element
// [pa] - pointer to the item
//
//--------------------------------------------------------------------------
void PrintSafeArray( VARTYPE vt, LPSAFEARRAY pa );
void Render( VARTYPE vt, void * pv )
{
if ( VT_ARRAY & vt )
{
PrintSafeArray( vt - VT_ARRAY, *(SAFEARRAY **) pv );
return;
}
switch ( vt )
{
case VT_UI1: wprintf( L"%u", (unsigned) *(BYTE *)pv ); break;
case VT_I1: wprintf( L"%d", (int) *(CHAR *)pv ); break;
case VT_UI2: wprintf( L"%u", (unsigned) *(USHORT *)pv ); break;
case VT_I2: wprintf( L"%d", (int) *(SHORT *)pv ); break;
case VT_UI4:
case VT_UINT: wprintf( L"%u", (unsigned) *(ULONG *)pv ); break;
case VT_I4:
case VT_ERROR:
case VT_INT: wprintf( L"%d", *(LONG *)pv ); break;
case VT_UI8: wprintf( L"%I64u", *(unsigned __int64 *)pv ); break;
case VT_I8: wprintf( L"%I64d", *(__int64 *)pv ); break;
case VT_R4: wprintf( L"%f", *(float *)pv ); break;
case VT_R8: wprintf( L"%lf", *(double *)pv ); break;
case VT_DECIMAL:
{
double dbl;
HRESULT hr = VarR8FromDec( (DECIMAL *) pv, &dbl );
if ( SUCCEEDED( hr ) )
wprintf( L"%lf", dbl );
break;
}
case VT_CY:
{
double dbl;
HRESULT hr = VarR8FromCy( * (CY *) pv, &dbl );
if ( SUCCEEDED( hr ) )
wprintf( L"%lf", dbl );
break;
}
case VT_BOOL: wprintf( *(VARIANT_BOOL *)pv ? L"TRUE" : L"FALSE" ); break;
case VT_BSTR: wprintf( L"%ws", *(BSTR *) pv ); break;
case VT_VARIANT:
{
PROPVARIANT * pVar = (PROPVARIANT *) pv;
Render( pVar->vt, & pVar->lVal );
break;
}
case VT_DATE:
{
SYSTEMTIME st;
BOOL fOK = VariantTimeToSystemTime( *(DATE *)pv, &st );
if ( !fOK )
break;
BOOL pm = st.wHour >= 12;
if ( st.wHour > 12 )
st.wHour -= 12;
else if ( 0 == st.wHour )
st.wHour = 12;
wprintf( L"%2d-%02d-%04d %2d:%02d%wc",
(DWORD) st.wMonth,
(DWORD) st.wDay,
(DWORD) st.wYear,
(DWORD) st.wHour,
(DWORD) st.wMinute,
pm ? L'p' : L'a' );
break;
}
case VT_EMPTY:
case VT_NULL:
break;
default :
{
wprintf( L"(vt 0x%x)", (int) vt );
break;
}
}
} //Render
//+-------------------------------------------------------------------------
//
// Function: PrintSafeArray
//
// Synopsis: Prints items in a safearray
//
// Arguments: [vt] - type of elements in the safearray
// [pa] - pointer to the safearray
//
//--------------------------------------------------------------------------
void PrintSafeArray( VARTYPE vt, LPSAFEARRAY pa )
{
// Get the dimensions of the array
UINT cDim = SafeArrayGetDim( pa );
if ( 0 == cDim )
return;
XPtr<LONG> xDim( cDim );
XPtr<LONG> xLo( cDim );
XPtr<LONG> xUp( cDim );
for ( UINT iDim = 0; iDim < cDim; iDim++ )
{
HRESULT hr = SafeArrayGetLBound( pa, iDim + 1, &xLo[iDim] );
if ( FAILED( hr ) )
return;
xDim[ iDim ] = xLo[ iDim ];
hr = SafeArrayGetUBound( pa, iDim + 1, &xUp[iDim] );
if ( FAILED( hr ) )
return;
wprintf( L"{" );
}
// slog through the array
UINT iLastDim = cDim - 1;
BOOL fDone = FALSE;
while ( !fDone )
{
// inter-element formatting
if ( xDim[ iLastDim ] != xLo[ iLastDim ] )
wprintf( L"," );
// Get the element and render it
void *pv;
HRESULT hr = SafeArrayPtrOfIndex( pa, xDim.Get(), &pv );
if ( FAILED( hr ) )
return;
Render( vt, pv );
// Move to the next element and carry if necessary
ULONG cOpen = 0;
for ( LONG iDim = iLastDim; iDim >= 0; iDim-- )
{
if ( xDim[ iDim ] < xUp[ iDim ] )
{
xDim[ iDim ] = 1 + xDim[ iDim ];
break;
}
wprintf( L"}" );
if ( 0 == iDim )
fDone = TRUE;
else
{
cOpen++;
xDim[ iDim ] = xLo[ iDim ];
}
}
for ( ULONG i = 0; !fDone && i < cOpen; i++ )
wprintf( L"{" );
}
} //PrintSafeArray
//+-------------------------------------------------------------------------
//
// Function: PrintVectorItems
//
// Synopsis: Prints items in a PROPVARIANT vector
//
// Arguments: [pVal] - The array of values
// [cVals] - The count of values
// [pcFmt] - The format string
//
//--------------------------------------------------------------------------
template<class T> void PrintVectorItems(
T * pVal,
ULONG cVals,
char * pcFmt )
{
printf( "{ " );
for( ULONG iVal = 0; iVal < cVals; iVal++ )
{
if ( 0 != iVal )
printf( "," );
printf( pcFmt, *pVal++ );
}
printf( " }" );
} //PrintVectorItems
//+-------------------------------------------------------------------------
//
// Function: DisplayValue
//
// Synopsis: Displays a PROPVARIANT value. Limited formatting is done.
//
// Arguments: [pVar] - The value to display
//
//--------------------------------------------------------------------------
void DisplayValue( PROPVARIANT const * pVar )
{
if ( 0 == pVar )
{
wprintf( L"NULL" );
return;
}
// Display the most typical variant types
PROPVARIANT const & v = *pVar;
switch ( v.vt )
{
case VT_EMPTY : break;
case VT_NULL : break;
case VT_I4 : wprintf( L"%10d", v.lVal ); break;
case VT_UI1 : wprintf( L"%10d", v.bVal ); break;
case VT_I2 : wprintf( L"%10d", v.iVal ); break;
case VT_R4 : wprintf( L"%10f", v.fltVal ); break;
case VT_R8 : wprintf( L"%10lf", v.dblVal ); break;
case VT_BOOL : wprintf( v.boolVal ? L"TRUE" : L"FALSE" ); break;
case VT_I1 : wprintf( L"%10d", v.cVal ); break;
case VT_UI2 : wprintf( L"%10u", v.uiVal ); break;
case VT_UI4 : wprintf( L"%10u", v.ulVal ); break;
case VT_INT : wprintf( L"%10d", v.lVal ); break;
case VT_UINT : wprintf( L"%10u", v.ulVal ); break;
case VT_I8 : wprintf( L"%20I64d", v.hVal ); break;
case VT_UI8 : wprintf( L"%20I64u", v.hVal ); break;
case VT_ERROR : wprintf( L"%#x", v.scode ); break;
case VT_LPSTR : wprintf( L"%S", v.pszVal ); break;
case VT_LPWSTR : wprintf( L"%ws", v.pwszVal ); break;
case VT_BSTR : wprintf( L"%ws", v.bstrVal ); break;
case VT_CY:
{
double dbl;
HRESULT hr = VarR8FromCy( v.cyVal, &dbl );
if ( SUCCEEDED( hr ) )
wprintf( L"%lf", dbl );
break;
}
case VT_DECIMAL :
{
double dbl;
HRESULT hr = VarR8FromDec( (DECIMAL *) &v.decVal, &dbl );
if ( SUCCEEDED( hr ) )
wprintf( L"%lf", dbl );
break;
}
case VT_FILETIME :
case VT_DATE :
{
SYSTEMTIME st;
if ( VT_DATE == v.vt )
{
BOOL fOK = VariantTimeToSystemTime( v.date, &st );
if ( !fOK )
break;
}
else
{
FILETIME ft;
BOOL fOK = FileTimeToLocalFileTime( &v.filetime, &ft );
if ( fOK )
fOK = FileTimeToSystemTime( &ft, &st );
if ( !fOK )
break;
}
BOOL pm = st.wHour >= 12;
if ( st.wHour > 12 )
st.wHour -= 12;
else if ( 0 == st.wHour )
st.wHour = 12;
wprintf( L"%2d-%02d-%04d %2d:%02d%wc",
(DWORD) st.wMonth,
(DWORD) st.wDay,
(DWORD) st.wYear,
(DWORD) st.wHour,
(DWORD) st.wMinute,
pm ? L'p' : L'a' );
break;
}
case VT_VECTOR | VT_I1:
PrintVectorItems( v.cac.pElems, v.cac.cElems, "%d" ); break;
case VT_VECTOR | VT_I2:
PrintVectorItems( v.cai.pElems, v.cai.cElems, "%d" ); break;
case VT_VECTOR | VT_I4:
PrintVectorItems( v.cal.pElems, v.cal.cElems, "%d" ); break;
case VT_VECTOR | VT_I8:
PrintVectorItems( v.cah.pElems, v.cah.cElems, "%I64d" ); break;
case VT_VECTOR | VT_UI1:
PrintVectorItems( v.caub.pElems, v.caub.cElems, "%u" ); break;
case VT_VECTOR | VT_UI2:
PrintVectorItems( v.caui.pElems, v.caui.cElems, "%u" ); break;
case VT_VECTOR | VT_UI4:
PrintVectorItems( v.caul.pElems, v.caul.cElems, "%u" ); break;
case VT_VECTOR | VT_ERROR:
PrintVectorItems( v.cascode.pElems, v.cascode.cElems, "%#x" ); break;
case VT_VECTOR | VT_UI8:
PrintVectorItems( v.cauh.pElems, v.cauh.cElems, "%I64u" ); break;
case VT_VECTOR | VT_BSTR:
PrintVectorItems( v.cabstr.pElems, v.cabstr.cElems, "%ws" ); break;
case VT_VECTOR | VT_LPSTR:
PrintVectorItems( v.calpstr.pElems, v.calpstr.cElems, "%S" ); break;
case VT_VECTOR | VT_LPWSTR:
PrintVectorItems( v.calpwstr.pElems, v.calpwstr.cElems, "%ws" ); break;
case VT_VECTOR | VT_R4:
PrintVectorItems( v.caflt.pElems, v.caflt.cElems, "%f" ); break;
case VT_VECTOR | VT_R8:
PrintVectorItems( v.cadbl.pElems, v.cadbl.cElems, "%lf" ); break;
default :
{
if ( VT_ARRAY & v.vt )
PrintSafeArray( v.vt - VT_ARRAY, v.parray );
else
wprintf( L"vt 0x%05x", v.vt );
break;
}
}
} //DisplayValue
//-----------------------------------------------------------------------------
//
// Function: GetOleDBErrorInfo
//
// Synopsis: Retrieves the secondary error from the OLE DB error object.
//
// Arguments: [pErrSrc] - Pointer to object that posted the error.
// [riid] - Interface that posted the error.
// [lcid] - Locale in which the text is desired.
// [pErrorInfo] - Pointer to memory where ERRORINFO should be.
// [ppIErrorInfo] - Holds the returning IErrorInfo. Caller
// should release this.
//
// Returns: HRESULT for whether the error info was retrieved
//
//-----------------------------------------------------------------------------
HRESULT GetOleDBErrorInfo(
IUnknown * pErrSrc,
REFIID riid,
LCID lcid,
ERRORINFO * pErrorInfo,
IErrorInfo ** ppIErrorInfo )
{
*ppIErrorInfo = 0;
// See if an error is available that is of interest to us.
XInterface<ISupportErrorInfo> xSupportErrorInfo;
HRESULT hr = pErrSrc->QueryInterface( IID_ISupportErrorInfo,
xSupportErrorInfo.GetQIPointer() );
if ( FAILED( hr ) )
return hr;
hr = xSupportErrorInfo->InterfaceSupportsErrorInfo( riid );
if ( FAILED( hr ) )
return hr;
// Get the current error object. Return if none exists.
XInterface<IErrorInfo> xErrorInfo;
hr = GetErrorInfo( 0, xErrorInfo.GetPPointer() );
if ( xErrorInfo.IsNull() )
return hr;
// Get the IErrorRecord interface and get the count of errors.
XInterface<IErrorRecords> xErrorRecords;
hr = xErrorInfo->QueryInterface( IID_IErrorRecords,
xErrorRecords.GetQIPointer() );
if ( FAILED( hr ) )
return hr;
ULONG cErrRecords;
hr = xErrorRecords->GetRecordCount( &cErrRecords );
if ( 0 == cErrRecords )
return hr;
#if 1 // A good way to get the complete error message...
XInterface<IErrorInfo> xErrorInfoRec;
ERRORINFO ErrorInfo;
for ( unsigned i=0; i<cErrRecords; i++ )
{
// Get basic error information.
xErrorRecords->GetBasicErrorInfo( i, &ErrorInfo );
// Get error description and source through the IErrorInfo interface
// pointer on a particular record.
xErrorRecords->GetErrorInfo( i, lcid, xErrorInfoRec.GetPPointer() );
XBStr bstrDescriptionOfError;
XBStr bstrSourceOfError;
BSTR bstrDesc = bstrDescriptionOfError.GetPointer();
BSTR bstrSrc = bstrSourceOfError.GetPointer();
xErrorInfoRec->GetDescription( &bstrDesc );
xErrorInfoRec->GetSource( &bstrSrc );
// At this point, you could call GetCustomErrorObject and query for
// additional interfaces to determine what else happened.
wprintf( L"%s (%#x)\n%s\n", bstrDesc, ErrorInfo.hrError, bstrSrc );
}
#endif
// Get basic error information for the most recent error
ULONG iRecord = cErrRecords - 1;
hr = xErrorRecords->GetBasicErrorInfo( iRecord, pErrorInfo );
if ( FAILED( hr ) )
return hr;
return xErrorRecords->GetErrorInfo( iRecord, lcid, ppIErrorInfo );
} //GetOleDBErrorInfo
//-----------------------------------------------------------------------------
//
// Function: DisplayRowsetStatus
//
// Synopsis: Retrieves status information about the rowset and catalog.
//
// Arguments: [xIRowset] - Rowset about which information is retrieved.
//
// Returns: HRESULT result of retrieving the status
//
//-----------------------------------------------------------------------------
HRESULT DisplayRowsetStatus( XInterface<IRowset> & xIRowset )
{
XInterface<IRowsetInfo> xIRowsetInfo;
HRESULT hr = xIRowset->QueryInterface( IID_IRowsetInfo,
xIRowsetInfo.GetQIPointer() );
if ( SUCCEEDED( hr ) )
{
// This rowset property is Indexing-Service specific
DBPROPID propId = MSIDXSPROP_ROWSETQUERYSTATUS;
DBPROPIDSET propSet;
propSet.rgPropertyIDs = &propId;
propSet.cPropertyIDs = 1;
const GUID guidRowsetExt = DBPROPSET_MSIDXS_ROWSETEXT;
propSet.guidPropertySet = guidRowsetExt;
ULONG cPropertySets = 0;
DBPROPSET * pPropertySets;
hr = xIRowsetInfo->GetProperties( 1,
&propSet,
&cPropertySets,
&pPropertySets );
if ( SUCCEEDED( hr ) )
{
DWORD dwStatus = pPropertySets->rgProperties->vValue.ulVal;
CoTaskMemFree( pPropertySets->rgProperties );
CoTaskMemFree( pPropertySets );
DWORD dwFill = QUERY_FILL_STATUS( dwStatus );
if ( STAT_ERROR == dwFill )
DisplayStat( IDS_ROWSET_STAT_ERROR );
DWORD dwReliability = QUERY_RELIABILITY_STATUS( dwStatus );
if ( 0 != ( STAT_PARTIAL_SCOPE & dwReliability ) )
DisplayStat( IDS_ROWSET_STAT_PARTIAL_SCOPE );
if ( 0 != ( STAT_NOISE_WORDS & dwReliability ) )
DisplayStat( IDS_ROWSET_STAT_NOISE_WORDS );
if ( 0 != ( STAT_CONTENT_OUT_OF_DATE & dwReliability ) )
DisplayStat( IDS_ROWSET_STAT_CONTENT_OUT_OF_DATE );
if ( 0 != ( STAT_REFRESH_INCOMPLETE & dwReliability ) )
DisplayStat( IDS_ROWSET_STAT_REFRESH_INCOMPLETE );
if ( 0 != ( STAT_CONTENT_QUERY_INCOMPLETE & dwReliability ) )
DisplayStat( IDS_ROWSET_STAT_CONTENT_QUERY_INCOMPLETE );
if ( 0 != ( STAT_TIME_LIMIT_EXCEEDED & dwReliability ) )
DisplayStat( IDS_ROWSET_STAT_TIME_LIMIT_EXCEEDED );
if ( 0 != ( STAT_SHARING_VIOLATION & dwReliability ) )
DisplayStat( IDS_ROWSET_STAT_SHARING_VIOLATION );
}
}
return hr;
} //DisplayRowsetStatus
ULONG CountEntries( WCHAR const * pwc, WCHAR wc )
{
WCHAR const * p = wcschr( pwc, wc );
ULONG c = 1;
while ( 0 != p )
{
c++;
p++;
p = wcschr( p, wc );
}
return c;
} //CountEntries
//+-------------------------------------------------------------------------
//
// Function: IssueQuery
//
// Synopsis: Creates and executes a query, then displays the results.
//
// Arguments: [pwcQueryCatalog] - Catalog name over which query is run
// [pwcQueryMachine] - Machine name on which query is run
// [pwcQueryScope] - Scope of the query
// [dwScopeFlags] - Scope flags
// [pwcQueryRestrition] - The actual query string
// [pwcColumns] - Output column names
// [pwcSort] - Sort order names, may be 0
// [fDisplayTree] - TRUE to display the command tree
// [fQuiet] - if TRUE, don't display hitcount
// [fForceUseContentIndex] - TRUE to always use index
// FALSE to allow directory enumeration
// [fNoQuery] - if TRUE, just parse and display query
// [fSearchHit] - if TRUE invoke hit-hilighting
// [ulDialect] - Query dialect (1 or 2)
// [cMaxHits] - Maximum # of hits, or 0 for no limit
// [fFirstHits] - TRUE for first N or FALSE for best N
// [lcid] - Locale for the query
// [fDefineCPP] - TRUE to define func and class props
//
// Returns: HRESULT result of the query
//
//--------------------------------------------------------------------------
HRESULT IssueQuery(
WCHAR const * pwcQueryCatalog,
WCHAR const * pwcQueryMachine,
WCHAR const * pwcQueryScope,
DWORD dwScopeFlags,
WCHAR const * pwcQueryRestriction,
WCHAR const * pwcColumns,
WCHAR const * pwcSort,
BOOL fDisplayTree,
BOOL fQuiet,
BOOL fForceUseContentIndex,
BOOL fNoQuery,
BOOL fSearchHit,
ULONG ulDialect,
ULONG cMaxHits,
BOOL fFirstHits,
LCID lcid,
BOOL fDefineCPP )
{
// Create an ICommand object. CIMakeICommand is a shortcut for making an
// ICommand. The ADVQUERY sample shows the OLE DB equivalent.
XInterface<ICommand> xICommand;
HRESULT hr;
// Handle distributed and single catalog queries
if ( ( 0 != wcschr( pwcQueryCatalog, L',' ) ) ||
( 0 != wcschr( pwcQueryMachine, L',' ) ) )
{
ULONG cCat = CountEntries( pwcQueryCatalog, L',' );
ULONG cMac = CountEntries( pwcQueryMachine, L',' );
if ( ( ( cCat != cMac ) && ( 1 != cCat ) && ( 1 != cMac ) ) ||
( cCat > MAX_CATALOGS || cMac > MAX_CATALOGS ) )
Usage();
WCHAR awcCat[ MAX_PATH ];
wcscpy( awcCat, pwcQueryCatalog );
WCHAR awcMac[ MAX_PATH ];
wcscpy( awcMac, pwcQueryMachine );
WCHAR * aCat[ MAX_CATALOGS ];
WCHAR * aMac[ MAX_CATALOGS ];
WCHAR const * aSco[ MAX_CATALOGS ];
DWORD aFla[ MAX_CATALOGS ];
WCHAR * pwcCat = awcCat;
WCHAR * pwcMac = awcMac;
for ( ULONG i = 0; i < __max( cCat, cMac ); i++ )
{
aFla[i] = dwScopeFlags;
aSco[i] = pwcQueryScope;
aMac[i] = pwcMac;
if ( 1 != cMac )
{
pwcMac = wcschr( pwcMac, L',' );
if ( 0 != pwcMac )
*pwcMac++ = 0;
}
aCat[i] = pwcCat;
if ( 1 != cCat )
{
pwcCat = wcschr( pwcCat, L',' );
if ( 0 != pwcCat )
*pwcCat++ = 0;
}
}
hr = CIMakeICommand( xICommand.GetPPointer(),
cCat,
aFla,
aSco,
aCat,
aMac );
}
else
{
hr = CIMakeICommand( xICommand.GetPPointer(), // result
1, // 1 scope
&dwScopeFlags, // scope flags
&pwcQueryScope, // scope path
&pwcQueryCatalog, // catalog
&pwcQueryMachine ); // machine
}
if ( FAILED( hr ) )
return hr;
// Set required properties on the ICommand
hr = SetCommandProperties( xICommand.GetPointer(),
fForceUseContentIndex,
lcid,
cMaxHits,
fFirstHits );
if ( FAILED( hr ) )
return hr;
// Get a command tree object
XInterface<ICommandTree> xICommandTree;
hr = xICommand->QueryInterface( IID_ICommandTree,
xICommandTree.GetQIPointer() );
if ( FAILED( hr ) )
return hr;
if ( ulDialect < 3 )
{
// Create an OLE DB query tree based on query parameters.
DBCOMMANDTREE * pTree;
ULONG cDefinedProperties = fDefineCPP ? cCPPProperties : 0;
hr = CITextToFullTreeEx( pwcQueryRestriction, // the query itself
ulDialect, // query dialect
pwcColumns, // columns to return
pwcSort, // sort order, may be 0
0, // reserved
&pTree, // resulting tree
cDefinedProperties, // C++ properties
aCPPProperties, // C++ properties
lcid ); // default locale
if ( FAILED( hr ) )
return hr;
// If directed, display the command tree.
if ( fDisplayTree )
{
wprintf( L"%ws\n", pwcQueryRestriction );
DisplayCommandTree( pTree );
}
// If directed, don't issue the query. Parsing it was sufficient.
if ( fNoQuery )
{
xICommandTree->FreeCommandTree( &pTree );
return S_OK;
}
// Set the tree in the ICommandTree. Ownership of the tree is transferred.
hr = xICommandTree->SetCommandTree( &pTree,
DBCOMMANDREUSE_NONE,
FALSE );
if ( FAILED( hr ) )
{
xICommandTree->FreeCommandTree( &pTree );
return hr;
}
}
else
{
// Get a command text object
XInterface<ICommandText> xICommandText;
hr = xICommand->QueryInterface( IID_ICommandText,
xICommandText.GetQIPointer() );
if ( FAILED( hr ) )
return hr;
hr = xICommandText->SetCommandText( DBGUID_SQL, pwcQueryRestriction );
if ( FAILED( hr ) )
return hr;
// If directed, display the command tree.
if ( fDisplayTree )
{
DBCOMMANDTREE * pTree = 0;
hr = xICommandTree->GetCommandTree( &pTree );
if ( FAILED( hr ) )
return hr;
wprintf( L"%ws\n", pwcQueryRestriction );
DisplayCommandTree( pTree );
}
// If directed, don't issue the query. Parsing it was sufficient.
if ( fNoQuery )
return S_OK;
}
// Execute the query. The query is complete when Execute() returns.
XInterface<IRowset> xIRowset;
hr = xICommand->Execute( 0, // no aggregating IUnknown
IID_IRowset, // IID for interface to return
0, // no DBPARAMs
0, // no rows affected
xIRowset.GetIUPointer() ); // result
if ( FAILED( hr ) )
{
// Get the real error; OLE DB permits few Execute() return codes
ERRORINFO ErrorInfo;
XInterface<IErrorInfo> xErrorInfo;
HRESULT hr2 = GetOleDBErrorInfo( xICommand.GetPointer(),
IID_ICommand,
lcid,
&ErrorInfo,
xErrorInfo.GetPPointer() );
// Post IErrorInfo only if we have a valid pointer to it.
if ( SUCCEEDED( hr2 ) && !xErrorInfo.IsNull() )
hr = ErrorInfo.hrError;
return hr;
}
// Get the count of columns
XInterface<IColumnsInfo> xColumnsInfo;
hr = xIRowset->QueryInterface( IID_IColumnsInfo, xColumnsInfo.GetQIPointer() );
if ( FAILED( hr ) )
return hr;
DBCOLUMNINFO *pColumnInfo = 0;
WCHAR *pColumnNames = 0;
DBORDINAL cColumns = 0;
hr = xColumnsInfo->GetColumnInfo( &cColumns,
&pColumnInfo,
&pColumnNames );
if ( FAILED( hr ) )
return hr;
// If bookmark was added as column 0, ignore it
if ( 0 != ( pColumnInfo[0].dwFlags & DBCOLUMNFLAGS_ISBOOKMARK ) )
cColumns--;
CoTaskMemFree( pColumnInfo );
CoTaskMemFree( pColumnNames );
// Create an accessor, so data can be retrieved from the rowset.
XInterface<IAccessor> xIAccessor;
hr = xIRowset->QueryInterface( IID_IAccessor,
xIAccessor.GetQIPointer() );
if ( FAILED( hr ) )
return hr;
// Column iOrdinals are parallel with those passed to CiTextToFullTree,
// so MapColumnIDs isn't necessary. These binding values for dwPart,
// dwMemOwner, and wType are the most optimal bindings for Indexing
// Service.
XPtr<DBBINDING> xBindings( (ULONG) cColumns );
if ( xBindings.IsNull() )
return E_OUTOFMEMORY;
memset( xBindings.Get(), 0, sizeof DBBINDING * cColumns );
for ( ULONG i = 0; i < cColumns; i++ )
{
xBindings[i].iOrdinal = 1 + i; // 1-based column number
xBindings[i].obValue = i * sizeof( PROPVARIANT * ); // offset
xBindings[i].dwPart = DBPART_VALUE; // retrieve value, not status
xBindings[i].dwMemOwner = DBMEMOWNER_PROVIDEROWNED; // provider owned
xBindings[i].wType = DBTYPE_VARIANT | DBTYPE_BYREF; // VARIANT *
}
HACCESSOR hAccessor;
hr = xIAccessor->CreateAccessor( DBACCESSOR_ROWDATA, // rowdata accessor
cColumns, // # of columns
xBindings.Get(), // columns
0, // ignored
&hAccessor, // result
0 ); // no status
if ( FAILED( hr ) )
return hr;
DBORDINAL iPathColumn = ~0;
if ( fSearchHit )
{
const DBID dbcolPath = { PSGUID_STORAGE,
DBKIND_GUID_PROPID,
(LPWSTR) (ULONG_PTR) PID_STG_PATH };
hr = xColumnsInfo->MapColumnIDs( 1,
& dbcolPath,
& iPathColumn );
if ( FAILED( hr ) )
return hr;
// Change from 1-based to 0-based.
iPathColumn--;
}
// Display the results of the query.
XPtr<PROPVARIANT *> xData( (ULONG) cColumns );
if ( xData.IsNull() )
hr = E_OUTOFMEMORY;
else
{
DBCOUNTITEM cRowsSoFar = 0;
do
{
DBCOUNTITEM cRowsReturned = 0;
const ULONG cRowsAtATime = 20;
HROW aHRow[cRowsAtATime];
HROW * pgrHRows = aHRow;
hr = xIRowset->GetNextRows( 0, // no chapter
0, // no rows to skip
cRowsAtATime, // # rows to get
&cRowsReturned, // # rows returned
&pgrHRows); // resulting hrows
if ( FAILED( hr ) )
break;
for ( DBCOUNTITEM iRow = 0; iRow < cRowsReturned; iRow++ )
{
HRESULT hr2 = xIRowset->GetData( aHRow[iRow], // hrow being accessed
hAccessor, // accessor to use
xData.Get() ); // resulting data
if ( FAILED( hr2 ) )
{
hr = hr2;
break;
}
if ( ( 1 != cColumns ) || !fSearchHit )
{
for ( ULONG iCol = 0; iCol < cColumns; iCol++ )
{
if ( 0 != iCol )
wprintf( L" " );
DisplayValue( xData[ iCol ] );
}
wprintf( L"\n" );
}
if ( fSearchHit )
{
PROPVARIANT * pPropVar = xData[ (unsigned int)iPathColumn ];
if ( ( VT_LPWSTR == pPropVar->vt ) &&
( 0 != pPropVar->pwszVal ) )
{
DoISearch( pwcQueryRestriction,
pPropVar->pwszVal,
( 1 == cColumns ),
fDefineCPP,
lcid,
ulDialect );
}
}
}
// Release the HROWs retrived in GetNextRows
if ( 0 != cRowsReturned )
{
cRowsSoFar += cRowsReturned;
xIRowset->ReleaseRows( cRowsReturned, // # of rows to release
aHRow, // rows to release
0, // no options
0, // no refcounts
0 ); // no status
}
// Check if all rows are now retrieved.
if ( DB_S_ENDOFROWSET == hr || DB_S_ROWLIMITEXCEEDED == hr )
{
hr = S_OK; // succeeded, return S_OK from DoQuery
break;
}
// Check if the query aborted because it was too costly.
if ( DB_S_STOPLIMITREACHED == hr )
{
CResString str( IDS_QUERYTIMEDOUT );
wprintf( L"%ws\n", str.Get() );
hr = S_OK;
break;
}
if ( FAILED( hr ) )
break;
} while ( TRUE );
if ( !fQuiet )
{
CResString str( IDS_QUERYDONE );
wprintf( str.Get(), cRowsSoFar, pwcQueryRestriction );
}
}
xIAccessor->ReleaseAccessor( hAccessor, 0 );
// Get query status information
if ( SUCCEEDED( hr ) && !fQuiet )
hr = DisplayRowsetStatus( xIRowset );
return hr;
} //IssueQuery
//+-------------------------------------------------------------------------
//
// Function: DoQuery
//
// Synopsis: Issues a query and displays an error message on failure
//
// Arguments: [pwcQueryCatalog] - Catalog name over which query is run
// [pwcQueryMachine] - Machine name on which query is run
// [pwcQueryScope] - Scope of the query
// [dwScopeFlags] - Scope flags
// [pwcQueryRestrition] - The actual query string
// [pwcColumns] - Output column names
// [pwcSort] - Sort order names, may be 0
// [fDisplayTree] - TRUE to display the command tree
// [fQuiet] - if TRUE, don't display hitcount
// [fForceUseContentIndex] - TRUE to always use index
// FALSE to allow directory enumeration
// [fNoQuery] - if TRUE, just parse and display query
// [fSearchHit] - if TRUE invoke isrchdmp.exe
// [ulDialect] - Query dialect (1 or 2)
// [cMaxHits] - Maximum # of hits, or 0 for no limit
// [fFirstHits] - TRUE for first N or FALSE for best N
// [lcid] - Locale for the query
// [fDefineCPP] - TRUE to define func and class props
//
// Returns: HRESULT result of the query
//
//--------------------------------------------------------------------------
HRESULT DoQuery(
WCHAR const * pwcCatalog,
WCHAR const * pwcMachine,
WCHAR const * pwcScope,
DWORD dwScopeFlags,
WCHAR const * pwcRestriction,
WCHAR const * pwcColumns,
WCHAR const * pwcSort,
BOOL fDisplayTree,
BOOL fQuiet,
BOOL fForceUseContentIndex,
BOOL fNoQuery,
BOOL fSearchHit,
ULONG ulDialect,
ULONG cMaxHits,
BOOL fFirstHits,
LCID lcid,
BOOL fDefineCPP )
{
HRESULT hr = IssueQuery( pwcCatalog,
pwcMachine,
pwcScope,
dwScopeFlags,
pwcRestriction,
pwcColumns,
pwcSort,
fDisplayTree,
fQuiet,
fForceUseContentIndex,
fNoQuery,
fSearchHit,
ulDialect,
cMaxHits,
fFirstHits,
lcid,
fDefineCPP );
if ( FAILED( hr ) )
DisplayError( IDS_QUERYFAILED, pwcRestriction, hr, lcid );
return hr;
} //DoQuery
//+-------------------------------------------------------------------------
//
// Function: DoQueryFile
//
// Synopsis: Issues each query in the specified query file. A query file
// is just a text file where each line contains a query.
//
// Arguments: [pwcQueryCatalog] - Catalog name over which query is run
// [pwcQueryMachine] - Machine name on which query is run
// [pwcQueryScope] - Scope of the query
// [dwScopeFlags] - Scope flags
// [pwcColumns] - Output column names
// [pwcSort] - Sort order names, may be 0
// [fDisplayTree] - TRUE to display the command tree
// [fQuiet] - if TRUE, don't display hitcount
// [fForceUseContentIndex] - TRUE to always use index
// FALSE to allow directory enumeration
// [fNoQuery] - if TRUE, just parse and display query
// [fSearchHit] - if TRUE invoke isrchdmp.exe
// [ulDialect] - Query dialect (1 or 2)
// [cMaxHits] - Maximum # of hits, or 0 for no limit
// [fFirstHits] - TRUE for first N or FALSE for best N
// [lcid] - Locale for the query
// [pwcQueryFile] - File containing queries, 1 per line
// [fDefineCPP] - TRUE to define func and class props
//
// Returns: HRESULT result of the query
//
//--------------------------------------------------------------------------
HRESULT DoQueryFile(
WCHAR const * pwcQueryCatalog,
WCHAR const * pwcQueryMachine,
WCHAR const * pwcQueryScope,
DWORD dwScopeFlags,
WCHAR const * pwcColumns,
WCHAR const * pwcSort,
BOOL fDisplayTree,
BOOL fQuiet,
BOOL fForceUseContentIndex,
BOOL fNoQuery,
BOOL fSearchHit,
ULONG ulDialect,
ULONG cMaxHits,
BOOL fFirstHits,
LCID lcid,
WCHAR const * pwcQueryFile,
BOOL fDefineCPP )
{
// Open and read the query file
HANDLE hFile = CreateFile( pwcQueryFile,
FILE_GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_DELETE,
0,
OPEN_EXISTING,
0,
0 );
if ( 0 == hFile || INVALID_HANDLE_VALUE == hFile )
return DisplayWin32Error( IDS_CANTOPENFILE,
pwcQueryFile,
lcid );
DWORD cbFile = GetFileSize( hFile, 0 );
if ( 0xffffffff == cbFile )
{
CloseHandle( hFile );
return DisplayWin32Error( IDS_CANTGETFILESIZE,
pwcQueryFile,
lcid );
}
// Allocate a buffer for the file
XPtr<BYTE> xQueries( cbFile + sizeof WCHAR );
if ( xQueries.IsNull() )
{
CloseHandle( hFile );
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
return DisplayWin32Error( IDS_CANTGETMEMORY,
pwcQueryFile,
lcid );
}
// Read the file into the buffer
DWORD cbRead;
BOOL fRead = ReadFile( hFile, xQueries.Get(), cbFile, &cbRead, 0 );
CloseHandle( hFile );
if ( ! fRead )
return DisplayWin32Error( IDS_CANTREADFROMFILE,
pwcQueryFile,
lcid );
if ( cbRead != cbFile )
{
SetLastError( ERROR_INVALID_DATA );
return DisplayWin32Error( IDS_CANTREADFROMFILE,
pwcQueryFile,
lcid );
}
// Check if the file is Unicode already
BOOL fUnicode = FALSE;
if ( cbRead >= 2 )
fUnicode = ( 0xfeff == ( * (WCHAR *) xQueries.Get() ) );
WCHAR * pwcIn = 0;
DWORD cwcIn = 0;
if ( fUnicode )
{
pwcIn = (WCHAR *) xQueries.Get();
// skip past the Unicode marker
pwcIn++;
cwcIn = ( cbFile / sizeof WCHAR ) - 1;
}
else
{
// Convert to Unicode. Leave a little room for slack.
DWORD cbTmp = cbFile * sizeof WCHAR + cbFile / 8;
XPtr<BYTE> xTmp( cbTmp + sizeof WCHAR );
if ( xTmp.IsNull() )
{
SetLastError( ERROR_NOT_ENOUGH_MEMORY );
return DisplayWin32Error( IDS_CANTGETMEMORY,
pwcQueryFile,
lcid );
}
cwcIn = MultiByteToWideChar( LocaleToCodepage( lcid ),
0,
(const char *) xQueries.Get(),
cbFile,
(WCHAR *) xTmp.Get(),
cbTmp );
if ( 0 == cwcIn )
return DisplayWin32Error( IDS_CANTCONVERTTOUNICODE,
pwcQueryFile,
lcid );
pwcIn = (WCHAR *) xTmp.Get();
xQueries.Free();
xQueries.Set( xTmp.Acquire() );
}
// Read each line in the file and issue the query
pwcIn[ cwcIn ] = 0;
WCHAR * pwc = pwcIn;
do
{
while ( 0 != *pwcIn &&
L'\r' != *pwcIn &&
L'\n' != *pwcIn )
pwcIn++;
BOOL fEOF = ( 0 == *pwcIn );
*pwcIn = 0;
if ( pwc != pwcIn )
{
DoQuery( pwcQueryCatalog,
pwcQueryMachine,
pwcQueryScope,
dwScopeFlags,
pwc,
pwcColumns,
pwcSort,
fDisplayTree,
fQuiet,
fForceUseContentIndex,
fNoQuery,
fSearchHit,
ulDialect,
cMaxHits,
fFirstHits,
lcid,
fDefineCPP );
wprintf( L"\n\n" );
}
if ( fEOF )
break;
pwcIn++;
while ( '\r' == *pwcIn || '\n' == *pwcIn )
pwcIn++;
pwc = pwcIn;
} while ( TRUE );
return S_OK;
} //DoQueryFile
//+-------------------------------------------------------------------------
//
// Function: LookupCatalog
//
// Synopsis: Looks for a catalog and machine matching the scope
//
// Arguments: [pwcScope] - The scope used to find the catalog
// [pwcMachine] - Returns the machine name
// [cwcMachine] - In/Out: Count of characters in pwcMachine
// [pwcCatalog] - Returns the catalog name
// [cwcCatalog] - In/Out: Count of characters in pwcCatalog
// [lcid] - Locale to use for errors
//
//--------------------------------------------------------------------------
HRESULT LookupCatalog(
WCHAR const * pwcScope,
WCHAR * pwcMachine,
ULONG & cwcMachine,
WCHAR * pwcCatalog,
ULONG & cwcCatalog,
LCID lcid )
{
HRESULT hr = LocateCatalogs( pwcScope, // scope to lookup
0, // go with the first match
pwcMachine, // returns the machine
&cwcMachine, // buffer size in/out
pwcCatalog, // returns the catalog
&cwcCatalog ); // buffer size in/out
if ( FAILED( hr ) || ( S_FALSE == hr ) )
{
DisplayError( IDS_CANTFINDCATALOG, pwcScope, hr, lcid );
hr = E_FAIL;
}
return hr;
} //LookupCatalog
//+-------------------------------------------------------------------------
//
// Function: NormalizeScope
//
// Synopsis: Normalizes a scope and sets scope flags.
//
// Arguments: [pwcIn] - The scope for the query
// [pwcOut] - Returns the scope for the query
// [dwScopeFlags] - Returns the scope flags for the query
//
//--------------------------------------------------------------------------
HRESULT NormalizeScope(
WCHAR const * pwcIn,
WCHAR * pwcOut,
BOOL fShallow,
DWORD & dwScopeFlags )
{
if ( wcslen( pwcIn ) >= MAX_PATH )
return E_INVALIDARG;
if ( fShallow )
dwScopeFlags = QUERY_SHALLOW;
else
dwScopeFlags = QUERY_DEEP;
wcscpy( pwcOut, pwcIn );
// Check if the scope is an IIS virtual scope.
WCHAR wc = pwcIn[0];
if ( L'/' == wc )
{
// Set the virtual scope flag and flip the slashes.
dwScopeFlags |= QUERY_VIRTUAL_PATH;
for ( WCHAR * pwc = pwcOut; *pwc; pwc++ )
if ( '/' == *pwc )
*pwc = '\\';
}
else if ( ( !( L'\\' == wc && L'\\' == pwcIn[1] ) ) &&
( !( L'\\' == wc && 0 == pwcIn[1] ) ) &&
L':' != pwcIn[1] &&
0 != wc )
{
// Turn the relative path into a full path based on the current dir.
_wfullpath( pwcOut, pwcIn, MAX_PATH );
}
return S_OK;
} //NormalizeScope
//+-------------------------------------------------------------------------
//
// Function: DisplayStatus
//
// Synopsis: Displays status information about a catalog
//
// Arguments: [pwcCatalog] - Catalog name
// [pwcMachine] - Machine on which catalog resides
// [lcid] - Locale to use
//
//--------------------------------------------------------------------------
HRESULT DisplayStatus(
WCHAR const * pwcCatalog,
WCHAR const * pwcMachine,
LCID lcid )
{
CI_STATE state;
state.cbStruct = sizeof state;
DisplayStat( pwcMachine, IDS_STAT_MACHINE );
DisplayStat( pwcCatalog, IDS_STAT_CATALOG );
HRESULT hr = CIState( pwcCatalog, pwcMachine, &state );
if ( SUCCEEDED( hr ) )
{
DisplayStat( state.cTotalDocuments, IDS_STAT_TOTALDOCUMENTS );
DisplayStat( state.cFreshTest, IDS_STAT_FRESHTEST );
DisplayStat( state.cFilteredDocuments, IDS_STAT_FILTEREDDOCUMENTS );
DisplayStat( state.cDocuments, IDS_STAT_DOCUMENTS );
DisplayStat( state.cSecQDocuments, IDS_STAT_SECQDOCUMENTS );
DisplayStat( state.cUniqueKeys, IDS_STAT_UNIQUEKEYS );
DisplayStat( state.cWordList, IDS_STAT_WORDLIST );
DisplayStat( state.cPersistentIndex, IDS_STAT_PERSISTENTINDEX );
DisplayStat( state.cQueries, IDS_STAT_QUERIES );
DisplayStat( state.dwIndexSize, IDS_STAT_INDEXSIZE );
DisplayStat( state.dwPropCacheSize / 1024, IDS_STAT_PROPCACHESIZE );
DisplayStat( ( state.eState & CI_STATE_SCANNING ) ?
state.cPendingScans : 0,
IDS_STAT_SCANS );
const DWORD ALL_CI_MERGE = ( CI_STATE_SHADOW_MERGE |
CI_STATE_ANNEALING_MERGE |
CI_STATE_INDEX_MIGRATION_MERGE |
CI_STATE_MASTER_MERGE |
CI_STATE_MASTER_MERGE_PAUSED );
if ( 0 != ( ALL_CI_MERGE & state.eState ) )
{
UINT idStr;
if ( state.eState & CI_STATE_SHADOW_MERGE )
idStr = IDS_STAT_MERGE_SHADOW;
else if ( state.eState & CI_STATE_ANNEALING_MERGE )
idStr = IDS_STAT_MERGE_ANNEALING;
else if ( state.eState & CI_STATE_INDEX_MIGRATION_MERGE )
idStr = IDS_STAT_MERGE_INDEX_MIGRATION;
else if ( state.eState & CI_STATE_MASTER_MERGE )
idStr = IDS_STAT_MERGE_MASTER;
else
idStr = IDS_STAT_MERGE_MASTER_PAUSED;
DisplayStat( state.dwMergeProgress, idStr );
}
if ( CI_STATE_READ_ONLY & state.eState )
DisplayStat( IDS_STAT_READ_ONLY );
if ( CI_STATE_RECOVERING & state.eState )
DisplayStat( IDS_STAT_RECOVERING );
if ( CI_STATE_LOW_MEMORY & state.eState )
DisplayStat( IDS_STAT_LOW_MEMORY );
if ( CI_STATE_HIGH_IO & state.eState )
DisplayStat( IDS_STAT_HIGH_IO );
if ( CI_STATE_BATTERY_POWER & state.eState )
DisplayStat( IDS_STAT_BATTERY_POWER );
if ( CI_STATE_USER_ACTIVE & state.eState )
DisplayStat( IDS_STAT_USER_ACTIVE );
if ( CI_STATE_STARTING & state.eState )
DisplayStat( IDS_STAT_STARTING );
if ( CI_STATE_READING_USNS & state.eState )
DisplayStat( IDS_STAT_READING_USNS );
}
else
{
DisplayError( IDS_CANTDISPLAYSTATUS, pwcCatalog, hr, lcid );
}
return hr;
} //DisplayStatus
//+-------------------------------------------------------------------------
//
// Function: ForceMerge
//
// Synopsis: Forces a master merge on the catalog
//
// Arguments: [pwcCatalog] - Catalog name
// [pwcMachine] - Machine on which catalog resides
// [lcid] - Locale to use
//
//--------------------------------------------------------------------------
HRESULT ForceMerge(
WCHAR const * pwcCatalog,
WCHAR const * pwcMachine,
LCID lcid )
{
// Create the main Indexing Service administration object.
CLSID clsid;
HRESULT hr = CLSIDFromProgID( L"Microsoft.ISAdm", &clsid );
if ( FAILED( hr ) )
return DisplayError( IDS_CANTFORCEMERGE,
pwcCatalog,
hr,
lcid );
XInterface<IAdminIndexServer> xAdmin;
hr = CoCreateInstance( clsid,
0,
CLSCTX_INPROC_SERVER,
__uuidof(IAdminIndexServer),
xAdmin.GetQIPointer() );
if ( FAILED( hr ) )
return DisplayError( IDS_CANTFORCEMERGE,
pwcCatalog,
hr,
lcid );
// Set the machine name.
BSTR bstrMachine = SysAllocString( pwcMachine );
if ( 0 == bstrMachine )
return DisplayError( IDS_CANTFORCEMERGE,
pwcCatalog,
E_OUTOFMEMORY,
lcid );
XBStr xbstr( bstrMachine );
hr = xAdmin->put_MachineName( bstrMachine );
if ( FAILED( hr ) )
return DisplayError( IDS_CANTFORCEMERGE,
pwcCatalog,
hr,
lcid );
// Get a catalog administration object.
BSTR bstrCatalog = SysAllocString( pwcCatalog );
if ( 0 == bstrCatalog )
return DisplayError( IDS_CANTFORCEMERGE,
pwcCatalog,
E_OUTOFMEMORY,
lcid );
xbstr.Free();
xbstr.Set( bstrCatalog );
XInterface<ICatAdm> xCatAdmin;
hr = xAdmin->GetCatalogByName( bstrCatalog,
(IDispatch **) xCatAdmin.GetQIPointer() );
if ( FAILED( hr ) )
return DisplayError( IDS_CANTFORCEMERGE,
pwcCatalog,
hr,
lcid );
// Force the merge.
hr = xCatAdmin->ForceMasterMerge();
if ( FAILED( hr ) )
return DisplayError( IDS_CANTFORCEMERGE,
pwcCatalog,
hr,
lcid );
return hr;
} //ForceMerge
//+-------------------------------------------------------------------------
//
// Function: DisplayUpToDate
//
// Synopsis: Checks if the index is up to date.
//
// Arguments: [pwcCatalog] - Catalog name
// [pwcMachine] - Machine on which catalog resides
// [lcid] - Locale to use
//
//--------------------------------------------------------------------------
HRESULT DisplayUpToDate(
WCHAR const * pwcCatalog,
WCHAR const * pwcMachine,
LCID lcid )
{
CI_STATE state;
state.cbStruct = sizeof state;
HRESULT hr = CIState( pwcCatalog, pwcMachine, &state );
if ( SUCCEEDED( hr ) )
{
// It's up to date if there are no documents to filter, no scans or
// usn activity, and the index isn't starting or recovering.
BOOL fUpToDate = ( ( 0 == state.cDocuments ) &&
( 0 == ( state.eState & CI_STATE_SCANNING ) ) &&
( 0 == ( state.eState & CI_STATE_READING_USNS ) ) &&
( 0 == ( state.eState & CI_STATE_STARTING ) ) &&
( 0 == ( state.eState & CI_STATE_RECOVERING ) ) );
DisplayStat( fUpToDate ? IDS_STAT_UP_TO_DATE :
IDS_STAT_NOT_UP_TO_DATE );
}
else
{
DisplayError( IDS_CANTDISPLAYSTATUS, pwcCatalog, hr, lcid );
}
return hr;
} //DisplayUpToDate
//+-------------------------------------------------------------------------
//
// Function: wmain
//
// Synopsis: Entry point for the app. Parses command line arguments and
// issues a query.
//
// Arguments: [argc] - Argument count
// [argv] - Arguments
//
//--------------------------------------------------------------------------
extern "C" int __cdecl wmain( int argc, WCHAR * argv[] )
{
WCHAR const * pwcCatalog = 0; // default: lookup catalog
WCHAR const * pwcMachine = L"."; // default: local machine
WCHAR const * pwcScope = L"\\"; // default: entire catalog
WCHAR const * pwcRestriction = 0; // no default restriction
WCHAR const * pwcColumns = L"path"; // default output column(s)
WCHAR const * pwcSort = 0; // no sort is the default
WCHAR const * pwcQueryFile = 0; // no query file specified
WCHAR const * pwcLocale = 0; // default: system locale
BOOL fDisplayTree = FALSE; // don't display the tree
BOOL fForceUseContentIndex = TRUE; // always use the index
ULONG ulDialect = 1; // original query language dialect
BOOL fQuiet = FALSE; // show the hitcount
ULONG cMaxHits = 0; // default: retrieve all hits
BOOL fFirstHits = FALSE; // First vs Best N hits
BOOL fDisplayStatus = FALSE; // default: don't show status
BOOL fDisplayUpToDate = FALSE; // default: don't show up to date
ULONG cRepetitions = 1; // # of times to repeat command
BOOL fShallow = FALSE; // default: all subdirectories
BOOL fNoQuery = FALSE; // default: execute query
BOOL fSearchHit = FALSE; // default: don't isrchdmp.exe
BOOL fDefineCPP = FALSE; // default: don't define props
BOOL fForceMerge = FALSE; // default: don't force a MM
BOOL fSmart = FALSE; // default: use all the options provided
// Parse command line parameters
for ( int i = 1; i < argc; i++ )
{
if ( L'-' == argv[i][0] || L'/' == argv[i][0] )
{
WCHAR wc = (WCHAR) toupper( (char) argv[i][1] );
if ( ':' != argv[i][2] &&
'D' != wc &&
'G' != wc &&
'H' != wc &&
'J' != wc &&
'N' != wc &&
'Q' != wc &&
'U' != wc &&
'S' != wc &&
'T' != wc &&
'Z' != wc )
Usage();
if ( 'C' == wc )
{
pwcCatalog = argv[i] + 3;
if ( wcslen( pwcCatalog ) >= MAX_PATH )
Usage();
}
else if ( 'M' == wc )
{
pwcMachine = argv[i] + 3;
if ( wcslen( pwcMachine ) >= MAX_PATH )
Usage();
}
else if ( 'P' == wc )
pwcScope = argv[i] + 3;
else if ( 'O' == wc )
pwcColumns = argv[i] + 3;
else if ( 'S' == wc )
{
if ( _wcsicmp (argv[i]+1, L"smart") == 0 )
{
fSmart = TRUE;
}
else
{
if (argv[i][2] != L':')
Usage();
pwcSort = argv[i] + 3;
}
}
else if ( 'X' == wc )
cMaxHits = _wtoi( argv[i] + 3 );
else if ( 'Y' == wc )
{
cMaxHits = _wtoi( argv[i] + 3 );
fFirstHits = TRUE;
}
else if ( 'I' == wc )
{
if ( 0 != pwcRestriction )
Usage();
pwcQueryFile = argv[i] + 3;
}
else if ( 'R' == wc)
{
// get the next arg as a number
cRepetitions = _wtol(argv[i]+3);
}
else if ( 'D' == wc )
fDisplayTree = TRUE;
else if ( 'G' == wc )
fForceMerge = TRUE;
else if ( 'H' == wc )
fSearchHit = TRUE;
else if ( 'J' == wc )
fShallow = TRUE;
else if ( 'N' == wc )
fNoQuery = TRUE;
else if ( 'Q' == wc )
fQuiet = TRUE;
else if ( 'T' == wc )
fDisplayStatus = TRUE;
else if ( 'U' == wc )
fDisplayUpToDate = TRUE;
else if ( 'E' == wc )
pwcLocale = argv[i] + 3;
else if ( 'L' == wc )
{
if ( '1' == argv[i][3] )
ulDialect = 1;
else if ( '2' == argv[i][3] )
ulDialect = 2;
else if ( '3' == argv[i][3] )
ulDialect = 3;
else
Usage();
}
else if ( 'F' == wc )
{
if ( '+' == argv[i][3] )
fForceUseContentIndex = TRUE;
else if ( '-' == argv[i][3] )
fForceUseContentIndex = FALSE;
else
Usage();
}
else if ( 'Z' == wc )
fDefineCPP = TRUE;
else
Usage();
}
else if ( 0 != pwcRestriction || 0 != pwcQueryFile )
Usage();
else
pwcRestriction = argv[i];
}
// A query restriction, query file, or status request is necessary.
if ( 0 == pwcRestriction && 0 == pwcQueryFile &&
!fDisplayStatus && !fDisplayUpToDate && !fForceMerge )
Usage();
if ( fSmart )
{
// If we're in smart mode, don't let people specify machine, path, or catalog
if ( ( pwcCatalog != 0 ) ||
( _wcsicmp( pwcMachine, L"." ) != 0 ) ||
( _wcsicmp( pwcScope, L"\\" ) != 0 ) )
{
Usage();
}
// Fix the scope, to figure out the catalog, but we'll reset it later.
// We set it to the current directory now, which will be expanded to the
// full path we're sitting in, so that we'll find the right catalog.
pwcScope = L".";
}
// Normalize relative and virtual scopes
WCHAR awcScope[ MAX_PATH ];
DWORD dwScopeFlags;
HRESULT hr = NormalizeScope( pwcScope, awcScope, fShallow, dwScopeFlags );
// Initialize OLE
BOOL fCoInit = FALSE;
if ( SUCCEEDED( hr ) )
{
hr = CoInitialize( 0 );
if ( SUCCEEDED( hr ) )
fCoInit = TRUE;
}
if ( FAILED( hr ) )
return -1;
// Get the locale identifier to use for the query
LCID lcid = LcidFromHttpAcceptLanguage( pwcLocale );
HINSTANCE hISearch = 0;
if ( fSearchHit )
{
hISearch = PrepareForISearch();
if ( 0 == hISearch )
Usage();
}
// If no catalog was specified, infer one based on the scope
WCHAR awcMachine[ MAX_PATH ], awcCatalog[ MAX_PATH ];
if ( SUCCEEDED( hr ) && ( 0 == pwcCatalog ) && !fNoQuery )
{
ULONG cwcMachine = sizeof awcMachine / sizeof WCHAR;
ULONG cwcCatalog = sizeof awcCatalog / sizeof WCHAR;
hr = LookupCatalog( awcScope,
awcMachine,
cwcMachine,
awcCatalog,
cwcCatalog,
lcid );
pwcMachine = awcMachine;
pwcCatalog = awcCatalog;
// Turn scopes like \\machine into \ now that the lookup is done
// and we've found a catalog and machine name.
if ( SUCCEEDED( hr ) &&
L'\\' == awcScope[0] && L'\\' == awcScope[1] &&
0 == wcschr( awcScope + 2, L'\\' ) )
awcScope[1] = 0;
}
if ( fSmart )
{
// Now that we've got the catalog, if we're in smart mode, put
// the scope back to what it was.
awcScope[0] = L'\\';
awcScope[1] = L'\0';
}
if ( SUCCEEDED( hr ) )
{
for (ULONG j = 0; j < cRepetitions; j++)
{
if ( 0 != pwcQueryFile )
hr = DoQueryFile( fNoQuery ? L"::_noquery" : pwcCatalog,
pwcMachine,
awcScope,
dwScopeFlags,
pwcColumns,
pwcSort,
fDisplayTree,
fQuiet,
fForceUseContentIndex,
fNoQuery,
fSearchHit,
ulDialect,
cMaxHits,
fFirstHits,
lcid,
pwcQueryFile,
fDefineCPP );
else if ( 0 != pwcRestriction )
hr = DoQuery( fNoQuery ? L"::_noquery" : pwcCatalog,
pwcMachine,
awcScope,
dwScopeFlags,
pwcRestriction,
pwcColumns,
pwcSort,
fDisplayTree,
fQuiet,
fForceUseContentIndex,
fNoQuery,
fSearchHit,
ulDialect,
cMaxHits,
fFirstHits,
lcid,
fDefineCPP );
if ( SUCCEEDED( hr ) && fForceMerge )
hr = ForceMerge( pwcCatalog, pwcMachine, lcid );
if ( SUCCEEDED( hr ) && fDisplayStatus )
hr = DisplayStatus( pwcCatalog, pwcMachine, lcid );
if ( SUCCEEDED( hr ) && fDisplayUpToDate )
hr = DisplayUpToDate( pwcCatalog, pwcMachine, lcid );
}
}
if ( fCoInit )
CoUninitialize();
if ( 0 != hISearch )
DoneWithISearch( hISearch );
if ( FAILED( hr ) )
return -1;
return 0;
} //wmain
| 33.310897 | 92 | 0.449305 | [
"render",
"object",
"vector"
] |
253d88c7cef7d0f7b649a38ae32fbbe650840257 | 3,315 | cpp | C++ | Desktop/MgDesktop/Services/ProfilingService.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Desktop/MgDesktop/Services/ProfilingService.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Desktop/MgDesktop/Services/ProfilingService.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | #include "ProfilingService.h"
#include "ProfileResult.h"
#include "ProfileRenderMapResult.h"
#include "SAX2Parser.h"
MgdProfilingService::MgdProfilingService()
{
Ptr<MgdServiceFactory> fact = new MgdServiceFactory();
m_svcRendering = static_cast<MgdRenderingService*>(fact->CreateService(MgServiceType::RenderingService));
}
MgdProfilingService::~MgdProfilingService()
{
SAFE_RELEASE(m_svcRendering);
}
MgByteReader* MgdProfilingService::ProfileRenderDynamicOverlay(
MgdMap* map,
MgdSelection* selection,
MgdRenderingOptions* options)
{
Ptr<MgByteReader> ret;
MG_TRY()
if (NULL == map)
throw new MgNullArgumentException(L"MgdProfilingService::ProfileRenderDynamicOverlay", __LINE__, __WFILE__, NULL, L"", NULL);
auto_ptr<ProfileRenderMapResult> pPRMResult; // a pointer points to Profile Render Map Result
pPRMResult.reset(new ProfileRenderMapResult());
// Start to profile the ProfileRenderDynamicOverlay process
double renderMapStart = MgdTimerUtil::GetTime();
m_svcRendering->RenderDynamicOverlay(map, selection, options, pPRMResult.get());
double renderMapEnd = MgdTimerUtil::GetTime();
pPRMResult->SetRenderTime(renderMapEnd - renderMapStart);
pPRMResult->SetProfileResultType(ProfileResult::ProfileRenderDynamicOverlay);
// Serialize the ProfileRenderMapResult to xml
MdfParser::SAX2Parser parser;
auto_ptr<Version> version;
version.reset(new Version(2,4,0));
string content = parser.SerializeToXML(pPRMResult.get(),version.get());
ret = new MgByteReader(MgUtil::MultiByteToWideChar(content), MgMimeType::Xml);
MG_CATCH_AND_THROW(L"MgdProfilingService::ProfileRenderDynamicOverlay")
return ret.Detach();
}
MgByteReader* MgdProfilingService::ProfileRenderMap(
MgdMap* map,
MgdSelection* selection,
MgCoordinate* center,
double scale,
INT32 width,
INT32 height,
MgColor* backgroundColor,
CREFSTRING format,
bool bKeepSelection)
{
Ptr<MgByteReader> ret;
MG_TRY()
if (NULL == map)
throw new MgNullArgumentException(L"MgdProfilingService::ProfileRenderMap", __LINE__, __WFILE__, NULL, L"", NULL);
auto_ptr<ProfileRenderMapResult> pPRMResult; // a pointer points to Profile Render Map Result
pPRMResult.reset(new ProfileRenderMapResult());
// Start to profile the ProfileRenderMap process
double renderMapStart = MgdTimerUtil::GetTime();
m_svcRendering->RenderMap(map, selection, center, scale, width, height, backgroundColor, format, bKeepSelection, pPRMResult.get());
double renderMapEnd = MgdTimerUtil::GetTime();
pPRMResult->SetRenderTime(renderMapEnd - renderMapStart);
pPRMResult->SetProfileResultType(ProfileResult::ProfileRenderMap);
// Serialize the ProfileRenderMapResult to xml
MdfParser::SAX2Parser parser;
auto_ptr<Version> version;
version.reset(new Version(2,4,0));
string content = parser.SerializeToXML(pPRMResult.get(),version.get());
ret = new MgByteReader(MgUtil::MultiByteToWideChar(content), MgMimeType::Xml);
MG_CATCH_AND_THROW(L"MgdProfilingService::ProfileRenderMap")
return ret.Detach();
} | 36.032609 | 136 | 0.71644 | [
"render"
] |
253e2d117d9cc4b5bc746ad0694909295728a4ee | 4,300 | cpp | C++ | Retired_Files/get_label_piecewise_affine_transformation_mask.mex.cpp | billkarsh/Alignment_Projects | f2ce48477da866b09a13fd33f1a53a8af644b35b | [
"BSD-3-Clause"
] | 11 | 2015-07-24T14:41:25.000Z | 2022-03-19T13:27:51.000Z | Retired_Files/get_label_piecewise_affine_transformation_mask.mex.cpp | billkarsh/Alignment_Projects | f2ce48477da866b09a13fd33f1a53a8af644b35b | [
"BSD-3-Clause"
] | 1 | 2016-05-14T22:26:25.000Z | 2016-05-14T22:26:25.000Z | Retired_Files/get_label_piecewise_affine_transformation_mask.mex.cpp | billkarsh/Alignment_Projects | f2ce48477da866b09a13fd33f1a53a8af644b35b | [
"BSD-3-Clause"
] | 18 | 2015-03-10T18:45:58.000Z | 2021-08-16T13:56:48.000Z | // Given a piecewise affine tranformation from an image plane (I) to
// another plane (L) and a label map on L, find for each pixel in I,
// the corresponding label. Label 0 is assigned for undefined pixels.
// If a mask is also provided, then a label is assigned only if the
// transform id in the mask is equal to the piecewise transform id
// for the pixel.
//
// Shiv N. Vitaladevuni
// Janelia Farm Research Campus, HHMI
// vitaladevunis@janelia.hhmi.org
//
// v0 04072009 init. code
//
#include <mex.h>
#include <math.h>
#include <algorithm>
#define M_PI_2 1.57079632679489661923
#define M_PI 3.14159265358979323846
#define MIN(A,B) ((A)<(B)?(A):(B))
#define MAX(A,B) ((A)>(B)?(A):(B))
void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[]){
mexPrintf("START: get_label_piecewise_affine_transformation_mask\n");
if(nrhs==0){
if(nlhs==1){
plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
*mxGetPr(plhs[0]) = 1;
return;
}
mexPrintf("Usage mapped_label = get_label_piecewise_affine_transformation_mask(label_map, transform_id_map, transforms, mask);\n");
mexPrintf("input params:\n");
mexPrintf("\t1. label map that is to be mapped by the piecewise affine transformation PxQ double\n");
mexPrintf("\t2. transformation ids for the piecewise affine transform MxN uint32\n");
mexPrintf("\t3. list of affine transforms 6xT double\n");
mexPrintf("\t4. default value scalar double\n");
mexPrintf("\t5. mask with transformation ids MxN uint32 (optional)\n");
mexPrintf("output:\n");
mexPrintf("\t1. mapped labels PxQ double\n");
return;
}
if(nrhs<3 || nrhs>6){
mexErrMsgTxt("Wrong number of inputs\n");
return;
}
int numDim = mxGetNumberOfDimensions(prhs[0]);
if(numDim>2){
mexErrMsgTxt("Wrong no. of dimensions for arg. 1\n");
return;
}
const mxArray * label_map_mx = prhs[0];
const mxArray * transform_map_mx = prhs[1];
const mxArray * transforms_mx = prhs[2];
const mxArray * default_value_mx = NULL;
if(nrhs>=4)
default_value_mx = prhs[3];
bool is_masked = false;
const mxArray * mask_mx = NULL;
if(nrhs>=5){
is_masked = true;
mask_mx = prhs[4];
}
const int * sizeCanvas;
sizeCanvas = mxGetDimensions(label_map_mx);
int width_canvas = sizeCanvas[1], height_canvas = sizeCanvas[0];
mexPrintf("width_canvas:%d, height_canvas:%d\n", width_canvas, height_canvas);
const int * sizeImage;
sizeImage = mxGetDimensions(transform_map_mx);
int width_image = sizeImage[1], height_image = sizeImage[0];
mexPrintf("width_image:%d, height_image:%d\n", width_image, height_image);
double * label_map = mxGetPr(label_map_mx);
unsigned int * transform_map = (unsigned int *) mxGetPr(transform_map_mx);
double * transforms = mxGetPr(transforms_mx);
double default_value = 0;
if(default_value_mx!=NULL)
default_value = * mxGetPr(default_value_mx);
unsigned int * mask = NULL;
if(is_masked)
mask = (unsigned int *) mxGetPr(mask_mx);
plhs[0] = mxCreateNumericMatrix(height_image, width_image, mxDOUBLE_CLASS, mxREAL);
{
double * mapped_label = mxGetPr(plhs[0]);
int x, y;
unsigned int transform_id, * t;
double * transform;
t = transform_map;
int x1, y1;
for(x=0; x<width_image; x++){
for(y=0; y<height_image; y++, t++){
mapped_label[x*height_image+y] = default_value;
transform_id = *t;
if(transform_id<=0)
continue;
transform_id--; // 0 indexed
transform = transforms + 6*transform_id; // affine transforms
x1 = (int)(transform[0]*(double)(x+1) + transform[2]*(double)(y+1) + transform[4] - 1);
y1 = (int)(transform[1]*(double)(x+1) + transform[3]*(double)(y+1) + transform[5] - 1);
// mexPrintf("x:%d, y:%d -> x1:%d, y1:%d\n", x, y, x1, y1);
if(x1<0 || x1>=width_canvas || y1<0 || y1>=height_canvas)
continue;
if(is_masked)
if(mask[x1*height_canvas+y1]!=transform_id+1)
continue;
mapped_label[x*height_image+y] = label_map[x1*height_canvas+y1];
}
}
}
mexPrintf("STOP: get_label_piecewise_affine_transformation_mask\n");
return;
}
| 34.95935 | 139 | 0.65 | [
"transform"
] |
85911650d4bd88492fdf8185de20e9d9ca80bece | 416 | cpp | C++ | Growtopia/Global_Variable.cpp | eyupware/GrowTopia-PS | 93cdc7da41f251acb455982e0a6f4ade2a77f231 | [
"Apache-2.0"
] | null | null | null | Growtopia/Global_Variable.cpp | eyupware/GrowTopia-PS | 93cdc7da41f251acb455982e0a6f4ade2a77f231 | [
"Apache-2.0"
] | null | null | null | Growtopia/Global_Variable.cpp | eyupware/GrowTopia-PS | 93cdc7da41f251acb455982e0a6f4ade2a77f231 | [
"Apache-2.0"
] | 1 | 2021-08-15T09:59:28.000Z | 2021-08-15T09:59:28.000Z | #include "Global_Variable.h"
#include "stdafx.h"
#include <vector>
#include <string>
using namespace std;
vector<string> blacklistedName = {
"prn", "con", "aux", "nul",
"com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9",
"lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"
};
vector<ENetPeer*> peers = {};
WorldDB worldDB;
uint32_t itemsDatHash = 0; | 23.111111 | 74 | 0.588942 | [
"vector"
] |
85951545b4a22b11afe86a0fc39791604dfbf03b | 3,267 | cpp | C++ | handsome/cpp_src/main.cpp | bracket/handsome | c93d34f94d0eea24f5514efc9bc423eb28b44a6b | [
"BSD-2-Clause"
] | null | null | null | handsome/cpp_src/main.cpp | bracket/handsome | c93d34f94d0eea24f5514efc9bc423eb28b44a6b | [
"BSD-2-Clause"
] | null | null | null | handsome/cpp_src/main.cpp | bracket/handsome | c93d34f94d0eea24f5514efc9bc423eb28b44a6b | [
"BSD-2-Clause"
] | null | null | null | #include <Bezier.hpp>
#include <BilinearPatch.hpp>
#include <BitmapWriter.hpp>
#include <CoonsPatch.hpp>
#include <CurveSubdivider.hpp>
#include <Filter.hpp>
#include <Kernel.hpp>
#include <Line.hpp>
#include <Sample.hpp>
#include <SampleBuffer.hpp>
#include <shade.hpp>
#include <Shader.hpp>
#include <SurfaceSubdivider.hpp>
#include <TileCache.hpp>
#include <Vec.hpp>
#include <iostream>
struct Vertex {
typedef float ScalarType;
Vec4 rhw_position;
Vec2 uv;
};
inline std::ostream & operator << (std::ostream & out, Vertex const & v) {
out << v.rhw_position << std::endl;
out << v.uv << std::endl;
return out;
}
template <>
struct interpolate_impl<Vertex> {
static inline Vertex call(
float const & t,
Vertex const & left,
Vertex const & right
)
{
return {
interpolate(t, left.rhw_position, right.rhw_position),
interpolate(t, left.uv, right.uv)
};
}
};
inline Vec4 rhw_position(Vertex const & vertex) {
return vertex.rhw_position;
}
template <class OutputIterator>
struct splay_impl<OutputIterator, Vertex> {
static inline void call(
OutputIterator out,
Vertex const & vertex,
Vec4 const & v
)
{
*out++ = Vertex({
vertex.rhw_position - v,
Vec2(vertex.uv.x(), 0.0)
});
*out++ = Vertex({
vertex.rhw_position,
Vec2(vertex.uv.x(), .5)
});
*out++ = Vertex({
vertex.rhw_position + v,
Vec2(vertex.uv.x(), 1.0)
});
}
};
template <class T>
inline T square(T const & t) { return t * t; }
inline float wrap(float f) { return f - floorf(f); }
struct Shader {
void operator () (Sample & out, Fragment<Vertex> const & frag) const {
float intensity = wrap(50.0f * (frag.vertex.uv.x() - frag.vertex.uv.y()));
Vec4 c = interpolate(
intensity,
Vec4(255 / 255.0f, 152 / 255.0f, 6 / 255.0f, 1),
Vec4(212 / 255.0f, 0 /255.0f, 4 / 255.0f, 1)
);
out.accumulate_color(c);
}
};
int main() {
TileCache cache(16, 4);
typedef Bezier<Vertex> CurveType;
typedef UniformCoonsPatchTraits<CurveType> TraitsType;
typedef CoonsPatch<TraitsType> SurfaceType;
CurveType left(
{ Vec4(0, 0, 1, 1), Vec2(0, 0) },
{ Vec4(0, 512, 1, 1), Vec2(0, 1.0 / 3) },
{ Vec4(256, 768, 1, 1), Vec2(0, 2.0 / 3) },
{ Vec4(512, 512, 1, 1), Vec2(0, 1) }
);
CurveType top(
{ Vec4(512, 512, 1, 1), Vec2(0, 1) },
{ Vec4(768, 512, 1, 1), Vec2(1.0 / 3, 1) },
{ Vec4(768, 768, 1, 1), Vec2(2.0 / 3, 1) },
{ Vec4(1024, 1024, 1, 1), Vec2(1, 1) }
);
CurveType bottom(
{ Vec4(0, 0, 1, 1), Vec2(0, 0) },
{ Vec4(256, 0, 1, 1), Vec2(1.0 / 3, 0) },
{ Vec4(512, 256, 1, 1), Vec2(2.0 / 3, 0) },
{ Vec4(768, 256, 1, 1), Vec2(1, 0) }
);
CurveType right(
{ Vec4(768, 256, 1, 1), Vec2(1, 0) },
{ Vec4(1024, 512, 1, 1), Vec2(1, 1.0 / 3) },
{ Vec4(1024, 768, 1, 1), Vec2(1, 2.0 / 3) },
{ Vec4(1024, 1024, 1, 1), Vec2(1, 1) }
);
SurfaceType surface(left, right, bottom, top);
SurfaceSubdivider<SurfaceType> subdivider(surface);
MicropolygonMesh<Vertex> * mesh = subdivider.get_mesh();
shade(*mesh, cache, Shader());
SampleBuffer kernel = make_box_kernel(
cache.get_sample_rate(), cache.get_sample_rate(),
square(1.0f / static_cast<float>(cache.get_sample_rate()))
);
SampleBuffer out(1024, 1024);
convolve_into(out, cache, kernel, 1);
write_bitmap("out.bmp", out);
return 0;
}
| 22.22449 | 76 | 0.628711 | [
"mesh"
] |
85a1d07034cb7f84296f1033cdf53ccbcb40424d | 15,898 | cpp | C++ | src/lib/Unidraw/link.cpp | emer/iv | e2ecb3acd834b8764c8582753cc86afcc4281af5 | [
"BSD-3-Clause"
] | null | null | null | src/lib/Unidraw/link.cpp | emer/iv | e2ecb3acd834b8764c8582753cc86afcc4281af5 | [
"BSD-3-Clause"
] | null | null | null | src/lib/Unidraw/link.cpp | emer/iv | e2ecb3acd834b8764c8582753cc86afcc4281af5 | [
"BSD-3-Clause"
] | null | null | null | #ifdef HAVE_CONFIG_H
#include <../../config.h>
#endif
/*
* Copyright (c) 1990, 1991 Stanford University
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of Stanford not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. Stanford makes no representations about
* the suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*
* STANFORD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
* IN NO EVENT SHALL STANFORD BE LIABLE FOR ANY SPECIAL, 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.
*/
/*
* Link component definitions.
*/
#include <ivstream.h>
#include <Unidraw/catalog.h>
#include <Unidraw/classes.h>
#include <Unidraw/clipboard.h>
#include <Unidraw/editor.h>
#include <Unidraw/globals.h>
#include <Unidraw/iterator.h>
#include <Unidraw/manips.h>
#include <Unidraw/selection.h>
#include <Unidraw/statevars.h>
#include <Unidraw/unidraw.h>
#include <Unidraw/viewer.h>
#include <Unidraw/Commands/edit.h>
#include <Unidraw/Commands/macro.h>
#include <Unidraw/Commands/transforms.h>
#include <Unidraw/Components/link.h>
#include <Unidraw/Components/pin.h>
#include <Unidraw/Graphic/lines.h>
#include <Unidraw/Graphic/picture.h>
#include <Unidraw/Tools/tool.h>
#include <InterViews/event.h>
#include <IV-2_6/InterViews/rubgroup.h>
#include <IV-2_6/InterViews/rubline.h>
#include <InterViews/transformer.h>
#include <IV-2_6/_enter.h>
#include <math.h>
#include <stdlib.h>
/*****************************************************************************/
ClassId LinkComp::GetClassId () { return LINK_COMP; }
boolean LinkComp::IsA (ClassId id) {
return LINK_COMP == id || GraphicComp::IsA(id);
}
static void InitLine (Line* line, float x0, float y0, float x1, float y1) {
Transformer* t = new Transformer(x1-x0, 0, 0, y1-y0, x0, y0);
line->SetTransformer(t);
Unref(t);
}
Component* LinkComp::Copy () {
LinkComp* copy = new LinkComp((Line*) GetLine()->Copy());
*copy->GetGraphic() = *GetGraphic();
return copy;
}
LinkComp::LinkComp (Line* line) {
if (line != nil) {
Coord x0, y0, x1, y1;
float fx0, fy0, fx1, fy1;
line->GetOriginal(x0, y0, x1, y1);
Transformer* t = line->GetTransformer();
Graphic* parent = new Picture(line);
parent->SetTransformer(nil);
if (t == nil) {
fx0 = x0; fy0 = y0; fx1 = x1; fy1 = y1;
} else {
t->Transform(float(x0), float(y0), fx0, fy0);
t->Transform(float(x1), float(y1), fx1, fy1);
}
delete line;
line = new Line(0, 0, 1, 1);
InitLine(line, fx0, fy0, fx1, fy1);
PinGraphic* pg1 = new PinGraphic;
PinGraphic* pg2 = new PinGraphic;
pg1->SetBrush(psnonebr);
pg2->SetBrush(psnonebr);
pg1->Translate(fx0, fy0);
pg2->Translate(fx1, fy1);
_conn1 = new PinComp(pg1);
_conn2 = new PinComp(pg2);
parent->Append(line, pg1, pg2);
SetGraphic(parent);
}
}
void LinkComp::Interpret (Command* cmd) {
if (cmd->IsA(DELETE_CMD) || cmd->IsA(CUT_CMD)) {
_conn1->Interpret(cmd);
_conn2->Interpret(cmd);
} else {
GraphicComp::Interpret(cmd);
}
}
void LinkComp::Uninterpret (Command* cmd) {
if (cmd->IsA(DELETE_CMD) || cmd->IsA(CUT_CMD)) {
_conn2->Uninterpret(cmd);
_conn1->Uninterpret(cmd);
} else {
GraphicComp::Uninterpret(cmd);
}
}
void LinkComp::Read (istream& in) {
GraphicComp::Read(in);
Line* line = new Line(0, 0, 1, 1);
Transformer* t = ReadTransformer(in);
line->SetTransformer(t);
Unref(t);
_conn1 = (Connector*) unidraw->GetCatalog()->ReadComponent(in);
_conn2 = (Connector*) unidraw->GetCatalog()->ReadComponent(in);
Graphic* parent = new Picture;
parent->FillBg(ReadBgFilled(in));
PSColor* fg = ReadColor(in);
PSColor* bg = ReadColor(in);
parent->SetColors(fg, bg);
parent->SetBrush(ReadBrush(in));
t = ReadTransformer(in);
parent->SetTransformer(t);
Unref(t);
parent->Append(line, _conn1->GetGraphic(), _conn2->GetGraphic());
SetGraphic(parent);
}
void LinkComp::Write (ostream& out) {
GraphicComp::Write(out);
Line* line = GetLine();
WriteTransformer(line->GetTransformer(), out);
unidraw->GetCatalog()->WriteComponent(_conn1, out);
unidraw->GetCatalog()->WriteComponent(_conn2, out);
Graphic* parent = line->Parent();
WriteBgFilled(parent->BgFilled(), out);
WriteColor(parent->GetFgColor(), out);
WriteColor(parent->GetBgColor(), out);
WriteBrush(parent->GetBrush(), out);
WriteTransformer(parent->GetTransformer(), out);
}
void LinkComp::First (Iterator& i) { i.SetValue(_conn1); }
void LinkComp::Last (Iterator& i) { i.SetValue(_conn2); }
boolean LinkComp::Done (Iterator i) { return i.GetValue() == nil; }
void LinkComp::Next (Iterator& i) {
void* v = i.GetValue();
if (v == nil) {
i.SetValue(_conn1);
} else if (v == _conn1) {
i.SetValue(_conn2);
} else {
i.SetValue(nil);
}
}
void LinkComp::Prev (Iterator& i) {
void* v = i.GetValue();
if (v == nil) {
i.SetValue(_conn2);
} else if (v == _conn1) {
i.SetValue(nil);
} else {
i.SetValue(_conn1);
}
}
GraphicComp* LinkComp::GetComp (Iterator i) {
return (GraphicComp*) i.GetValue();
}
void LinkComp::SetComp (GraphicComp* gc, Iterator& i) { i.SetValue(gc); }
void LinkComp::Update () {
float fx0, fy0, fx1, fy1;
Transformer* t1 = _conn1->GetGraphic()->GetTransformer();
Transformer* t2 = _conn2->GetGraphic()->GetTransformer();
t1->Transform(0., 0., fx0, fy0);
t2->Transform(0., 0., fx1, fy1);
InitLine(GetLine(), fx0, fy0, fx1, fy1);
Notify();
}
Line* LinkComp::GetLine () {
Iterator i;
Graphic* gr = GetGraphic();
gr->First(i);
return (Line*) gr->GetGraphic(i);
}
void LinkComp::SetMobility (Mobility m) {
_conn1->SetMobility(m);
_conn2->SetMobility(m);
}
void LinkComp::GetConnectors (Connector*& c1, Connector*& c2) {
c1 = _conn1;
c2 = _conn2;
}
LinkComp::~LinkComp () {
Graphic* parent = GraphicComp::GetGraphic();
Graphic* g1 = _conn1->GetGraphic();
Graphic* g2 = _conn2->GetGraphic();
parent->Remove(g1);
parent->Remove(g2);
delete _conn1;
delete _conn2;
}
/****************************************************************************/
LinkComp* LinkView::GetLinkComp () { return (LinkComp*) GetSubject(); }
ClassId LinkView::GetClassId () { return LINK_VIEW; }
boolean LinkView::IsA (ClassId id) {
return LINK_VIEW == id || GraphicView::IsA(id);
}
LinkView::LinkView (LinkComp* subj) : GraphicView(subj) {
_connView1 = _connView2 = nil;
}
void LinkView::Update () {
LinkComp* linkComp = GetLinkComp();
Graphic* link = GetGraphic();
Graphic* line = GetLine();
Graphic* subjLine = linkComp->GetLine();
IncurDamage(line);
*line = *subjLine;
*link = *linkComp->GetGraphic();
IncurDamage(line);
EraseHandles();
}
void LinkView::CreateHandles () {
Coord x[2], y[2];
Viewer* v = GetViewer();
if (v != nil) {
GetEndpoints(x[0], y[0], x[1], y[1]);
_handles = new RubberHandles(nil, nil, x, y, 2, 0, HANDLE_SIZE);
v->InitRubberband(_handles);
}
}
Manipulator* LinkView::CreateLinkCompManip (
Viewer* v, Event& e, Transformer* rel, Tool* tool
) {
GraphicView* views = v->GetGraphicView();
Selection* s = v->GetSelection();
RubberGroup* rg = new RubberGroup(nil, nil);
float x, y, tx, ty;
Coord cx = 0, rad = PIN_RAD, dum1 = 0, dum2 = 0;
ConnectorView* target = views->ConnectorIntersecting(
e.x-SLOP, e.y-SLOP, e.x+SLOP, e.y+SLOP
);
s->Clear();
if (target != nil) {
target->GetConnector()->GetCenter(x, y);
rel->Transform(x, y, tx, ty);
e.x = iv26_round(tx);
e.y = iv26_round(ty);
}
if (rel != nil) {
rel->Transform(cx, dum1);
rel->Transform(rad, dum2);
rad = abs(rad - cx);
}
rg->Append(
new RubberLine(nil, nil, e.x, e.y, e.x, e.y),
new FixedPin(nil, nil, e.x, e.y, rad),
new SlidingPin(nil, nil, e.x, e.y, rad, e.x, e.y)
);
return new ConnectManip(v, rg, rel, tool);
}
Manipulator* LinkView::CreateManipulator (
Viewer* v, Event& e, Transformer* rel, Tool* tool
) {
Coord x0, y0, x1, y1;
Rubberband* rub = nil;
Manipulator* m = nil;
if (tool->IsA(GRAPHIC_COMP_TOOL)) {
m = CreateLinkCompManip(v, e, rel, tool);
} else if (tool->IsA(MOVE_TOOL)) {
GetEndpoints(x0, y0, x1, y1);
rub = new SlidingLine(nil, nil, x0, y0, x1, y1, e.x, e.y);
m = new DragManip(v, rub, rel, tool, Gravity);
} else if (tool->IsA(SCALE_TOOL)) {
GetEndpoints(x0, y0, x1, y1);
rub = new ScalingLine(nil, nil, x0, y0, x1, y1, (x0+x1)/2, (y0+y1)/2);
m = new DragManip(v, rub, rel, tool, Gravity);
} else if (tool->IsA(ROTATE_TOOL)) {
GetEndpoints(x0, y0, x1, y1);
rub = new RotatingLine(
nil, nil, x0, y0, x1, y1, (x0+x1)/2, (y0+y1)/2, e.x, e.y
);
m = new DragManip(v, rub, rel, tool, Gravity);
}
return m;
}
Command* LinkView::InterpLinkCompManip (Manipulator* m) {
Viewer* v = m->GetViewer();
Editor* ed = v->GetEditor();
GraphicView* views = v->GetGraphicView();
BrushVar* brVar = (BrushVar*) ed->GetState("BrushVar");
ConnectManip* cm = (ConnectManip*) m;
Transformer* rel = cm->GetTransformer();
RubberGroup* rg = (RubberGroup*) cm->GetRubberband();
RubberLine* rl = (RubberLine*) rg->First();
Coord x0, y0, x1, y1;
Connector* c1, *c2;
ConnectorView* target1, *target2;
MacroCmd* macro = new MacroCmd(ed);
rl->GetCurrent(x0, y0, x1, y1);
if (rel != nil) {
rel = new Transformer(rel);
rel->Invert();
}
Graphic* pg = GetGraphicComp()->GetGraphic();
Line* line = new Line(x0, y0, x1, y1, pg);
if (brVar != nil) line->SetBrush(brVar->GetBrush());
line->SetTransformer(rel);
Unref(rel);
LinkComp* linkComp = NewSubject(line);
linkComp->GetConnectors(c1, c2);
macro->Append(new PasteCmd(ed, new Clipboard(linkComp)));
target1 = views->ConnectorIntersecting(x0-SLOP, y0-SLOP, x0+SLOP, y0+SLOP);
target2 = views->ConnectorIntersecting(x1-SLOP, y1-SLOP, x1+SLOP, y1+SLOP);
if (target1 != nil) {
macro->Append(new ConnectCmd(ed, c1, target1->GetConnector()));
}
if (target2 != nil) {
macro->Append(new ConnectCmd(ed, c2, target2->GetConnector()));
}
return macro;
}
LinkComp* LinkView::NewSubject (Line* line) { return new LinkComp(line); }
Command* LinkView::InterpretManipulator (Manipulator* m) {
DragManip* dm = (DragManip*) m;
Editor* ed = dm->GetViewer()->GetEditor();
Tool* tool = dm->GetTool();
Transformer* rel = dm->GetTransformer();
Command* cmd = nil;
if (tool->IsA(GRAPHIC_COMP_TOOL)) {
cmd = InterpLinkCompManip(dm);
} else if (tool->IsA(MOVE_TOOL)) {
SlidingLine* sl;
Coord x0, y0, x1, y1, dummy1, dummy2;
float fx0, fy0, fx1, fy1;
sl = (SlidingLine*) dm->GetRubberband();
sl->GetOriginal(x0, y0, dummy1, dummy2);
sl->GetCurrent(x1, y1, dummy1, dummy2);
if (rel != nil) {
rel->InvTransform(float(x0), float(y0), fx0, fy0);
rel->InvTransform(float(x1), float(y1), fx1, fy1);
}
cmd = new MoveCmd(ed, fx1-fx0, fy1-fy0);
} else if (tool->IsA(SCALE_TOOL)) {
ScalingLine* sl = (ScalingLine*) dm->GetRubberband();
float sxy = sl->CurrentScaling();
cmd = new ScaleCmd(ed, sxy, sxy);
} else if (tool->IsA(ROTATE_TOOL)) {
RotatingLine* rl = (RotatingLine*) dm->GetRubberband();
float angle = rl->CurrentAngle() - rl->OriginalAngle();
cmd = new RotateCmd(ed, angle);
}
return cmd;
}
void LinkView::First (Iterator& i) { i.SetValue(_connView1); }
void LinkView::Last (Iterator& i) { i.SetValue(_connView2); }
boolean LinkView::Done (Iterator i) { return i.GetValue() == nil; }
void LinkView::Next (Iterator& i) {
void* v = i.GetValue();
if (v == nil) {
i.SetValue(_connView1);
} else if (v == _connView1) {
i.SetValue(_connView2);
} else {
i.SetValue(nil);
}
}
void LinkView::Prev (Iterator& i) {
void* v = i.GetValue();
if (v == nil) {
i.SetValue(_connView2);
} else if (v == _connView1) {
i.SetValue(nil);
} else {
i.SetValue(_connView1);
}
}
GraphicView* LinkView::GetView (Iterator i) {
return (GraphicView*) i.GetValue();
}
void LinkView::SetView (GraphicView* gv, Iterator& i) { i.SetValue(gv); }
void LinkView::GetEndpoints (Coord& x0, Coord& y0, Coord& x1, Coord& y1) {
Line* line = GetLine();
Transformer t;
line->GetOriginal(x0, y0, x1, y1);
line->TotalTransformation(t);
t.Transform(x0, y0);
t.Transform(x1, y1);
}
Line* LinkView::GetLine () {
Iterator i;
Graphic* gr = GetGraphic();
gr->First(i);
return (Line*) gr->GetGraphic(i);
}
Graphic* LinkView::GetGraphic () {
Graphic* gr = GraphicView::GetGraphic();
if (gr == nil) {
LinkComp* linkComp = GetLinkComp();
gr = new Picture(linkComp->GetGraphic());
gr->Append(linkComp->GetLine()->Copy());
SetGraphic(gr);
Connector* c1, *c2;
linkComp->GetConnectors(c1, c2);
_connView1 = (ConnectorView*) c1->Create(COMPONENT_VIEW);
_connView2 = (ConnectorView*) c2->Create(COMPONENT_VIEW);
c1->Attach(_connView1);
c2->Attach(_connView2);
_connView1->Update();
_connView2->Update();
gr->Append(_connView1->GetGraphic(), _connView2->GetGraphic());
}
return gr;
}
LinkView::~LinkView () {
Graphic* parent = GraphicView::GetGraphic();
Graphic* g1 = _connView1->GetGraphic();
Graphic* g2 = _connView2->GetGraphic();
parent->Remove(g1);
parent->Remove(g2);
delete _connView1;
delete _connView2;
}
/****************************************************************************/
ClassId PSLink::GetClassId () { return PS_LINK; }
boolean PSLink::IsA (ClassId id) {
return PS_LINK == id || PostScriptView::IsA(id);
}
PSLink::PSLink (LinkComp* subj) : PostScriptView(subj) { }
boolean PSLink::Definition (ostream& out) {
LinkComp* comp = (LinkComp*) GetSubject();
Graphic* link = comp->GetGraphic();
Line* line = comp->GetLine();
Transformer* link_t = link->GetTransformer();
Transformer* line_t = line->GetTransformer();
Transformer* temp_t = new Transformer(line_t);
Resource::ref(link_t);
temp_t->postmultiply(*link_t);
link->SetTransformer(temp_t);
Coord x0, y0, x1, y1;
line->GetOriginal(x0, y0, x1, y1);
out << "Begin " << MARK << " Line\n";
MinGS(out);
out << MARK << "\n";
out << x0 << " " << y0 << " " << x1 << " " << y1 << " Line\n";
out << "End\n\n";
link->SetTransformer(link_t);
Resource::unref(link_t);
Resource::unref(temp_t);
return out.good();
}
| 27.696864 | 79 | 0.604919 | [
"transform"
] |
85a89ea81bbb80ecd6154a4e2ae326087ca25966 | 23,711 | cpp | C++ | libbree/base/bree.cpp | z-ninja/nwOS | 7008c0256d5b268b6eb04c656170f7ba7ca54bb4 | [
"MIT"
] | null | null | null | libbree/base/bree.cpp | z-ninja/nwOS | 7008c0256d5b268b6eb04c656170f7ba7ca54bb4 | [
"MIT"
] | null | null | null | libbree/base/bree.cpp | z-ninja/nwOS | 7008c0256d5b268b6eb04c656170f7ba7ca54bb4 | [
"MIT"
] | null | null | null | #include <base/bree.h>
#include <thread>
namespace bree
{
enum timer_action
{
timer_action_timeout = 1 << 0,
timer_action_interval = 1 << 1,
timer_action_canceled = 1 << 2,
};
enum manager_action
{
manager_action_timer_cancel = 1 << 3,
manager_action_timer = 1 << 4,
manager_action_context_main_register = 1 << 5,
manager_action_context_register = 1 << 6,
manager_action_thread_register = 1 << 7,
manager_action_thread_unregister = 1 << 8,
manager_action_context_done = 1 << 9,
manager_action_bree_quit = 1 << 10,
manager_action_bree_closed = 1 << 11
};
struct manager_action_thread : public bree_event
{
bree_context_thread_ptr m_thread;
manager_action_thread(bree_context_thread_ptr a_thread,manager_action a_action):bree_event(a_action),m_thread(a_thread) {}
virtual~manager_action_thread() {}
};
struct timer_event : public bree_event
{
std::function<void()> m_cb;
std::chrono::steady_clock::time_point m_deadline;
int64_t m_duration;
timer_event(std::function<void()>a_cb,int64_t a_duration,timer_action a_timer_action,bree_context_ptr a_context):
bree_event(manager_action_timer|a_timer_action,a_context),m_cb(a_cb),m_deadline(),m_duration(a_duration)
{
auto now = std::chrono::steady_clock::now();
m_deadline = now+std::chrono::milliseconds(a_duration);
}
virtual~timer_event() {}
void dispatch()
{
if(m_dest != nullptr)
{
m_dest->post(m_cb,true);
}
}
};
struct timer_event_cancel : public bree_event
{
timer::timer_t m_timer_h;
timer_event_cancel(timer::timer_t a_timer_h):bree_event(manager_action_timer_cancel),m_timer_h(a_timer_h) {}
virtual~timer_event_cancel() {}
};
struct manager_context_action_register : public bree_event
{
bree_context_ptr m_context;
bree::object_unregister_callback m_clean_up_callback;
manager_context_action_register(bree_context_ptr a_context,bree::object_unregister_callback a_clean_up_callback,manager_action a_action):
bree_event(a_action),m_context(a_context),m_clean_up_callback(a_clean_up_callback)
{}
virtual~manager_context_action_register() {}
};
struct manager_context_action_event : public bree_event
{
bree_context_ptr m_context;
manager_context_action_event(bree_context_ptr a_context,manager_action a_action):bree_event(a_action),m_context(a_context)
{}
virtual~manager_context_action_event() {}
};
typedef timer_event*timer_event_ptr;
class bree_context_manager
{
private:
void work()
{
struct
{
bool operator()(timer_event_ptr a, timer_event_ptr b) const
{
return a->m_deadline < b->m_deadline;
}
} timers_sorter;
std::unique_lock<std::mutex> l_lock(m_event_mutex);
std::vector<bree_event_ptr> l_events_list;
std::map<bree_context_ptr,bree::object_unregister_callback> l_context_cache;
m_running = true;
bool l_bool_quit_event = false;
bool main_context_registerd = false;
while(m_running)
{
if(m_best_timer != nullptr)
{
auto l_now = std::chrono::steady_clock::now();
std::cv_status l_status;
if(l_now >= m_best_timer->m_deadline)
{
l_status = std::cv_status::timeout;
}
else
{
l_status = m_event_cond.wait_until(l_lock,m_best_timer->m_deadline);
}
if(l_status == std::cv_status::timeout)
{
l_lock.unlock();
if(l_bool_quit_event){
m_best_timer->m_flags |= timer_action_canceled;
}
if(m_best_timer->m_flags & timer_action_canceled)
{
/// canceled action
auto l_tm = std::find_if(m_timers_list.begin(),m_timers_list.end(),[&](const timer_event*this_timer)->bool
{
return m_best_timer == this_timer;
});
if(l_tm != m_timers_list.end())
{
m_timers_list.erase(l_tm);
delete m_best_timer;
}
else {
/// should not happen
std::cout << "WARNING:could not find timer in list to cancel" << std::endl;
}
m_best_timer = nullptr;
}
else
{
m_best_timer->dispatch();
}
if(m_best_timer != nullptr)
{
if(m_best_timer->m_flags & timer_action_interval)
{
m_best_timer->m_deadline +=std::chrono::milliseconds(m_best_timer->m_duration);
m_best_timer = nullptr;
std::sort(m_timers_list.begin(),m_timers_list.end(),timers_sorter);
}
else if(m_best_timer->m_flags & timer_action_timeout)
{
auto l_tm = std::find_if(m_timers_list.begin(),m_timers_list.end(),[&](const timer_event*this_timer)->bool
{
return m_best_timer == this_timer;
});
if(l_tm != m_timers_list.end())
{
m_timers_list.erase(l_tm);
delete m_best_timer;
}
else{
/// should not happen
std::cout << "WARNING:could not find timer in list" << std::endl;
}
m_best_timer = nullptr;
}
else
{
std::cout << "invalid event type for timer" << std::endl;
}
}
if(m_best_timer == nullptr)
{
auto l_best_timer = m_timers_list.begin();
if(l_best_timer != m_timers_list.end())
{
m_best_timer = (*l_best_timer);
}
}
}
else
{
size_t new_timers_count = 0;
while(!m_event_list.empty())
{
bree_event_ptr w_evt = m_event_list.front();
m_event_list.pop();
if(w_evt->m_flags & manager_action_timer)
{
timer_event*w_timer = dynamic_cast<timer_event*>(w_evt);
m_timers_list.push_back(w_timer);
new_timers_count++;
}
else
{
l_events_list.push_back(w_evt);
}
}
l_lock.unlock();
if(new_timers_count>0)
{
std::sort(m_timers_list.begin(),m_timers_list.end(),timers_sorter);
auto l_best_timer = m_timers_list.begin();
if(l_best_timer != m_timers_list.end())
{
m_best_timer = (*l_best_timer);
}
}
}
}
else
{
m_event_cond.wait(l_lock,[&]()->bool
{
/// while this callback is called, lock is locked so it is safe to not use lock here
return !m_running || !m_event_list.empty();
});
/// here lock is still locked by so far
size_t new_timers_count = 0;
while(!m_event_list.empty())
{
bree_event_ptr w_evt = m_event_list.front();
m_event_list.pop();
if(w_evt->m_flags & manager_action_timer)
{
timer_event*w_timer = dynamic_cast<timer_event*>(w_evt);
m_timers_list.push_back(w_timer);
new_timers_count++;
}
else
{
l_events_list.push_back(w_evt);
}
}
if(new_timers_count>0)
{
std::sort(m_timers_list.begin(),m_timers_list.end(),timers_sorter);
}
auto l_best_timer = m_timers_list.begin();
if(l_best_timer != m_timers_list.end())
{
m_best_timer = (*l_best_timer);
}
l_lock.unlock();
}
auto l_ev = l_events_list.begin();
while(l_ev != l_events_list.end())
{
bree_event_ptr w_evt = (*l_ev);
if(w_evt->m_flags & manager_action_timer_cancel)
{
timer_event_cancel*l_evt = dynamic_cast<timer_event_cancel*>(w_evt);
timer_event*l_canceled_timer = reinterpret_cast<timer_event*>(l_evt->m_timer_h);
l_canceled_timer->m_flags |= timer_action_canceled;
auto now = std::chrono::steady_clock::now() - std::chrono::milliseconds(1);
l_canceled_timer->m_deadline = now;
m_best_timer = nullptr;
std::sort(m_timers_list.begin(),m_timers_list.end(),timers_sorter);
auto l_best_timer = m_timers_list.begin();
if(l_best_timer != m_timers_list.end())
{
m_best_timer = (*l_best_timer);
}
}
else if(w_evt->m_flags & manager_action_context_register)
{
manager_context_action_register*l_evt = dynamic_cast<manager_context_action_register*>(w_evt);
if(main_context_registerd&&m_context != nullptr)
{
l_evt->m_context->to_object();
context::register_object(m_context,l_evt->m_context->to_object(),l_evt->m_clean_up_callback);
}
else
{
if(l_context_cache.find(l_evt->m_context) == l_context_cache.end())
{
l_context_cache.insert(std::make_pair(l_evt->m_context,l_evt->m_clean_up_callback));
}
}
}
else if(w_evt->m_flags & manager_action_context_main_register)
{
manager_context_action_event*l_evt = dynamic_cast<manager_context_action_event*>(w_evt);
m_context = l_evt->m_context;
auto l_mc = l_context_cache.find(m_context);
if(l_mc != l_context_cache.end())
{
m_main_context_clean_up_callback = l_mc->second;
l_context_cache.erase(l_mc);
main_context_registerd = true;
}
l_mc = l_context_cache.begin();
while(l_mc != l_context_cache.end())
{
register_context(l_mc->first,l_mc->second);
l_context_cache.erase(l_mc);
l_mc = l_context_cache.begin();
}
}
else if(w_evt->m_flags & manager_action_thread_register)
{
manager_action_thread*l_evt = dynamic_cast<manager_action_thread*>(w_evt);
if(l_evt->m_thread != nullptr)
{
if(std::find(m_threads_list.begin(),m_threads_list.end(),l_evt->m_thread)== m_threads_list.end())
{
m_threads_list.push_back(l_evt->m_thread);
}
}
}
else if(w_evt->m_flags & manager_action_thread_unregister)
{
manager_action_thread*l_evt = dynamic_cast<manager_action_thread*>(w_evt);
if(l_evt->m_thread != nullptr)
{
auto l_th = std::find(m_threads_list.begin(),m_threads_list.end(),l_evt->m_thread);
if(l_th != m_threads_list.end())
{
if((*l_th)->m_thread.joinable()){
(*l_th)->m_thread.join();
}
m_threads_list.erase(l_th);
}
}
if(l_bool_quit_event)
{
if(m_threads_list.size() == 0)
{
m_running = false;
}
}
}
else if(w_evt->m_flags & manager_action_context_done)
{
if(l_bool_quit_event)
{
if(m_threads_list.size() == 0)
{
m_running = false;
}
}
m_main_context_clean_up_callback(m_context);
}
else if(w_evt->m_flags & manager_action_bree_quit)
{
auto l_tm = m_timers_list.begin();
while(l_tm != m_timers_list.end())
{
delete (*l_tm);
m_timers_list.erase(l_tm);
l_tm = m_timers_list.begin();
}
l_bool_quit_event = true;
m_best_timer = nullptr;
m_context->stop();
}
l_events_list.erase(l_ev);
l_ev = l_events_list.begin();
delete w_evt;
}
l_lock.lock();
}
m_flags |= manager_action_bree_closed;
l_lock.unlock();
while(!m_event_list.empty())
{
bree_event_ptr w_evt = m_event_list.front();
m_event_list.pop();
l_events_list.push_back(w_evt);
}
auto l_ev = l_events_list.begin();
while(l_ev != l_events_list.end())
{
bree_event_ptr w_evt = (*l_ev);
l_events_list.erase(l_ev);
l_ev = l_events_list.begin();
delete w_evt;
}
}
public:
int&m_argc;
char **&m_argv;
bree_context_ptr m_context;
bree::object_unregister_callback m_main_context_clean_up_callback;
bree_context_manager(int&a_argc,char**&a_argv,bree_context_ptr a_context):m_argc(a_argc),
m_argv(a_argv),m_context(a_context),m_main_context_clean_up_callback(nullptr),
/** private initialization */
m_running(false),m_event_mutex(),m_event_cond(),m_timers_list(),m_threads_list(),
m_best_timer(nullptr),m_thread([&]()->void
{
work();
})
{
if(m_context == nullptr)
{
m_context = bree::context::context_new();
}
m_context->m_flags |= bree::context_flags_main;
this_thread::context = m_context;
instance = this;
manager_context_action_event* l_evt = new manager_context_action_event(m_context,manager_action_context_main_register);
push_event(l_evt);
}
~bree_context_manager()
{
}
static bool push_event(bree_event_ptr a_event)
{
if(instance != nullptr)
{
{
std::unique_lock<std::mutex> l_lock(instance->m_event_mutex);
if(m_flags & manager_action_bree_closed)
{
l_lock.unlock();
delete a_event;
return false;
}
m_event_list.push(a_event);
}
instance->m_event_cond.notify_one();
}
else
{
if(m_flags & manager_action_bree_closed)
{
delete a_event;
return false;
}
m_event_list.push(a_event);
}
return true;
}
static bool register_context(bree_context_ptr a_context,bree::object_unregister_callback a_cb)
{
/// event
manager_context_action_register* l_evt = new manager_context_action_register(a_context,a_cb,manager_action_context_register);
return push_event(l_evt);
}
static void bree_init(int&a_argc,char**&a_argv,bree_context_ptr a_context)
{
if(a_context != nullptr)
{
a_context->m_flags |= bree::context_flags_main;
}
static bree_context_manager manager(a_argc,a_argv,a_context);
}
static void bree_run()
{
if(instance != nullptr)
{
std::unique_lock<std::mutex> l_lock(instance->m_event_mutex);
if(m_flags & manager_action_bree_closed)
{
l_lock.unlock();
return;
}
l_lock.unlock();
instance->m_context->run();
try{
if(instance->m_thread.joinable())
{
instance->m_thread.join();
}
}catch(std::exception&ex){
std::cout << "timer thread join exception: " << ex.what() << std::endl;
/// should never happen
}
}
this_thread::context = nullptr;
}
static void bree_exit(int a_exit)
{
s_exit_code = a_exit;
push_event(new bree_event(manager_action_bree_quit));
}
static void interval_callback(std::function<bool()>a_cb,timer::timer_t a_handle)
{
if(a_cb())
{
bree_context_manager::cancel(a_handle);
}
}
static timer::timer_t timeout(bree_context_ptr a_context,std::function<void()>a_cb,int64_t a_milliseconds)
{
if(a_context == nullptr)
{
if(instance == nullptr|| instance->m_context == nullptr)
{
return nullptr;
}
a_context = instance->m_context;
}
timer_event_ptr l_evt = new timer_event(a_cb,a_milliseconds,timer_action_timeout,a_context);
timer::timer_t l_timer_h = reinterpret_cast<timer::timer_t>(l_evt);
push_event(l_evt);
return l_timer_h;
}
static timer::timer_t interval(bree_context_ptr a_context,std::function<bool()>a_cb,int64_t a_milliseconds)
{
if(a_context == nullptr)
{
if(instance == nullptr|| instance->m_context == nullptr)
{
return nullptr;
}
a_context = instance->m_context;
}
timer_event_ptr l_evt = new timer_event(nullptr,a_milliseconds,timer_action_interval,a_context);
timer::timer_t l_timer_h = reinterpret_cast<timer::timer_t>(l_evt);
std::function<void()> l_cb = std::bind(&bree_context_manager::interval_callback,a_cb,l_timer_h);
l_evt->m_cb = l_cb;
push_event(l_evt);
return l_timer_h;
}
static void cancel(bree::timer::timer_t a_timer)
{
timer_event_cancel*l_evt = new timer_event_cancel(a_timer);
push_event(l_evt);
}
static bree_context_manager*instance;
static std::queue<bree_event_ptr> m_event_list;
static int m_flags;
static int s_exit_code;
private:
bool m_running;
std::mutex m_event_mutex;
std::condition_variable m_event_cond;
std::vector<timer_event_ptr> m_timers_list;
std::vector<bree_context_thread_ptr> m_threads_list;
timer_event_ptr m_best_timer;
std::thread m_thread;
};
bree_context_manager* bree_context_manager::instance = nullptr;
std::queue<bree_event_ptr> bree_context_manager::m_event_list;
int bree_context_manager::m_flags = 0;
int bree_context_manager::s_exit_code = 0;
BREE_PUBLIC void bree_init(int&a_argc,char**&a_argv,bree_context_ptr a_context)
{
bree_context_manager::bree_init(a_argc,a_argv,a_context);
}
BREE_PUBLIC void bree_run()
{
bree_context_manager::bree_run();
}
BREE_PUBLIC void bree_exit(int a_exit)
{
bree_context_manager::bree_exit(a_exit);
}
BREE_PUBLIC int bree_exit_code()
{
return bree_context_manager::s_exit_code;
}
namespace timer
{
BREE_PUBLIC timer_t timeout(bree_context_ptr a_context,std::function<void()>a_cb,int64_t a_milliseconds)
{
return bree_context_manager::timeout(a_context,a_cb,a_milliseconds);
}
BREE_PUBLIC timer_t interval(bree_context_ptr a_context,std::function<bool()>a_cb,int64_t a_milliseconds)
{
return bree_context_manager::interval(a_context,a_cb,a_milliseconds);
}
BREE_PUBLIC void cancel(timer_t a_timer)
{
bree_context_manager::cancel(a_timer);
}
}/// namespace timer
BREE_PUBLIC int&get_argc()
{
return bree_context_manager::instance->m_argc;
}
BREE_PUBLIC char**&get_argv()
{
return bree_context_manager::instance->m_argv;
}
namespace context
{
namespace global
{
BREE_PUBLIC void register_context(bree_context_ptr a_context,bree::object_unregister_callback a_cb)
{
bree_context_manager::register_context(a_context,a_cb);
}
BREE_PUBLIC void main_context_done(bree_context_ptr a_context)
{
if(bree_context_manager::instance != nullptr)
{
bree_context_manager::instance->push_event(new manager_context_action_event(a_context,bree::manager_action_context_done));
}
}
BREE_PUBLIC void register_thread(bree_context_thread_ptr a_thread)
{
if(bree_context_manager::instance != nullptr)
{
bree_context_manager::instance->push_event(new manager_action_thread(a_thread,manager_action_thread_register));
}
}
BREE_PUBLIC void unregister_thread(bree_context_thread_ptr a_thread)
{
if(bree_context_manager::instance != nullptr)
{
bree_context_manager::instance->push_event(new manager_action_thread(a_thread,manager_action_thread_unregister));
}
}
}/// namespace global
}/// namespace context
namespace main_thread
{
BREE_PUBLIC bree::timer::timer_t timeout(std::function<void()>a_cb,int64_t a_milliseconds)
{
return bree::bree_context_manager::timeout(nullptr,a_cb,a_milliseconds);
}
BREE_PUBLIC bree::timer::timer_t interval(std::function<bool()>a_cb,int64_t a_milliseconds)
{
return bree::bree_context_manager::interval(nullptr,a_cb,a_milliseconds);
}
}
namespace this_thread
{
BREE_PUBLIC bree::timer::timer_t timeout(std::function<void()>a_cb,int64_t a_milliseconds)
{
return bree::bree_context_manager::timeout(context,a_cb,a_milliseconds);
}
BREE_PUBLIC bree::timer::timer_t interval(std::function<bool()>a_cb,int64_t a_milliseconds)
{
return bree::bree_context_manager::interval(context,a_cb,a_milliseconds);
}
}/// namespace this_thread
}/// namespace bree
| 36.2 | 141 | 0.535152 | [
"vector"
] |
85b023ddfadfbb55417222ea5b4b9676822b5aa6 | 400 | cpp | C++ | cpp/test/testReadIntoArray.cpp | anthonyf996/couch-potatoes-sql-backend | ed9ad2048989c09181c059590b651475a3d581c3 | [
"MIT"
] | null | null | null | cpp/test/testReadIntoArray.cpp | anthonyf996/couch-potatoes-sql-backend | ed9ad2048989c09181c059590b651475a3d581c3 | [
"MIT"
] | null | null | null | cpp/test/testReadIntoArray.cpp | anthonyf996/couch-potatoes-sql-backend | ed9ad2048989c09181c059590b651475a3d581c3 | [
"MIT"
] | null | null | null | #include <iostream>
#include "testReadIntoArray.hpp"
int main( int argc, char* argv[] ) {
--argc;
if ( argc != 1 ) {
std::cerr << "Usage: ./rmComments ( input file )\n";
return 1;
}
std::vector<std::string> list = readIntoArray( argv[1] );
std::vector<std::string>::iterator itr = list.begin();
for ( ; itr != list.end(); itr++ ) {
std::cout << *itr;
}
return 0;
}
| 18.181818 | 59 | 0.5625 | [
"vector"
] |
85b7a5176370a6d4c7e85948c54f6939150278df | 1,171 | hpp | C++ | querier/QuerierInterface.hpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | querier/QuerierInterface.hpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | querier/QuerierInterface.hpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | #ifndef QUERIERINTERFACE_H
#define QUERIERINTERFACE_H
#include <deque>
#include <initializer_list>
#include "base/Error.hpp"
#include "label/Label.hpp"
#include "label/MatcherInterface.hpp"
#include "querier/SeriesSetInterface.hpp"
namespace tsdb {
namespace querier {
class QuerierInterface {
public:
// Return nullptr when no series match.
virtual std::unique_ptr<::tsdb::querier::SeriesSetInterface> select(
const std::vector<::tsdb::label::MatcherInterface*>& l) const = 0;
// LabelValues returns all SORTED values for a label name.
virtual std::vector<std::string> label_values(const std::string& s) const = 0;
// label_values_for returns all potential values for a label name.
// under the constraint of another label.
// virtual std::deque<boost::string_ref> label_values_for(const std::string &
// s, const label::Label & label) const=0;
// label_names returns all the unique label names present in the block in
// sorted order.
virtual std::vector<std::string> label_names() const = 0;
virtual error::Error error() const = 0;
virtual ~QuerierInterface() = default;
};
} // namespace querier
} // namespace tsdb
#endif | 29.275 | 80 | 0.730999 | [
"vector"
] |
85ba7d678073c36060aa99d108c7676c69d2a5a9 | 2,990 | cpp | C++ | c++/0167-two-sum-ii-input-array-is-sorted.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | 2 | 2019-04-13T09:55:04.000Z | 2019-05-16T12:47:40.000Z | c++/0167-two-sum-ii-input-array-is-sorted.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | null | null | null | c++/0167-two-sum-ii-input-array-is-sorted.cpp | aafulei/leetcode | e3a0ef9c912abf99a1d6e56eff8802ba44b0057d | [
"MIT"
] | null | null | null | // 22/06/09 = Thu
// 22/03/15 = Tue
// 19/02/14 = Thu
// 167. Two Sum II - Input Array is Sorted [Medium]
// Given a 1-indexed array of integers numbers that is already sorted in
// non-decreasing order, find two numbers such that they add up to a specific
// target number. Let these two numbers be numbers[index1] and numbers[index2]
// where 1 <= index1 < index2 <= numbers.length.
// Return the indices of the two numbers, index1 and index2, added by one as an
// integer array [index1, index2] of length 2.
// The tests are generated such that there is exactly one solution. You may not
// use the same element twice.
// Your solution must use only constant extra space.
// Example 1:
// Input: numbers = [2,7,11,15], target = 9
// Output: [1,2]
// Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We
// return [1, 2].
// Example 2:
// Input: numbers = [2,3,4], target = 6
// Output: [1,3]
// Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We
// return [1, 3].
// Example 3:
// Input: numbers = [-1,0], target = -1
// Output: [1,2]
// Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We
// return [1, 2].
// Constraints:
// 2 <= numbers.length <= 3 * 10^4
// -1000 <= numbers[i] <= 1000
// numbers is sorted in non-decreasing order.
// -1000 <= target <= 1000
// The tests are generated such that there is exactly one solution.
// Related Topics:
// [Array] [Binary Search] [Two Pointers*]
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int lo = 0;
int hi = numbers.size() - 1;
while (lo != hi) {
int guess = numbers[lo] + numbers[hi];
if (guess == target) {
return {lo + 1, hi + 1};
} else if (guess < target) {
++lo;
} else {
--hi;
}
}
assert(false);
}
};
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int>::const_iterator b = numbers.cbegin();
vector<int>::const_iterator e = std::prev(numbers.cend());
while (b != e) {
int guess = *b + *e;
if (guess == target) {
int lo_index = std::distance(numbers.cbegin(), b) + 1;
int hi_index = std::distance(numbers.cbegin(), e) + 1;
return {lo_index, hi_index};
} else if (guess < target) {
++b;
} else {
--e;
}
}
assert(false);
}
};
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int>::const_iterator b = numbers.cbegin();
vector<int>::const_reverse_iterator e = numbers.crbegin();
while (std::next(b) != e.base()) {
int guess = *b + *e;
if (guess == target) {
return {static_cast<int>(std::distance(numbers.cbegin(), b)) + 1,
static_cast<int>(std::distance(e, numbers.crend()))};
} else if (guess < target) {
++b;
} else {
++e;
}
}
assert(false);
}
};
| 27.943925 | 79 | 0.585284 | [
"vector"
] |
85bb260a1e575eb54a33409c7bc3133ba46b9756 | 4,870 | cpp | C++ | example/example.cpp | MusicScience37/variant-cpp11 | 6abfaccaaa1d3ffe9119a93629a875f978683b67 | [
"MIT"
] | null | null | null | example/example.cpp | MusicScience37/variant-cpp11 | 6abfaccaaa1d3ffe9119a93629a875f978683b67 | [
"MIT"
] | null | null | null | example/example.cpp | MusicScience37/variant-cpp11 | 6abfaccaaa1d3ffe9119a93629a875f978683b67 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <iostream>
#include <string>
#include <unordered_map>
#include "variant_cpp11/variant.h"
/*!
* \brief namespace for examples of variant
*/
namespace variant_cpp11_examples {
/*!
* \brief check whether result is true
*
* \param result result of comparisons
*/
void check(bool result) {
if (!result) {
std::cout << "\nCHECK FAILED!!\n" << std::endl;
std::exit(1);
}
}
/*!
* \brief example of assigning values
*/
void assign() {
std::cout << "# Test of assigning values\n" << std::endl;
// default constructor will create an object without value
variant_cpp11::variant<int, float, std::string> obj;
// copy a value
obj = 123;
// move a value
obj = std::move(std::string("abc"));
// destructor will destroy stored values
};
/*!
* \brief example of getting values
*/
void get() {
std::cout << "# Test of getting values\n" << std::endl;
variant_cpp11::variant<float, std::string> obj("abc");
// get value
std::cout << "- string: " << obj.get<std::string>() << std::endl;
check(obj.get<std::string>() == "abc");
// wrong type will throw an exception
try {
const float val = obj.get<float>(); // this throws
std::cout << "- wrongly got value: " << val << std::endl;
check(false);
} catch (variant_cpp11::variant_error& e) {
std::cout << "- exception for wrong type: " << e.what() << std::endl;
}
// get value without exception
float* ptr_float = obj.get_if<float>();
check(ptr_float == nullptr);
std::string* ptr_string = obj.get_if<std::string>();
check(ptr_string != nullptr);
check(*ptr_string == "abc");
std::cout << std::endl;
}
/*!
* \brief example of checking types of stored values
*/
void check_type() {
std::cout << "# Test of checking types of stored values\n" << std::endl;
variant_cpp11::variant<int, float> obj(1.0F);
// check whether variant has some value
check(obj.has_value());
if (!obj) {
check(false);
}
// check with indices
std::cout << "- index of value type: " << obj.index() << std::endl;
check(obj.index() == 1);
// check with explicit type
check(!obj.has<int>());
check(obj.has<float>());
std::cout << std::endl;
}
/*!
* \brief example of copying and moving variant objects
*/
void copy_move() {
std::cout << "# Test of copying and moving variant objects\n" << std::endl;
// type for test
struct test_type {
test_type() = default;
~test_type() = default;
// copying is disabled
test_type(const test_type&) = delete;
test_type& operator=(const test_type&) = delete;
// moving is enabled
test_type(test_type&&) = default;
test_type& operator=(test_type&&) = default;
};
variant_cpp11::variant<int, test_type> obj(5);
// copy
variant_cpp11::variant<int, test_type> copied(obj);
// move
variant_cpp11::variant<int, test_type> moved(std::move(copied));
// copy for types not copyable will throw an exception
obj = test_type();
try {
variant_cpp11::variant<int, test_type> copied = obj;
std::cout << "- index wrong copied: " << obj.index() << std::endl;
check(false);
} catch (variant_cpp11::variant_error& e) {
std::cout << "- exception for types not copyable: " << e.what()
<< std::endl;
}
std::cout << std::endl;
}
/*!
* \brief example of executing functions
*/
void execute_functions() {
std::cout << "# Test of execting functions\n" << std::endl;
variant_cpp11::variant<int, std::string> obj;
struct visitor {
void operator()(int val) {
std::cout << "- int value: " << val << std::endl;
}
void operator()(std::string& val) {
std::cout << "- string value: " << val << std::endl;
// visitor can assign values
val = "abcde";
}
};
obj = 1;
obj.visit(visitor());
obj = "a";
obj.visit(visitor());
obj.visit(visitor());
std::cout << std::endl;
}
/*!
* \brief example of using hash
*/
void use_hash() {
std::cout << "# Test of using hash\n" << std::endl;
using key_type = variant_cpp11::variant<int, std::string>;
// use unordered_map which uses std::hash of variant
std::unordered_map<key_type, int> hash_map;
hash_map.emplace(1, 1);
hash_map.emplace("abc", 2);
check(hash_map.at(1) == 1);
check(hash_map.at("abc") == 2);
}
} // namespace variant_cpp11_examples
int main() {
variant_cpp11_examples::assign();
variant_cpp11_examples::get();
variant_cpp11_examples::check_type();
variant_cpp11_examples::copy_move();
variant_cpp11_examples::execute_functions();
variant_cpp11_examples::use_hash();
return 0;
}
| 25.103093 | 79 | 0.592813 | [
"object"
] |
85bcfdb4d73dd05b1a66207811bb629ea8fa1ded | 1,414 | cpp | C++ | OldSoft/Favourite Game program/favgame2.0.cpp | Keron320/Programming-Cpp | e9c1896a27be76c14b990eb6b2eb7f8f1ca0b475 | [
"MIT"
] | null | null | null | OldSoft/Favourite Game program/favgame2.0.cpp | Keron320/Programming-Cpp | e9c1896a27be76c14b990eb6b2eb7f8f1ca0b475 | [
"MIT"
] | null | null | null | OldSoft/Favourite Game program/favgame2.0.cpp | Keron320/Programming-Cpp | e9c1896a27be76c14b990eb6b2eb7f8f1ca0b475 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main(){
vector<string> game;
string choice;
string change;
int unlist = 0;
vector<string>::const_iterator iter;
cout<<"Welcome to your favorite game list!"<<endl;
while(choice != "exit"){
cout<<"Your current favourite games are: "<<endl;
sort(game.begin(),game.end());
for (iter = game.begin(); iter != game.end();++iter){
cout<<*iter<<endl;
}
cout<<"What would you like to do next,add or remove games? (add/remove)"<<endl;
cin >> choice;
if (choice == "add"){
cout<<"Insert name of the game: "<<endl;
string favouriteGame;
cin>>ws; // std::ws absorbs whitespace stuff
getline(cin,favouriteGame);
game.insert(game.begin(),favouriteGame);
}
else if (choice == "remove"){
cout<<"By number or name?"<<endl;
cin >> choice;
if(choice == "name"){
string name;
cout<<"Enter the name of the game: "<<endl;
cin>>ws;
getline(cin,name);
iter = find(game.begin(),game.end(),name);
if ( iter != game.end()){
cout<<name<<" found and removed from the list"<<endl;
game.erase(remove(game.begin(),game.end(),name),game.end());
}
}
else if ( choice == "number"){
cin>>unlist;
cout<<"Enter number from: "<<endl;
game.erase(game.begin()+(unlist-1));
}
}
}
return 0;
}
| 22.444444 | 79 | 0.596888 | [
"vector"
] |
85bf86b6b04a84d6600f3ad05667f98abcf0d91f | 875 | cpp | C++ | Problems/Backtracking/countVowelStrings.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | Problems/Backtracking/countVowelStrings.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | Problems/Backtracking/countVowelStrings.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | #include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
void helper(string &s,vector<string> &vowels,int start,int n,int &c){
if(s.length() == n){
c++;
cout<<s<<endl;
return;
}
for(int i=start;i<vowels.size();i++){
s += vowels[i];
helper(s,vowels,start,n,c);
start++;
s.pop_back();
}
}
int countVowelStrings(int n) {
int c =0;
vector<string> vowels;
vowels.push_back("a");
vowels.push_back("e");
vowels.push_back("i");
vowels.push_back("o");
vowels.push_back("u");
string s = "";
int start = 0;
helper(s,vowels,start,n,c);
return c;
}
};
int main(){
Solution s;
cout<<s.countVowelStrings(6)<<endl;
return 0;
} | 23.026316 | 73 | 0.491429 | [
"vector"
] |
85c2dad7fe0b940eb15e454f5e5e0ffe28b8e977 | 34,328 | cpp | C++ | src/mesh.cpp | zia1138/edge4d | e21a308d619c03db83ef68cf63b1637685bd2139 | [
"BSD-2-Clause"
] | 4 | 2016-05-28T07:26:31.000Z | 2019-01-31T10:18:12.000Z | src/mesh.cpp | zia1138/edge4d | e21a308d619c03db83ef68cf63b1637685bd2139 | [
"BSD-2-Clause"
] | null | null | null | src/mesh.cpp | zia1138/edge4d | e21a308d619c03db83ef68cf63b1637685bd2139 | [
"BSD-2-Clause"
] | null | null | null | #include <stdlib.h>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include "mesh.hpp"
#include "util.hpp"
namespace geom {
// Intersect two face lists. Return face index that does not match given face index.
inline int isect(int fidx, vector<int> &A, vector<int> &B) {
for(size_t i = 0; i < A.size(); i++)
for(size_t j = 0; j < B.size(); j++) if(A[i] == B[j] && A[i] != fidx) return A[i];
// Nothing found in intersection, return -1.
return -1;
}
// Compute face-face adjacencies by intersecting face lists on each vertex.
void mesh::face_adjacencies() {
for(size_t f = 0; f < faces.size(); f++) {
int v0 = faces[f].vert[0], v1 = faces[f].vert[1], v2 = faces[f].vert[2];
faces[f].adj[0] = isect(f, facelist[v0], facelist[v1]);
faces[f].adj[1] = isect(f, facelist[v0], facelist[v2]);
faces[f].adj[2] = isect(f, facelist[v1], facelist[v2]);
}
}
// Update the mesh bounding box.
void mesh::reset_range() {
x_min = numeric_limits<float>().max(); x_max = -(numeric_limits<float>().max());
y_min = numeric_limits<float>().max(); y_max = -(numeric_limits<float>().max());
z_min = numeric_limits<float>().max(); z_max = -(numeric_limits<float>().max());
for(size_t vidx = 0; vidx < vertices.size(); vidx++) {
vec3 &v = vertices[vidx].pos;
// Collect bounding box for mesh.
if(v[0] > x_max) x_max = v[0]; if(v[0] < x_min) x_min = v[0];
if(v[1] > y_max) y_max = v[1]; if(v[1] < y_min) y_min = v[1];
if(v[2] > z_max) z_max = v[2]; if(v[2] < z_min) z_min = v[2];
}
// Set the center of the mesh
x_center = x_min + (x_max - x_min) / 2; y_center = y_min + (y_max - y_min) / 2; z_center = z_min + (z_max - z_min) / 2;
centroid = compute_centroid();
// Populate verticies.
vector<vec3> vec3vert(vertices.size());
for(size_t vidx = 0; vidx < vertices.size(); vidx++) vec3vert[vidx] = vertices[vidx].pos;
PCA3(pca3, pca3_x, vec3vert); // Compute PCA of vertices.
compute_axes();
}
void mesh::compute_axes() {
// Populate verticies.
vector<vec3> vec3vert(vertices.size());
for(size_t vidx = 0; vidx < vertices.size(); vidx++) vec3vert[vidx] = vertices[vidx].pos - centroid;
// Find maximum projection onto PCA axes.
axes3.resize(3);
for(size_t i = 0; i < pca3.size(); i++) axes3[i] = pca3[i].max_mag_project(vec3vert);
}
void mesh::rebuild_adj() {
// Compute how much space is needed for the face list on each vertex.
vector<int> fadjcnt(vertices.size(), 0);
for(size_t fidx = 0; fidx < faces.size(); fidx++) {
for(int i = 0; i < 3; i++) fadjcnt[faces[fidx].vert[i]]++;
}
for(size_t vidx = 0; vidx < vertices.size(); vidx++)
if(fadjcnt[vidx] == 0) { cerr << "no adjacent face for vertex" << endl; exit(1); }
// Reserve space for each face list.
facelist.resize(vertices.size());
// Clear, if any are present.
for(size_t vidx = 0; vidx < facelist.size(); vidx++) facelist[vidx].clear();
for(size_t vidx = 0; vidx < facelist.size(); vidx++) facelist[vidx].reserve(fadjcnt[vidx]);
// Populate each face list.
for(int fidx = 0; fidx < (int)faces.size(); fidx++) {
for(int i = 0; i < 3; i++) facelist[faces[fidx].vert[i]].push_back(fidx);
}
// Intersect face lists to obtain face-face adjacencies.
face_adjacencies();
}
// Create a mesh from a vertex table and a face table.
void mesh::rebuild(vector<vec3> &vtable, vector<face> &ftable) {
faces.clear(); vertices.clear();
// Copy vertex positions.
vertices.resize(vtable.size());
// Copy mesh vertices.
for(size_t vidx = 0; vidx < vtable.size(); vidx++) vertices[vidx].pos = vtable[vidx];
// Copy verticies from face table.
faces.resize(ftable.size());
for(int fidx = 0; fidx < (int)faces.size(); fidx++) {
for(int i = 0; i < 3; i++) faces[fidx].vert[i] = ftable[fidx].vert[i];
}
rebuild_adj(); // (re)Build face adjacencies
update_meta(); // Update meta information.
}
// Compute face normals using vertex indicies.
void mesh::compute_face_normals() {
for(int fidx = 0; fidx < (int)faces.size(); fidx++) {
mesh_face &F = faces[fidx];
vec3 &v0 = vertices[F.vert[0]].pos;
vec3 &v1 = vertices[F.vert[1]].pos;
vec3 &v2 = vertices[F.vert[2]].pos;
faces[fidx].normal = ComputeNormal(v0, v1, v2);
}
}
// Computes vertex normal as the mean of the neighboring face normals.
void mesh::compute_vertex_normals() {
// Compute vertex normals.
for(size_t vidx = 0; vidx < vertices.size(); vidx++) {
vector<int> &adj = facelist[vidx]; // Get face adjacencies.
vec3 vnormal(0,0,0);
for(size_t a = 0; a < adj.size(); a++) vnormal += faces[adj[a]].normal;
float Z = (float)adj.size();
vertices[vidx].normal = (1.0f / Z) * vnormal;
vertices[vidx].normal.normalize();
}
}
// Voxelize mesh.
void mesh::volpts(vector<ivec3> &pts) {
// Create a binary volume using mesh voxelization.
int w = ceil(x_max - x_min), h = ceil(y_max - y_min), d = ceil(z_max - z_min);
ivec3 min_v(x_min, y_min, z_min);
volume8 vol(w,h,d); voxelize(vol, 0, 255, true);
for(int z = 0; z < d; z++)
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++)
if(vol(x,y,z) == 255) pts.push_back(ivec3(x,y,z) + min_v);
}
// Voxalize, but only a thin boundary along edge of mesh.
void mesh::volpts(vector<ivec3> &pts, int dthresh) {
// Create a binary volume using mesh voxelization.
int w = ceil(x_max - x_min), h = ceil(y_max - y_min), d = ceil(z_max - z_min);
ivec3 min_v(x_min, y_min, z_min);
// Voxelize
volume8 vol(w,h,d); voxelize(vol, 0, 255, true);
// Compute EDT, which allows selecting points along thin boundary.
volume32 EDT(w,h,d); EDT.ComputeEDT(vol, 0);
int dsqthresh = dthresh * dthresh;
for(int z = 0; z < d; z++)
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++) {
if(vol(x,y,z) == 255) {
if(EDT(x,y,z) <= dsqthresh) {
pts.push_back(ivec3(x,y,z) + min_v);
}
}
}
}
void mesh::volpts(vector<ivec3> &above, vector<ivec3> &below, plane3 &plane) {
vector<ivec3> pts; volpts(pts);
for(size_t p = 0; p < pts.size(); p++) {
vec3 pt_v = pts[p].to_vec3();
if(plane.pos_side(pt_v)) above.push_back(pts[p]);
else if(plane.neg_side(pt_v)) below.push_back(pts[p]);
}
}
double mesh::compute_volume(double vxd) {
/// Make sure the mesh is closed.
for(size_t fidx = 0; fidx < faces.size(); fidx++) {
if(faces[fidx].adj[0] < 0) return -1; if(faces[fidx].adj[1] < 0) return -1;
if(faces[fidx].adj[2] < 0) return -1;
}
// Create a binary volume for measurement.
int w = ceil(x_max - x_min), h = ceil(y_max - y_min), d = ceil(z_max - z_min);
// Voxelize the mesh in that volume.
volume8 vol(w,h,d); voxelize(vol, 0, 255, true);
double vxd3 = vxd * vxd * vxd, total_vol = 0;
int vcnt = 0;
// Add up the fg voxels in that small volume.
for(int z = 0; z < d; z++)
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++)
if(vol(x,y,z) == 255) {
total_vol += vxd3;
vcnt++;
}
//cout << "vol = " << vxd << "/" << vcnt << "/" << w * h * d << endl;
return total_vol;
}
// Find areas of labeled components on the mesh.
void mesh::component_areas(vector<int> &facelabels, float alpha, vector<float> &areas) {
int num_components = 0;
for(size_t i = 0; i < facelabels.size(); i++) num_components = max(num_components, facelabels[i]);
areas.resize(num_components + 1);
for(size_t a = 0; a < areas.size(); a++) areas[a] = 0;
for(size_t fidx = 0; fidx < facelabels.size(); fidx++) {
if(facelabels[fidx] >= 0) {
mesh_face &F = faces[fidx];
// This maps from voxel space to geometric space.
vec3 p0 = alpha * vertices[F.vert[0]].pos;
vec3 p1 = alpha * vertices[F.vert[1]].pos;
vec3 p2 = alpha * vertices[F.vert[2]].pos;
areas.at(facelabels[fidx]) += geom::area(p0, p1, p2);
}
}
}
// Clean components on surface image.
void mesh::clean_small_comps(vector<int> &facelabels, int num_components, int thresh) {
// Count the number of faces in each component.
vector<int> labelcnt(num_components, 0);
for(size_t i = 0; i < facelabels.size(); i++) if(facelabels[i] > 0) labelcnt.at(facelabels[i] - 1)++;
// For those with less than threshold number of faces, set
// facelabel to zero.
vector< vector<int> > comps(num_components);
for(size_t i = 0; i < facelabels.size(); i++) {
if(facelabels[i] > 0 && labelcnt[facelabels[i] - 1] < thresh) {
facelabels[i] = 0;
}
}
}
// input labels, 0 = background and do not label
// 1 = label this triangle component
// output, 0 = background and 1 - N component labels.
int mesh::label_components(vector<int> &labels) {
int num_components = 0;
for(size_t fidx = 0; fidx < labels.size(); fidx++) {
if(labels[fidx] == 1) {
dfs_label(labels, fidx, num_components+2);
num_components++;
}
}
// Subtract 1 so that labels range from [1,N].
for(size_t i = 0; i < labels.size(); i++) if(labels[i] != 0) labels[i] -= 1;
return num_components;
}
void mesh::connected_components(vector< vector<int> > &components, int min_tri) {
// Create a label for each face.
vector<int> labels(faces.size(), 1); // use 1 here to ensure all faces visited
int num_components = label_components(labels);
vector< vector<int> > components_raw(num_components);
for(size_t i = 0; i < labels.size(); i++) {
if(labels[i] > 0) { components_raw.at(labels[i] - 1).push_back(i); }
}
for(size_t i = 0; i < components_raw.size(); i++) {
if((int)components_raw[i].size() > min_tri) components.push_back(components_raw[i]);
}
}
// Label nodes in a connected component by DFS. 0 = background, 1 =
// to label, SCANNED = in queue.
void mesh::dfs_label(vector<int> &labels, int start, int label) {
const int SCANNED = -numeric_limits<int>::max();
vector<int> L; L.push_back(start);
labels[start] = SCANNED; // SCANNED = in queue
while(L.empty() == false) {
// Get current face from queue.
int cur = L.back(); L.pop_back();
labels[cur] = label; // mark as finished
// Get adjacent faces.
int *adj = faces[cur].adj;
for(int j = 0; j < 3; j++) {
if(adj[j] < 0) continue; // Skip edges that have no adjacencies.
if(labels[adj[j]] == 1) { // unvisited
labels[adj[j]] = SCANNED; // SCANNED means it's in the queue
L.push_back(adj[j]);
}
}
}
}
// Starting a given face index start, label face with labe with a
// given threshold distance.
void mesh::dfs_paint(vector<int> &facelabels, int start, int label, int dthresh) {
vector<int> L, dist; L.push_back(start); dist.push_back(0);
// Uses most negative value for labeling faces that got scanned.
const int SCANNED = -numeric_limits<int>::max(), VISITED = -numeric_limits<int>::max() + 1;
facelabels[start] = SCANNED;
vector<int> to_label;
while(L.empty() == false) {
// Get current face from queue.
int cur = L.back(); L.pop_back();
// triangle cur_tri = as_triangle(cur);
// vec3 cur_cent = cur_tri.centroid();
int cur_dist = dist.back(); dist.pop_back();
facelabels[cur] = VISITED;
to_label.push_back(cur);
if(cur_dist < dthresh) {
// Get adjacent faces.
int *adj = faces[cur].adj;
for(int j = 0; j < 3; j++) {
if(adj[j] < 0) continue; // Skip edges that have no adjacencies.
if(facelabels[adj[j]] == SCANNED) continue; // In queue, skip.
if(facelabels[adj[j]] == VISITED) continue; // Already visited, skip.
// triangle adj_tri = as_triangle(adj[j]);
// float d = geom::distance3(adj_tri.centroid(), cur_cent);
dist.push_back(cur_dist + 1);
L.push_back(adj[j]);
}
}
}
// Apply label to visited faces.
for(size_t i = 0; i < to_label.size(); i++) facelabels[to_label[i]] = label;
}
// Hash map that implements linear probing. TODO: Make this a hash table that grows.
struct entry { int vidx_mesh, vidx_sub; };
struct hash_map {
int N; entry *data;
hash_map(int Nmax) { N = Nmax; data = new entry[N]; clear(); }
~hash_map() { delete[] data; }
// if vidx_mesh = -1, then the slot is empty.
void clear() { for(int i = 0; i < N; i++) data[i].vidx_mesh = -1; }
int find(int vidx_mesh) {
int i = vidx_mesh % N;
int istart = i;
while(data[i].vidx_mesh >= 0) {
if(data[i].vidx_mesh == vidx_mesh) return data[i].vidx_sub;
else i = (i + 1) % N;
if(i == istart) return -1;
}
return -1;
}
void insert(int vidx_mesh, int vidx_sub) {
int i = vidx_mesh % N;
int istart = i;
while(data[i].vidx_mesh >= 0) {
i = (i + 1) % N;
if(i == istart) { cerr << "mesh: hashmap_out of space" << endl; exit(1); }
}
data[i].vidx_mesh = vidx_mesh; data[i].vidx_sub = vidx_sub;
}
};
// Returns a component as a mesh face table and coresponding vertex table.
void mesh::as_mesh(vector<int> &subfaces, vector<vec3> &vtable, vector<face> &ftable) {
vtable.clear(); ftable.clear();
hash_map vidx(3*subfaces.size());
for(size_t i = 0; i < subfaces.size(); i++) {
// Get face index.
int fidx = subfaces[i];
// Get vertex indicies of that face.
int v0 = faces[fidx].vert[0], v1 = faces[fidx].vert[1], v2 = faces[fidx].vert[2];
// Map those vertex indicies to vertiex indicies in the sub-mesh.
int v0sub = vidx.find(v0), v1sub = vidx.find(v1), v2sub = vidx.find(v2);
// If any of the verticies were not found in the submesh, create
// a new vertex in the submesh and save the map from the old
// vertex to the new one.
if(v0sub < 0) {
v0sub = vtable.size();
vtable.push_back(vertices[v0].pos);
vidx.insert(v0, v0sub);
}
if(v1sub < 0) {
v1sub = vtable.size();
vtable.push_back(vertices[v1].pos);
vidx.insert(v1, v1sub);
}
if(v2sub < 0) {
v2sub = vtable.size();
vtable.push_back(vertices[v2].pos);
vidx.insert(v2, v2sub);
}
// Create new face with vertex indicies in the submesh and copy the normal.
face newface;
// newface.normal = faces[fidx].normal;
newface.vert[0] = v0sub; newface.vert[1] = v1sub; newface.vert[2] = v2sub;
ftable.push_back(newface);
}
}
vec3 mesh::refine_disp(volume8 &v, int vidx, float dist, float sign) {
vec3 o = vertices[vidx].pos;
vec3 d = vertices[vidx].normal;
d = sign * d; // Normals point inward, this is weird so flip sign.
vec3 p = o; // Initially no displacement.
// Intersect volume within some threshold distance.
vector<ivec3> res; v.ray_intersect(res, o, d, dist);
if(res.size() > 0) {
// If items found, then find maximum intensity voxel.
uint8 maxI = v(res[0]); ivec3 maxpos = res[0];
for(size_t r = 1; r < res.size(); r++) {
if( v(res[r]) > maxI ) { maxI = v(res[r]); maxpos = res[r]; }
}
p[0] = float(maxpos.x()); p[1] = float(maxpos.y()); p[2] = float(maxpos.z());
}
p -= o;
return p; // Compute displacement to position.
}
// TODO: Use smooth vertex and maxI vertex add them together to get
// new position add alpha/(1-alpha) weight to smoothing vs fitting.
// Refines mesh position to match high intensity image boundaries in
// source volume v.
void mesh::refine(volume8 &v, float dist, int max_iter, float alpha, float stepsize) {
// Vertex displacements.
vector<vec3> sdisp(vertices.size());
vector<vec3> disp(vertices.size());
for(int iter = 0; iter < max_iter; iter++) {
for(int vidx = 0; vidx < num_vert(); vidx++) {
disp[vidx] = refine_disp(v, vidx, dist);
sdisp[vidx] = smooth_disp(vidx);
}
for(int vidx = 0; vidx < num_vert(); vidx++)
vertices[vidx].pos += stepsize * (alpha * disp[vidx] + (1.0 - alpha) * sdisp[vidx]);
// Vertices moved so re-compute face normals.
compute_face_normals(); compute_vertex_normals();
}
update_meta();
}
vec3 mesh::smooth_disp(int vidx) {
vec3 &v = vertices[vidx].pos; // v = current vertex
vector<int> &fadj = facelist[vidx]; // get face adjacencies for the current vertex
int Z = 0;
vec3 smoothed(0,0,0);
// Get faces adjacent to that vertex.
for(int f = 0; f < (int)fadj.size(); f++) {
mesh_face &adjface = faces[fadj[f]];
// Examine the vertices of that face.
for(int i = 0; i < 3; i++) {
if(adjface.vert[i] != vidx) {
smoothed += vertices[adjface.vert[i]].pos;
Z++;
}
}
}
if(Z == 0) return v;
smoothed /= (float)Z;
smoothed -= v;
return smoothed;
}
void mesh::smooth_iter(vector<vec3> &disp, float stepsize) {
if(disp.size() != vertices.size()) disp.resize(vertices.size());
for(int vidx = 0; vidx < num_vert(); vidx++) {
vec3 &v = vertices[vidx].pos; // v = current vertex
vector<int> &fadj = facelist[vidx]; // get face adjacencies for the current vertex
int Z = 0;
vec3 smoothed(0,0,0);
// Get faces adjacent to that vertex.
for(int f = 0; f < (int)fadj.size(); f++) {
mesh_face &adjface = faces[fadj[f]];
// Examine the vertices of that face.
for(int i = 0; i < 3; i++) {
if(adjface.vert[i] != vidx) {
smoothed += vertices[adjface.vert[i]].pos;
Z++;
}
}
}
if(Z == 0) continue;
// The smoothed position is just the average of those face verticies.
smoothed /= (float)Z;
smoothed -= v;
disp[vidx] = smoothed; // Compute and store the displacement to smoothed position.
}
// Displace face in direction of smoothed position by given step size.
for(int vidx = 0; vidx < num_vert(); vidx++) vertices[vidx].pos += stepsize * disp[vidx];
// Recompute vertex and face normals and advance to next iteration.
compute_face_normals();
}
// Performs Taubin lambda/mu mesh smoothing. Algorithm adapted from
// TriMesh2.
void mesh::smooth(int niters) {
float stepsize = 0;
vector<vec3> disp(vertices.size()); // Vertex displacements.
for(int iter = 0; iter < 2 * niters; iter++) {
if(iter % 2 == 0) stepsize = 0.330f; else stepsize = -0.331f;
smooth_iter(disp, stepsize);
}
update_meta();
}
// For each face create a triangle that has a map from the triangle
// to the face index. Build a BVH on those triangles.
void mesh::build_bvh() {
if(bvh != NULL) delete bvh;
tri_face.resize(faces.size());
for(int fidx = 0; fidx < (int)tri_face.size(); fidx++) {
mesh_face &face = faces[fidx];
mesh_triangle t;
t.normal = face.normal;
t.v[0] = vertices[face.vert[0]].pos; t.v[1] = vertices[face.vert[1]].pos; t.v[2] = vertices[face.vert[2]].pos;
t.fidx = fidx;
tri_face[fidx] = t;
}
bvh = new BVH<mesh_triangle>(tri_face);
}
// Performs ray intersection using the BVH. Returns intersection
// points and face indexes.
void mesh::ray_intersect(vector<vec3> &pts, vector<int> &fidxs, vec3 &o, vec3 &d) {
if(bvh == NULL) { cerr << "ray_intersect: no BVH" << endl; return; } // no BVH, return false
// Find the triangles who's BV's intersect the ray.
vector<mesh_triangle *> res;
bvh->Query(res, o.x(), o.y(), o.z(), d.x(), d.y(), d.z());
if(res.size() == 0) return;
// See if the ray actually intersects the triangle.
pts.reserve(res.size());
fidxs.reserve(res.size());
for(size_t i = 0; i < res.size(); i++) {
vec3 v;
if(res[i]->ray_intersect(v, o, d)) {
pts.push_back(v);
fidxs.push_back(res[i]->fidx);
}
}
}
// Returns true on ray intersection. n contains the intersection
// point and fidx has the face index of the intersected triangle.
bool mesh::ray_intersect(vec3 &n, int &fidx, vec3 &o, vec3 &d) {
if(bvh == NULL) return false; // no BVH, return false
vector<vec3> pts; vector<int> fidxs;
ray_intersect(pts, fidxs, o, d);
if(pts.size() == 0) return false;
// Find closest intersection point on interseted triangles relative
// to the given origin.
float mindsq = distance3sq(pts[0], o);
n = pts[0];
fidx = fidxs[0];
for(size_t p = 1; p < pts.size(); p++) {
float dsq = distance3sq(o, pts[p]);
if(dsq < mindsq) {
// Update return values with closest intersection point.
n = pts[p]; fidx = fidxs[p];
mindsq = dsq;
}
}
return true;
}
// NOTE: voxelize() assumes that no vertex is outside of the
// dimension of the volume. NOTE: Voxelize should return a volume
// similar to the corresponding funtion in volume8::triangulate().
void mesh::voxelize(volume8 &v, uint8 bg, uint8 fg, bool min_dim) {
v.fill(bg); // Clear the volume.
// Get triangles of the mesh surface.
vector<triangle> triangles; as_triangles(triangles);
if(min_dim) {
// Shifts triangles by minimum dimension.
vec3 v0(x_min, y_min, z_min);
for(size_t t = 0; t < triangles.size(); t++) {
triangles[t].v[0] -= v0;
triangles[t].v[1] -= v0;
triangles[t].v[2] -= v0;
}
}
vector<ivec3> res;
for(size_t t = 0; t < triangles.size(); t++) {
res.clear(); v.tri_intersect(res, triangles[t]);
for(size_t r = 0; r < res.size(); r++) v(res[r]) = fg;
}
// TODO: This functionality can get a little tricky. The topology
// can get complex and we need to consider inside/outside
// relations. Also there are challenges with self-intersecting
// meshes!!! We want to AND those properly as in computational
// solid geometry (CSG) ops. For now I do what's simplest and AND
// self intersecting mesh regions.
// Find components of dark bg regions in voxel data.
vector< vector<ivec3> > comps; v.components(comps, 0, 0);
for(size_t c = 0; c < comps.size(); c++) {
vector<ivec3> &lc = comps[c];
// Do not fill component with foreground value if is against the
// edge of the volume.
bool fill_component = true;
for(size_t i = 0; i < lc.size(); i++) {
if(lc[i].x() == 0 || lc[i].x() == v.width - 1 ||
lc[i].y() == 0 || lc[i].y() == v.height - 1 ||
lc[i].z() == 0 || lc[i].z() == v.depth - 1) {
fill_component = false; break;
}
}
if(fill_component) { for(size_t i = 0; i < lc.size(); i++) v(lc[i]) = 255; }
}
}
void mesh::sample(vector<uint8> &v_samples, volume8 &v) {
// Get triangles for this mesh.
vector<triangle> triangles; as_triangles(triangles);
v_samples.resize(triangles.size());
for(size_t i = 0; i < v_samples.size(); i++) v_samples[i] = 0;
vector<ivec3> res;
for(size_t fidx = 0; fidx < triangles.size(); fidx++) {
// Intersect triangle with cubes.
res.clear(); v.tri_intersect(res, triangles[fidx]);
// Compute average value of intersected voxels.
float avg = 0, N = res.size();
for(size_t r = 0; r < res.size(); r++) {
avg += (float)v(res[r].x(), res[r].y(), res[r].z()) / N;
}
v_samples[fidx] = avg;
}
}
void mesh::surface_bandpass(vector<int> &bandpass, vector<uint8> &v_samples,
int fg, int bg, int T, int blurIter) {
vector<uint8> v2 = v_samples;
blur_samples(v2, blurIter);
// Uses convention that facelabel is set to 1 if non-edge region,
// 0 if an edge region.
bandpass.resize(v2.size());
for(size_t i = 0; i < v2.size(); i++) {
if((int)v_samples[i] - (int)v2[i] > T) bandpass[i] = fg;
else bandpass[i] = bg;
}
//vector<int> tmp = facelabels;
//dilate_label(tmp, 3, 0, 1);
//facelabels = tmp;
}
void mesh::blur_samples(vector<uint8> &src, int maxIter) {
vector<uint8> tmp(src.size());
for(int iter = 0; iter < maxIter; iter++) {
// Compute the average value of the current face and its
// neighbors given the input sample image.
for(size_t fidx = 0; fidx < faces.size(); fidx++) {
mesh_face &f = faces[fidx];
float avg = (float)src[fidx] / 4.0f;
for(int j = 0; j < 3; j++) avg += (float)src[f.adj[j]] / 4.0f;
tmp[fidx] = avg;
}
src = tmp;
}
}
void mesh::dilate_label(vector<int> &dst, vector<int> &src, int niter, int fg, int bg) {
dst = src;
vector<int> tmp(dst.size());
for(int iter = 0; iter < niter; iter++) {
for(size_t fidx = 0; fidx < faces.size(); fidx++) {
if(dst[fidx] == fg) tmp[fidx] = fg; // fg face, leave alone
else if(dst[fidx] == bg) {
// If a bg face, count the number of neighboring fg faces.
mesh_face &f = faces[fidx];
int cnt = 0;
for(int j = 0; j < 3; j++) { if(f.adj[j] >= 0 && dst[f.adj[j]] == fg) cnt++; }
if(cnt > 0) tmp[fidx] = fg; else tmp[fidx] = bg;
}
}
dst = tmp;
}
}
void mesh::dilate_fg(vector<int> &dst, vector<int> &src, int niter, int fg) {
dst = src;
vector<int> tmp(dst.size());
for(int iter = 0; iter < niter; iter++) {
// Scan through faces.
tmp = dst;
for(size_t fidx = 0; fidx < faces.size(); fidx++) {
if(dst[fidx] == fg) {
mesh_face &f = faces[fidx];
// Label adjacent faces with fg value.
for(int j = 0; j < 3; j++) { if(f.adj[j] >= 0) tmp[f.adj[j]] = fg; }
}
}
dst = tmp;
}
}
void mesh::fill_bg(vector<int> &dst, vector<int> &src, int niter, int bg) {
dst = src;
int sel_idx = 0;
vector<int> tmp(dst.size());
for(int iter = 0; iter < niter; iter++) {
tmp = dst;
for(size_t fidx = 0; fidx < faces.size(); fidx++) {
if(dst[fidx] != bg) continue;
// If a bg face, count the number of neighboring fg faces.
mesh_face &f = faces[fidx];
int fg_cnt = 0;
for(int j = 0; j < 3; j++) { if(f.adj[j] >= 0 && dst[f.adj[j]] != bg) fg_cnt++; }
if(fg_cnt == 1) {
// Single fg. Update current with value.
for(int j = 0; j < 3; j++) {
if(f.adj[j] >= 0 && dst[f.adj[j]] != bg) { tmp[fidx] = dst[f.adj[j]]; break; }
}
}
else if(fg_cnt >= 2) { // >=2 fg faces, pick max count
if(f.adj[0] >= 0 && f.adj[1] >= 0 && dst[f.adj[0]] == dst[f.adj[1]]) {
tmp[fidx] = dst[f.adj[0]];
}
else if(f.adj[0] >= 0 && f.adj[2] >= 0 && dst[f.adj[0]] == dst[f.adj[2]] ) {
tmp[fidx] = dst[f.adj[0]];
}
else if(f.adj[1] >= 0 && f.adj[2] >= 0 && dst[f.adj[1]] == dst[f.adj[2]] ){
tmp[fidx] = dst[f.adj[1]];
}
else {
// Otherwise pick one arbitrarily (cycle selection). Don't have to worry about
// inf looping here since fg_cnt >= 2 assures no f.adj[sel_idx] == -1.
while(true) {
if(f.adj[sel_idx] < 0) { sel_idx++; if(sel_idx == 3) sel_idx = 0; }
else {
tmp[fidx] = dst.at(f.adj[sel_idx]);
sel_idx++; if(sel_idx == 3) sel_idx = 0;
break;
}
}
tmp[fidx] = dst[f.adj[0]];
}
}
}
dst = tmp;
}
}
// Watershed segment voxel samples. I is an image with intensity
// information. O is coded as follows: 0 = background label, <= -1
// leave alone label, >= 1, label to grow by Watershed
void mesh::watershed(vector<uint8> &I, vector<int> &O) {
map<int, queue<int> > PQ;
for(int p = 0; p < num_faces(); p++) {
if(O[p] > 0) { // > 0 label to use
// Put all marker/seed pixels with background neighbors into
// the priority queue.
bool bgNeighbor = false;
mesh_face &f = faces[p];
for(int i = 0; i < 3; i++) {
if(f.adj[i] < 0) continue;
int q = f.adj[i];
if(O[q] == 0) bgNeighbor = true; // 0 is the back ground label
}
if(bgNeighbor) PQ[(int)I[p]].push(p); // Separate queues for each intensity.
}
}
// NOTE: 0 == unlabeled
while(!PQ.empty()) {
// Get the queue for the lowest intensity level.
int vimg = PQ.begin()->first;
queue<int> curQ = PQ.begin()->second;
PQ.erase( PQ.begin() );
while(curQ.empty() == false) { // Empty this queue.
int p = curQ.front(); curQ.pop();
// Propagate the label of p to all unlabeled neighbors of p.
mesh_face &f = faces[p];
for(int i = 0; i < 3; i++) {
if(f.adj[i] < 0) continue;
int q = f.adj[i];
if(O[q] == 0) { // Check to see if q is an unlabeled neighbor.
O[q] = O[p]; // Propagate the label of p to unlabeled neighbors.
// Is the intensity at the propagated position less than
// (or equal to) the current queue intensity? Add to
// current queue. This deals "reasonably" with plateaus in
// the image.
if( I[q] <= vimg ) curQ.push(q);
else PQ[I[q]].push(q); // Otherwise add to corresponding intensity queue.
}
}
}
}
}
void mesh::boundary_edges(vector<int> &facelabels, vector<vec3> &v0, vector<vec3> &v1) {
v0.clear(); v1.clear();
for(size_t fidx = 0; fidx < faces.size(); fidx++) {
mesh_face &f = faces[fidx];
for(int a = 0; a < 3; a++) {
if(f.adj[a] >= 0 && facelabels[fidx] != facelabels[f.adj[a]]) {
int i = -1, j = -1;
switch(a) {
case 0: i = 0; j = 1; break; // edge 0 = vert 0 and 1
case 1: i = 0; j = 2; break; // edge 1 = vert 0 and 2
case 2: i = 1; j = 2; break; // edge 2 = vert 1 and 2
}
v0.push_back(vertices[f.vert[i]].pos);
v1.push_back(vertices[f.vert[j]].pos);
}
}
}
}
void mesh::boundary_edges(vector<vec3> &v0, vector<vec3> &v1) {
v0.clear(); v1.clear();
for(size_t fidx = 0; fidx < faces.size(); fidx++) {
mesh_face &f = faces[fidx];
for(int a = 0; a < 3; a++) {
if(f.adj[a] < 0) {
int i = -1, j = -1;
switch(a) {
case 0: i = 0; j = 1; break; // edge 0 = vert 0 and 1
case 1: i = 0; j = 2; break; // edge 1 = vert 0 and 2
case 2: i = 1; j = 2; break; // edge 2 = vert 1 and 2
}
v0.push_back(vertices[f.vert[i]].pos);
v1.push_back(vertices[f.vert[j]].pos);
}
}
}
}
// Dijkstra's algorithm. Single source shortest path.
void mesh::Dijkstra(vector<int> &previous, vector<float> &dist, int source) {
const float inf = numeric_limits<float>().max();
dist.resize(num_faces());
previous.resize(num_faces());
util::PQi<float> Q(num_faces(), dist);
for(int fidx = 0; fidx < num_faces(); fidx++) {
dist[fidx] = inf;
previous[fidx] = -1;
}
dist[source] = 0;
// Fill the priority queue.
for(int fidx = 0; fidx < num_faces(); fidx++) Q.insert(fidx);
while(!Q.empty()) {
int u = Q.extractMin();
if(dist.at(u) == inf) break; // No more accessible faces.
// For each adjacency.
for(int i = 0; i < 3; i++) {
int v = faces[u].adj[i]; if(v < 0) continue;
float alt = dist[u] + distance3sq(face_centroid(u), face_centroid(v));
if(alt < dist[v]) {
dist[v] = alt; Q.decreaseKey(v);
previous[v] = u;
}
}
}
}
void mesh::ShortestPath(vector<int> &path, vector<int> &previous, int target) {
int u = target;
// Path will end up with triangle centroids.
path.clear();
while(previous[u] >= 0) {
path.push_back(u);
u = previous[u];
}
path.push_back(u);
reverse(path.begin(), path.end());
}
void mesh::edge_vert(vector<vec3> &edge_vert) {
edge_vert.clear();
set<int> edge_vidxs;
for(int fidx = 0; fidx < num_faces(); fidx++) {
if(faces[fidx].adj[0] < 0) {
edge_vidxs.insert(faces[fidx].vert[0]);
edge_vidxs.insert(faces[fidx].vert[1]);
}
if(faces[fidx].adj[1] < 0) {
edge_vidxs.insert(faces[fidx].vert[0]);
edge_vidxs.insert(faces[fidx].vert[2]);
}
if(faces[fidx].adj[2] < 0) {
edge_vidxs.insert(faces[fidx].vert[1]);
edge_vidxs.insert(faces[fidx].vert[2]);
}
}
for(set<int>::iterator it = edge_vidxs.begin(); it != edge_vidxs.end(); it++) {
edge_vert.push_back(vertices.at(*it).pos);
}
}
void mesh::pca_dims(vector<float> &dims, float alpha) {
// Get mesh verticies, subtract centroid
vector<vec3> mesh_vert(vertices.size());
for(size_t v = 0; v < vertices.size(); v++) mesh_vert[v] = vertices[v].pos - centroid;
// Compute PCA using mesh vertices.
vector<vec3> pca3; vector<float> pca3_x;
PCA3(pca3, pca3_x, mesh_vert);
dims.reserve(3); dims.resize(3);
for(int i = 0; i < 3; i++) {
vec3 dir1 = pca3.at(i).max_project(mesh_vert); // Make sure to rescale to micron axes.
vec3 pca3_neg = -pca3[i];
vec3 dir2 = pca3_neg.max_project(mesh_vert);
dir1 *= alpha;
dir2 *= alpha;
dims[i] = dir1.length() + dir2.length();
}
}
void mesh::pca_longdir(vec3 &pos1, vec3 &pos2, float len_frac) {
// Get mesh verticies, subtract centroid
vector<vec3> mesh_vert(vertices.size());
for(size_t v = 0; v < vertices.size(); v++) mesh_vert[v] = vertices[v].pos - centroid;
// Compute PCA using mesh vertices.
vector<vec3> pca3; vector<float> pca3_x;
PCA3(pca3, pca3_x, mesh_vert);
vec3 dir1 = pca3.at(2).max_project(mesh_vert); // Make sure to rescale to micron axes.
vec3 pca3_neg = -pca3[2];
vec3 dir2 = pca3_neg.max_project(mesh_vert);
pos1 = dir1 * len_frac + centroid;
pos2 = dir2 * len_frac + centroid;
if(pos1.z() > pos2.z()) swap(pos1, pos2);
}
float mesh::bend_measure() {
if(vertices.size() == 0) return -1;
// Get mesh verticies, subtract centroid
vector<vec3> mesh_vert(vertices.size());
for(size_t v = 0; v < vertices.size(); v++) mesh_vert[v] = vertices[v].pos - centroid;
// Compute PCA using mesh vertices.
vector<vec3> pca3; vector<float> pca3_x;
PCA3(pca3, pca3_x, mesh_vert);
vec3 pc2 = pca3[2], pc1 = pca3[1];
vector<float> Rsq_vals(mesh_vert.size());
for(size_t v = 0; v < mesh_vert.size(); v++) {
float s2 = pc2.scalar_proj(mesh_vert[v]);
float s1 = pc1.scalar_proj(mesh_vert[v]);
vec3 on_plane = s2 * pc2 + s1 * pc1;
Rsq_vals[v] = geom::distance3sq(on_plane, mesh_vert[v]);
}
sort(Rsq_vals.begin(), Rsq_vals.end());
return Rsq_vals.at(0.75 * Rsq_vals.size());
}
float mesh::compute_sa(float alpha) {
float surface_area = 0;
vector<triangle> tri; as_triangles(tri);
for(size_t fidx = 0; fidx < tri.size(); fidx++) {
triangle t = tri[fidx];
// Map from isotropic voxel space to micron space.
t[0] *= alpha; t[1] *= alpha; t[2] *= alpha;
surface_area += t.area();
}
return surface_area;
}
};
| 35.536232 | 124 | 0.590801 | [
"mesh",
"geometry",
"vector",
"solid"
] |
85cd0035048ef2e403f890305571815586b6f576 | 1,800 | cpp | C++ | android-29/android/app/job/JobInfo_TriggerContentUri.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/app/job/JobInfo_TriggerContentUri.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/app/job/JobInfo_TriggerContentUri.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../net/Uri.hpp"
#include "../../os/Parcel.hpp"
#include "../../../JObject.hpp"
#include "./JobInfo_TriggerContentUri.hpp"
namespace android::app::job
{
// Fields
JObject JobInfo_TriggerContentUri::CREATOR()
{
return getStaticObjectField(
"android.app.job.JobInfo$TriggerContentUri",
"CREATOR",
"Landroid/os/Parcelable$Creator;"
);
}
jint JobInfo_TriggerContentUri::FLAG_NOTIFY_FOR_DESCENDANTS()
{
return getStaticField<jint>(
"android.app.job.JobInfo$TriggerContentUri",
"FLAG_NOTIFY_FOR_DESCENDANTS"
);
}
// QJniObject forward
JobInfo_TriggerContentUri::JobInfo_TriggerContentUri(QJniObject obj) : JObject(obj) {}
// Constructors
JobInfo_TriggerContentUri::JobInfo_TriggerContentUri(android::net::Uri arg0, jint arg1)
: JObject(
"android.app.job.JobInfo$TriggerContentUri",
"(Landroid/net/Uri;I)V",
arg0.object(),
arg1
) {}
// Methods
jint JobInfo_TriggerContentUri::describeContents() const
{
return callMethod<jint>(
"describeContents",
"()I"
);
}
jboolean JobInfo_TriggerContentUri::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jint JobInfo_TriggerContentUri::getFlags() const
{
return callMethod<jint>(
"getFlags",
"()I"
);
}
android::net::Uri JobInfo_TriggerContentUri::getUri() const
{
return callObjectMethod(
"getUri",
"()Landroid/net/Uri;"
);
}
jint JobInfo_TriggerContentUri::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
void JobInfo_TriggerContentUri::writeToParcel(android::os::Parcel arg0, jint arg1) const
{
callMethod<void>(
"writeToParcel",
"(Landroid/os/Parcel;I)V",
arg0.object(),
arg1
);
}
} // namespace android::app::job
| 21.176471 | 89 | 0.691667 | [
"object"
] |
85cde87b69e522da80fe48b493db88d316e7e0c4 | 2,143 | cc | C++ | hetest/cpp/baseline/heaan/client/heaan-client.cc | CianLevy/Modified-HEtest | 4f4422bba48f269e953ca0d3863f774f66ba2247 | [
"BSD-2-Clause"
] | 2 | 2020-05-18T08:19:39.000Z | 2021-06-24T13:34:28.000Z | hetest/cpp/baseline/heaan/client/heaan-client.cc | CianLevy/Modified-HEtest | 4f4422bba48f269e953ca0d3863f774f66ba2247 | [
"BSD-2-Clause"
] | null | null | null | hetest/cpp/baseline/heaan/client/heaan-client.cc | CianLevy/Modified-HEtest | 4f4422bba48f269e953ca0d3863f774f66ba2247 | [
"BSD-2-Clause"
] | null | null | null | #include "heaan-client.h"
#include "../heaan-serialiser.h"
#include <string>
#include "common/check.h"
#include <memory>
using namespace std;
using namespace NTL;
void HEAANClient::Setup(){
string line = "";
string delimiter = "=";
vector<unsigned long> params;
getline(cin, line);
while(line != "ENDKEY"){
size_t pos = line.find(delimiter);
params.push_back(stoi(line.substr(pos + 1)));
getline(cin, line);
}
k = params.at(0);
logq = params.at(1);
logp = params.at(2);
}
void HEAANClient::GenerateKeys(){
Setup();
srand(time(NULL));
SetNumThreads(1); //Not a fair comparison to use multiple threads
ring = std::make_shared<Ring>();
secret_key = boost::make_unique<SecretKey>(*ring);
scheme = std::make_shared<Scheme>(*secret_key, *ring);
cout << "KEY" << endl;
cout << logp << endl;
cout << *scheme << endl;
cout << "ENDKEY" << endl;
}
vector<int> HEAANClient::ReadInput(){
string line;
vector<int> inputV;
getline(cin, line);
if (line[0] == '['){
int previous = 1;
for (size_t i = 1; i < line.size(); i++){
if (line[i] == ',' || line[i] == ']'){
inputV.push_back(stoi(line.substr(previous, i - previous)));
previous = i + 1;
}
}
}
getline(cin, line);
CHECK(line == "ENDPDATA") << "Unexpected PDATA footer" << line;
return inputV;
}
void HEAANClient::Encrypt(){
vector<int> plaintxts = ReadInput();
cout << "EDATA" << endl;
cout << plaintxts.size() << endl;
for (auto i : plaintxts){
Plaintext ptxt(logp, logq, 1);
double val = (double)i;
scheme->encodeSingle(ptxt, val, logp, logq);
Ciphertext c(logp, logq, 1);
scheme->encryptMsg(c, ptxt);
cout << c << endl;
}
cout << "ENDEDATA" << endl;
}
void HEAANClient::Decrypt(){
Ciphertext result;
cin >> result;
complex<double> result_decrypted = scheme->decryptSingle(*secret_key, result);
cout << "PDATA" << endl;
cout << result_decrypted << endl;
cout << "ENDPDATA" << endl;
} | 23.043011 | 82 | 0.570229 | [
"vector"
] |
85d5fb760dded50fa40109e84b509017ee77e8d9 | 8,895 | cpp | C++ | renderer/renderer_screen_basic.cpp | jdmclark/jkgfxmod | 6612413810129ebeae2affeb956d0a5fdb41dd0e | [
"MIT"
] | 57 | 2019-03-11T20:29:42.000Z | 2022-03-11T19:26:01.000Z | renderer/renderer_screen_basic.cpp | jdmclark/jkgfxmod | 6612413810129ebeae2affeb956d0a5fdb41dd0e | [
"MIT"
] | 71 | 2019-03-31T14:39:58.000Z | 2022-02-12T05:25:39.000Z | renderer/renderer_screen_basic.cpp | jdmclark/jkgfxmod | 6612413810129ebeae2affeb956d0a5fdb41dd0e | [
"MIT"
] | 10 | 2019-05-14T21:02:57.000Z | 2021-06-06T23:19:16.000Z | #include "renderer_screen_basic.hpp"
#include "base/log.hpp"
#include "math/colors.hpp"
jkgm::render_depthbuffer::render_depthbuffer(size<2, int> dims)
: viewport(make_point(0, 0), dims)
{
gl::bind_renderbuffer(rbo);
gl::renderbuffer_storage(gl::renderbuffer_format::depth, dims);
}
jkgm::render_buffer::render_buffer(size<2, int> dims, render_depthbuffer *rbo)
: viewport(make_point(0, 0), dims)
{
gl::bind_framebuffer(gl::framebuffer_bind_target::any, fbo);
// Set up color texture:
gl::bind_texture(gl::texture_bind_target::texture_2d, tex);
gl::tex_image_2d(gl::texture_bind_target::texture_2d,
/*level*/ 0,
gl::texture_internal_format::rgba16f,
dims,
gl::texture_pixel_format::rgba,
gl::texture_pixel_type::float32,
span<char const>(nullptr, 0U));
gl::set_texture_max_level(gl ::texture_bind_target::texture_2d, 0U);
gl::framebuffer_texture(
gl::framebuffer_bind_target::any, gl::framebuffer_attachment::color0, tex, 0);
// Set up real depth buffer:
gl::framebuffer_renderbuffer(
gl::framebuffer_bind_target::any, gl::framebuffer_attachment::depth, rbo->rbo);
// Finish:
gl::draw_buffers(gl::draw_buffer::color0);
auto fbs = gl::check_framebuffer_status(gl::framebuffer_bind_target::any);
if(gl::check_framebuffer_status(gl::framebuffer_bind_target::any) !=
gl::framebuffer_status::complete) {
gl::log_errors();
LOG_ERROR("Failed to create render framebuffer: ", static_cast<int>(fbs));
}
gl::bind_framebuffer(gl::framebuffer_bind_target::any, gl::default_framebuffer);
}
jkgm::render_gbuffer::render_gbuffer(size<2, int> dims, render_depthbuffer *rbo)
: viewport(make_point(0, 0), dims)
{
gl::bind_framebuffer(gl::framebuffer_bind_target::any, fbo);
// Set up color texture:
gl::bind_texture(gl::texture_bind_target::texture_2d, color_tex);
gl::tex_image_2d(gl::texture_bind_target::texture_2d,
/*level*/ 0,
gl::texture_internal_format::rgba16f,
dims,
gl::texture_pixel_format::rgba,
gl::texture_pixel_type::float32,
span<char const>(nullptr, 0U));
gl::set_texture_max_level(gl ::texture_bind_target::texture_2d, 0U);
gl::framebuffer_texture(
gl::framebuffer_bind_target::any, gl::framebuffer_attachment::color0, color_tex, 0);
// Set up emissive texture:
gl::bind_texture(gl::texture_bind_target::texture_2d, emissive_tex);
gl::tex_image_2d(gl::texture_bind_target::texture_2d,
/*level*/ 0,
gl::texture_internal_format::rgba16f,
dims,
gl::texture_pixel_format::rgba,
gl::texture_pixel_type::float32,
span<char const>(nullptr, 0U));
gl::set_texture_max_level(gl ::texture_bind_target::texture_2d, 0U);
gl::framebuffer_texture(
gl::framebuffer_bind_target::any, gl::framebuffer_attachment::color1, emissive_tex, 0);
// Set up normal texture:
gl::bind_texture(gl::texture_bind_target::texture_2d, normal_tex);
gl::tex_image_2d(gl::texture_bind_target::texture_2d,
/*level*/ 0,
gl::texture_internal_format::rgb16f,
dims,
gl::texture_pixel_format::rgb,
gl::texture_pixel_type::float32,
make_span((char const *)nullptr, 0U));
gl::set_texture_max_level(gl::texture_bind_target::texture_2d, 0U);
gl::set_texture_mag_filter(gl::texture_bind_target::texture_2d, gl::mag_filter::linear);
gl::set_texture_min_filter(gl::texture_bind_target::texture_2d, gl::min_filter::linear);
gl::set_texture_wrap_mode(gl::texture_bind_target::texture_2d,
gl::texture_direction::s,
gl::texture_wrap_mode::clamp_to_border);
gl::set_texture_wrap_mode(gl::texture_bind_target::texture_2d,
gl::texture_direction::t,
gl::texture_wrap_mode::clamp_to_border);
gl::set_texture_border_color(gl::texture_bind_target::texture_2d,
color(0.0f, 0.0f, 1.0f, std::numeric_limits<float>::lowest()));
gl::framebuffer_texture(gl::framebuffer_bind_target::any,
gl::framebuffer_attachment::color2,
normal_tex,
/*level*/ 0);
// Set up depth texture:
gl::bind_texture(gl::texture_bind_target::texture_2d, depth_tex);
gl::tex_image_2d(gl::texture_bind_target::texture_2d,
/*level*/ 0,
gl::texture_internal_format::r16f,
dims,
gl::texture_pixel_format::red,
gl::texture_pixel_type::float32,
make_span((char const *)nullptr, 0U));
gl::set_texture_max_level(gl::texture_bind_target::texture_2d, 0U);
gl::set_texture_mag_filter(gl::texture_bind_target::texture_2d, gl::mag_filter::linear);
gl::set_texture_min_filter(gl::texture_bind_target::texture_2d, gl::min_filter::linear);
gl::set_texture_wrap_mode(gl::texture_bind_target::texture_2d,
gl::texture_direction::s,
gl::texture_wrap_mode::clamp_to_border);
gl::set_texture_wrap_mode(gl::texture_bind_target::texture_2d,
gl::texture_direction::t,
gl::texture_wrap_mode::clamp_to_border);
gl::set_texture_border_color(gl::texture_bind_target::texture_2d,
color(0.0f, 0.0f, 1.0f, std::numeric_limits<float>::lowest()));
gl::framebuffer_texture(gl::framebuffer_bind_target::any,
gl::framebuffer_attachment::color3,
depth_tex,
/*level*/ 0);
// Set up real depth buffer:
gl::framebuffer_renderbuffer(
gl::framebuffer_bind_target::any, gl::framebuffer_attachment::depth, rbo->rbo);
// Finish:
gl::draw_buffers(gl::draw_buffer::color0,
gl::draw_buffer::color1,
gl::draw_buffer::color2,
gl::draw_buffer::color3);
auto fbs = gl::check_framebuffer_status(gl::framebuffer_bind_target::any);
if(gl::check_framebuffer_status(gl::framebuffer_bind_target::any) !=
gl::framebuffer_status::complete) {
gl::log_errors();
LOG_ERROR("Failed to create render framebuffer: ", static_cast<int>(fbs));
}
gl::bind_framebuffer(gl::framebuffer_bind_target::any, gl::default_framebuffer);
}
jkgm::renderer_screen_basic::renderer_screen_basic(size<2, int> screen_res)
: shared_depthbuffer(screen_res)
, screen_buffer(screen_res, &shared_depthbuffer)
, screen_gbuffer(screen_res, &shared_depthbuffer)
{
}
void jkgm::renderer_screen_basic::begin_frame()
{
gl::set_viewport(screen_buffer.viewport);
gl::bind_framebuffer(gl::framebuffer_bind_target::any, screen_buffer.fbo);
gl::clear_buffer_color(0, color::zero());
gl::clear_buffer_depth(1.0f);
}
void jkgm::renderer_screen_basic::begin_opaque_pass()
{
gl::bind_framebuffer(gl::framebuffer_bind_target::any, screen_gbuffer.fbo);
gl::clear_buffer_color(0, color::zero());
gl::clear_buffer_color(1, color::zero());
gl::clear_buffer_color(2, color::zero());
gl::clear_buffer_color(3, color::fill(1.0f));
gl::clear_buffer_depth(1.0f);
}
void jkgm::renderer_screen_basic::end_opaque_pass() {}
jkgm::gl::texture_view jkgm::renderer_screen_basic::get_resolved_color_texture()
{
return screen_gbuffer.color_tex;
}
jkgm::gl::texture_view jkgm::renderer_screen_basic::get_resolved_emissive_texture()
{
return screen_gbuffer.emissive_tex;
}
jkgm::gl::texture_view jkgm::renderer_screen_basic::get_resolved_normal_texture()
{
return screen_gbuffer.normal_tex;
}
jkgm::gl::texture_view jkgm::renderer_screen_basic::get_resolved_depth_texture()
{
return screen_gbuffer.depth_tex;
}
void jkgm::renderer_screen_basic::begin_compose_opaque_pass()
{
gl::bind_framebuffer(gl::framebuffer_bind_target::any, screen_buffer.fbo);
gl::clear_buffer_color(0, color::zero());
}
void jkgm::renderer_screen_basic::end_compose_opaque_pass() {}
void jkgm::renderer_screen_basic::begin_transparency_pass()
{
gl::bind_framebuffer(gl::framebuffer_bind_target::any, screen_buffer.fbo);
}
void jkgm::renderer_screen_basic::end_transparency_pass() {}
void jkgm::renderer_screen_basic::end_frame() {}
jkgm::gl::texture_view jkgm::renderer_screen_basic::get_resolved_final_texture()
{
return screen_buffer.tex;
} | 41.180556 | 96 | 0.650703 | [
"render"
] |
85e5d072cfa681f7590a9230ed56d9303d88e63c | 2,844 | hpp | C++ | src/framework/shared/inc/private/common/fxlock.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 994 | 2015-03-18T21:37:07.000Z | 2019-04-26T04:04:14.000Z | src/framework/shared/inc/private/common/fxlock.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 13 | 2019-06-13T15:58:03.000Z | 2022-02-18T22:53:35.000Z | src/framework/shared/inc/private/common/fxlock.hpp | IT-Enthusiast-Nepal/Windows-Driver-Frameworks | bfee6134f30f92a90dbf96e98d54582ecb993996 | [
"MIT"
] | 350 | 2015-03-19T04:29:46.000Z | 2019-05-05T23:26:50.000Z | /*++
Copyright (c) Microsoft Corporation
Module Name:
FxLock.hpp
Abstract:
This is the C++ header for the FxLock
This represents a container for handling locking
Author:
Revision History:
--*/
#ifndef _FXLOCK_H_
#define _FXLOCK_H_
/**
* This is the base lock object implementation
*
* This is intended to be embedded in an FxNonPagedObject
* rather than forcing a separate allocation for
* non-verifier mode.
*
* In order to reduce the runtime memory cost of
* building in verifier support for a retail version,
* a single pointer it stored to FxVerifierLock
* if verifier is on. If this pointer is != NULL,
* lock calls are proxied to this lock function,
* leaving our internal spinlock redundent.
*
* The decision is to minimize the non-verifier
* memory footprint so we do not have to compile
* it out for retail builds, but always have it
* available through a driver debug setting.
*/
class FxLock {
private:
MxLock m_lock;
// For Verifier
FxVerifierLock* m_Verifier;
public:
FxLock(
VOID
)
{
m_lock.Initialize();
m_Verifier = NULL;
}
VOID
Initialize(
__in FxObject * ParentObject
);
~FxLock()
{
if (m_Verifier != NULL) {
delete m_Verifier;
}
}
_When_(this->m_Verifier == NULL, _Acquires_lock_(this->m_lock))
inline
VOID
Lock(
__out PKIRQL PreviousIrql
)
{
if (m_Verifier != NULL) {
m_Verifier->Lock(PreviousIrql, FALSE);
}
// else if (PreviousIrql == NULL) {
// KeAcquireSpinLockAtDpcLevel(&m_lock);
// }
else {
m_lock.Acquire(PreviousIrql);
}
}
_When_(this->m_Verifier == NULL, _Releases_lock_(this->m_lock))
inline
void
Unlock(
__in KIRQL PreviousIrql
)
{
if (m_Verifier != NULL) {
m_Verifier->Unlock(PreviousIrql, FALSE);
}
// else if (AtDpc) {
// KeReleaseSpinLockFromDpcLevel(&m_lock);
// }
else {
m_lock.Release(PreviousIrql);
}
}
_When_(this->m_Verifier == NULL, _Acquires_lock_(this->m_lock))
inline
VOID
LockAtDispatch(
VOID
)
{
if (m_Verifier != NULL) {
KIRQL previousIrql;
m_Verifier->Lock(&previousIrql, TRUE);
}
else {
m_lock.AcquireAtDpcLevel();
}
}
_When_(this->m_Verifier == NULL, _Releases_lock_(this->m_lock))
inline
void
UnlockFromDispatch(
VOID
)
{
if (m_Verifier != NULL) {
m_Verifier->Unlock(DISPATCH_LEVEL, TRUE);
}
else {
m_lock.ReleaseFromDpcLevel();
}
}
};
#endif // _FXLOCK_H_
| 18.834437 | 67 | 0.576301 | [
"object"
] |
85f3c71f40b9a177f2e3adba8b8742fdb8b45aa7 | 981 | cpp | C++ | src/Rocket3d/main.cpp | walthill/Rocket3D | 45ba128699b354f21db04f4b114c81504c8e0771 | [
"Apache-2.0"
] | null | null | null | src/Rocket3d/main.cpp | walthill/Rocket3D | 45ba128699b354f21db04f4b114c81504c8e0771 | [
"Apache-2.0"
] | 3 | 2019-12-07T01:28:17.000Z | 2020-02-05T16:57:33.000Z | src/Rocket3d/main.cpp | walthill/Rocket3D | 45ba128699b354f21db04f4b114c81504c8e0771 | [
"Apache-2.0"
] | null | null | null | /********
=========================
ROCKET3D
=========================
File Created By: Walter Hill
Rocket3D is an open source 3D game engine written using C++ & OpenGL.
This code is open source under the Apache 2.0 license.
(https://github.com/walthill/Rocket3D/blob/master/LICENSE)
=========================
main.cpp
=========================
This file is the entry point for the entirety of the Rocket3D game engine.
The GameApp class is initialized and destroyed here. The engine loop is entered from here.
********/
#include "../RocketEngine/logging/RK_Log.h"
#include "core/Application.h"
int main(int argc, char* argv[])
{
RK_LOGGER_INIT();
RK_CORE_INFO_ALL("Rocket Logger initialized");
Application::initInstance();
if(!Application::getInstance()->run())
Application::cleanInstance();
RK_MEMREPORT();
//console report
//rkutil::MemoryTracker::getInstance()->reportAllocs(std::cout);
RK_LOGGER_CLEAN();
system("pause");
return 0;
} | 23.926829 | 91 | 0.639144 | [
"3d"
] |
65b7ce423c29938e31d6fb8c1c929e8f3dfce4b9 | 84,782 | cpp | C++ | src/shapelib/shpopen.cpp | fritzr/voronoi-game | 77fcc6a40076ab092795445f4e2a73f475338090 | [
"MIT"
] | null | null | null | src/shapelib/shpopen.cpp | fritzr/voronoi-game | 77fcc6a40076ab092795445f4e2a73f475338090 | [
"MIT"
] | null | null | null | src/shapelib/shpopen.cpp | fritzr/voronoi-game | 77fcc6a40076ab092795445f4e2a73f475338090 | [
"MIT"
] | 1 | 2020-07-12T03:44:53.000Z | 2020-07-12T03:44:53.000Z | /******************************************************************************
* $Id: shpopen.c,v 1.60 2009-09-17 20:50:02 bram Exp $
*
* Project: Shapelib
* Purpose: Implementation of core Shapefile read/write functions.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 1999, 2001, Frank Warmerdam
*
* This software is available under the following "MIT Style" license,
* or at the option of the licensee under the LGPL (see LICENSE.LGPL). This
* option is discussed in more detail in shapelib.html.
*
* --
*
* 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.
******************************************************************************
*
* $Log: shpopen.c,v $
* Revision 1.60 2009-09-17 20:50:02 bram
* on Win32, define snprintf as alias to _snprintf
*
* Revision 1.59 2008-03-14 05:25:31 fwarmerdam
* Correct crash on buggy geometries (gdal #2218)
*
* Revision 1.58 2008/01/08 23:28:26 bram
* on line 2095, use a float instead of a double to avoid a compiler warning
*
* Revision 1.57 2007/12/06 07:00:25 fwarmerdam
* dbfopen now using SAHooks for fileio
*
* Revision 1.56 2007/12/04 20:37:56 fwarmerdam
* preliminary implementation of hooks api for io and errors
*
* Revision 1.55 2007/11/21 22:39:56 fwarmerdam
* close shx file in readonly mode (GDAL #1956)
*
* Revision 1.54 2007/11/15 00:12:47 mloskot
* Backported recent changes from GDAL (Ticket #1415) to Shapelib.
*
* Revision 1.53 2007/11/14 22:31:08 fwarmerdam
* checks after mallocs to detect for corrupted/voluntary broken shapefiles.
* http://trac.osgeo.org/gdal/ticket/1991
*
* Revision 1.52 2007/06/21 15:58:33 fwarmerdam
* fix for SHPRewindObject when rings touch at one vertex (gdal #976)
*
* Revision 1.51 2006/09/04 15:24:01 fwarmerdam
* Fixed up log message for 1.49.
*
* Revision 1.50 2006/09/04 15:21:39 fwarmerdam
* fix of last fix
*
* Revision 1.49 2006/09/04 15:21:00 fwarmerdam
* MLoskot: Added stronger test of Shapefile reading failures, e.g. truncated
* files. The problem was discovered by Tim Sutton and reported here
* https://svn.qgis.org/trac/ticket/200
*
* Revision 1.48 2006/01/26 15:07:32 fwarmerdam
* add bMeasureIsUsed flag from Craig Bruce: Bug 1249
*
* Revision 1.47 2006/01/04 20:07:23 fwarmerdam
* In SHPWriteObject() make sure that the record length is updated
* when rewriting an existing record.
*
* Revision 1.46 2005/02/11 17:17:46 fwarmerdam
* added panPartStart[0] validation
*
* Revision 1.45 2004/09/26 20:09:48 fwarmerdam
* const correctness changes
*
* Revision 1.44 2003/12/29 00:18:39 fwarmerdam
* added error checking for failed IO and optional CPL error reporting
*
* Revision 1.43 2003/12/01 16:20:08 warmerda
* be careful of zero vertex shapes
*
* Revision 1.42 2003/12/01 14:58:27 warmerda
* added degenerate object check in SHPRewindObject()
*
* Revision 1.41 2003/07/08 15:22:43 warmerda
* avoid warning
*
* Revision 1.40 2003/04/21 18:30:37 warmerda
* added header write/update public methods
*
* Revision 1.39 2002/08/26 06:46:56 warmerda
* avoid c++ comments
*
* Revision 1.38 2002/05/07 16:43:39 warmerda
* Removed debugging printf.
*
* Revision 1.37 2002/04/10 17:35:22 warmerda
* fixed bug in ring reversal code
*
* Revision 1.36 2002/04/10 16:59:54 warmerda
* added SHPRewindObject
*
* Revision 1.35 2001/12/07 15:10:44 warmerda
* fix if .shx fails to open
*
* Revision 1.34 2001/11/01 16:29:55 warmerda
* move pabyRec into SHPInfo for thread safety
*
* Revision 1.33 2001/07/03 12:18:15 warmerda
* Improved cleanup if SHX not found, provied by Riccardo Cohen.
*
* Revision 1.32 2001/06/22 01:58:07 warmerda
* be more careful about establishing initial bounds in face of NULL shapes
*
* Revision 1.31 2001/05/31 19:35:29 warmerda
* added support for writing null shapes
*
* Revision 1.30 2001/05/28 12:46:29 warmerda
* Add some checking on reasonableness of record count when opening.
*
* Revision 1.29 2001/05/23 13:36:52 warmerda
* added use of SHPAPI_CALL
*
* Revision 1.28 2001/02/06 22:25:06 warmerda
* fixed memory leaks when SHPOpen() fails
*
* Revision 1.27 2000/07/18 15:21:33 warmerda
* added better enforcement of -1 for append in SHPWriteObject
*
* Revision 1.26 2000/02/16 16:03:51 warmerda
* added null shape support
*
* Revision 1.25 1999/12/15 13:47:07 warmerda
* Fixed record size settings in .shp file (was 4 words too long)
* Added stdlib.h.
*
* Revision 1.24 1999/11/05 14:12:04 warmerda
* updated license terms
*
* Revision 1.23 1999/07/27 00:53:46 warmerda
* added support for rewriting shapes
*
* Revision 1.22 1999/06/11 19:19:11 warmerda
* Cleanup pabyRec static buffer on SHPClose().
*
* Revision 1.21 1999/06/02 14:57:56 kshih
* Remove unused variables
*
* Revision 1.20 1999/04/19 21:04:17 warmerda
* Fixed syntax error.
*
* Revision 1.19 1999/04/19 21:01:57 warmerda
* Force access string to binary in SHPOpen().
*
* Revision 1.18 1999/04/01 18:48:07 warmerda
* Try upper case extensions if lower case doesn't work.
*
* Revision 1.17 1998/12/31 15:29:39 warmerda
* Disable writing measure values to multipatch objects if
* DISABLE_MULTIPATCH_MEASURE is defined.
*
* Revision 1.16 1998/12/16 05:14:33 warmerda
* Added support to write MULTIPATCH. Fixed reading Z coordinate of
* MULTIPATCH. Fixed record size written for all feature types.
*
* Revision 1.15 1998/12/03 16:35:29 warmerda
* r+b is proper binary access string, not rb+.
*
* Revision 1.14 1998/12/03 15:47:56 warmerda
* Fixed setting of nVertices in SHPCreateObject().
*
* Revision 1.13 1998/12/03 15:33:54 warmerda
* Made SHPCalculateExtents() separately callable.
*
* Revision 1.12 1998/11/11 20:01:50 warmerda
* Fixed bug writing ArcM/Z, and PolygonM/Z for big endian machines.
*
* Revision 1.11 1998/11/09 20:56:44 warmerda
* Fixed up handling of file wide bounds.
*
* Revision 1.10 1998/11/09 20:18:51 warmerda
* Converted to support 3D shapefiles, and use of SHPObject.
*
* Revision 1.9 1998/02/24 15:09:05 warmerda
* Fixed memory leak.
*
* Revision 1.8 1997/12/04 15:40:29 warmerda
* Fixed byte swapping of record number, and record length fields in the
* .shp file.
*
* Revision 1.7 1995/10/21 03:15:58 warmerda
* Added support for binary file access, the magic cookie 9997
* and tried to improve the int32 selection logic for 16bit systems.
*
* Revision 1.6 1995/09/04 04:19:41 warmerda
* Added fix for file bounds.
*
* Revision 1.5 1995/08/25 15:16:44 warmerda
* Fixed a couple of problems with big endian systems ... one with bounds
* and the other with multipart polygons.
*
* Revision 1.4 1995/08/24 18:10:17 warmerda
* Switch to use SfRealloc() to avoid problems with pre-ANSI realloc()
* functions (such as on the Sun).
*
* Revision 1.3 1995/08/23 02:23:15 warmerda
* Added support for reading bounds, and fixed up problems in setting the
* file wide bounds.
*
* Revision 1.2 1995/08/04 03:16:57 warmerda
* Added header.
*
*/
#include "shapefil.h"
#include <math.h>
#include <limits.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
SHP_CVSID("$Id: shpopen.c,v 1.60 2009-09-17 20:50:02 bram Exp $")
typedef unsigned char uchar;
#if UINT_MAX == 65535
typedef long int32;
#else
typedef int int32;
#endif
#ifndef FALSE
# define FALSE 0
# define TRUE 1
#endif
#define ByteCopy( a, b, c ) memcpy( b, a, c )
#ifndef MAX
# define MIN(a,b) ((a<b) ? a : b)
# define MAX(a,b) ((a>b) ? a : b)
#endif
#if defined(WIN32) || defined(_WIN32)
# ifndef snprintf
# define snprintf _snprintf
# endif
#endif
static int bBigEndian;
/************************************************************************/
/* SwapWord() */
/* */
/* Swap a 2, 4 or 8 byte word. */
/************************************************************************/
static void SwapWord( int length, void * wordP )
{
int i;
uchar temp;
for( i=0; i < length/2; i++ )
{
temp = ((uchar *) wordP)[i];
((uchar *)wordP)[i] = ((uchar *) wordP)[length-i-1];
((uchar *) wordP)[length-i-1] = temp;
}
}
/************************************************************************/
/* SfRealloc() */
/* */
/* A realloc cover function that will access a NULL pointer as */
/* a valid input. */
/************************************************************************/
static void * SfRealloc( void * pMem, int nNewSize )
{
if( pMem == NULL )
return( (void *) malloc(nNewSize) );
else
return( (void *) realloc(pMem,nNewSize) );
}
/************************************************************************/
/* SHPWriteHeader() */
/* */
/* Write out a header for the .shp and .shx files as well as the */
/* contents of the index (.shx) file. */
/************************************************************************/
void SHPWriteHeader( SHPHandle psSHP )
{
uchar abyHeader[100];
int i;
int32 i32;
double dValue;
int32 *panSHX;
if (psSHP->fpSHX == NULL)
{
psSHP->sHooks.Error( "SHPWriteHeader failed : SHX file is closed");
return;
}
/* -------------------------------------------------------------------- */
/* Prepare header block for .shp file. */
/* -------------------------------------------------------------------- */
for( i = 0; i < 100; i++ )
abyHeader[i] = 0;
abyHeader[2] = 0x27; /* magic cookie */
abyHeader[3] = 0x0a;
i32 = psSHP->nFileSize/2; /* file size */
ByteCopy( &i32, abyHeader+24, 4 );
if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
i32 = 1000; /* version */
ByteCopy( &i32, abyHeader+28, 4 );
if( bBigEndian ) SwapWord( 4, abyHeader+28 );
i32 = psSHP->nShapeType; /* shape type */
ByteCopy( &i32, abyHeader+32, 4 );
if( bBigEndian ) SwapWord( 4, abyHeader+32 );
dValue = psSHP->adBoundsMin[0]; /* set bounds */
ByteCopy( &dValue, abyHeader+36, 8 );
if( bBigEndian ) SwapWord( 8, abyHeader+36 );
dValue = psSHP->adBoundsMin[1];
ByteCopy( &dValue, abyHeader+44, 8 );
if( bBigEndian ) SwapWord( 8, abyHeader+44 );
dValue = psSHP->adBoundsMax[0];
ByteCopy( &dValue, abyHeader+52, 8 );
if( bBigEndian ) SwapWord( 8, abyHeader+52 );
dValue = psSHP->adBoundsMax[1];
ByteCopy( &dValue, abyHeader+60, 8 );
if( bBigEndian ) SwapWord( 8, abyHeader+60 );
dValue = psSHP->adBoundsMin[2]; /* z */
ByteCopy( &dValue, abyHeader+68, 8 );
if( bBigEndian ) SwapWord( 8, abyHeader+68 );
dValue = psSHP->adBoundsMax[2];
ByteCopy( &dValue, abyHeader+76, 8 );
if( bBigEndian ) SwapWord( 8, abyHeader+76 );
dValue = psSHP->adBoundsMin[3]; /* m */
ByteCopy( &dValue, abyHeader+84, 8 );
if( bBigEndian ) SwapWord( 8, abyHeader+84 );
dValue = psSHP->adBoundsMax[3];
ByteCopy( &dValue, abyHeader+92, 8 );
if( bBigEndian ) SwapWord( 8, abyHeader+92 );
/* -------------------------------------------------------------------- */
/* Write .shp file header. */
/* -------------------------------------------------------------------- */
if( psSHP->sHooks.FSeek( psSHP->fpSHP, 0, 0 ) != 0
|| psSHP->sHooks.FWrite( abyHeader, 100, 1, psSHP->fpSHP ) != 1 )
{
psSHP->sHooks.Error( "Failure writing .shp header" );
return;
}
/* -------------------------------------------------------------------- */
/* Prepare, and write .shx file header. */
/* -------------------------------------------------------------------- */
i32 = (psSHP->nRecords * 2 * sizeof(int32) + 100)/2; /* file size */
ByteCopy( &i32, abyHeader+24, 4 );
if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
if( psSHP->sHooks.FSeek( psSHP->fpSHX, 0, 0 ) != 0
|| psSHP->sHooks.FWrite( abyHeader, 100, 1, psSHP->fpSHX ) != 1 )
{
psSHP->sHooks.Error( "Failure writing .shx header" );
return;
}
/* -------------------------------------------------------------------- */
/* Write out the .shx contents. */
/* -------------------------------------------------------------------- */
panSHX = (int32 *) malloc(sizeof(int32) * 2 * psSHP->nRecords);
for( i = 0; i < psSHP->nRecords; i++ )
{
panSHX[i*2 ] = psSHP->panRecOffset[i]/2;
panSHX[i*2+1] = psSHP->panRecSize[i]/2;
if( !bBigEndian ) SwapWord( 4, panSHX+i*2 );
if( !bBigEndian ) SwapWord( 4, panSHX+i*2+1 );
}
if( (int)psSHP->sHooks.FWrite( panSHX, sizeof(int32)*2, psSHP->nRecords, psSHP->fpSHX )
!= psSHP->nRecords )
{
psSHP->sHooks.Error( "Failure writing .shx contents" );
}
free( panSHX );
/* -------------------------------------------------------------------- */
/* Flush to disk. */
/* -------------------------------------------------------------------- */
psSHP->sHooks.FFlush( psSHP->fpSHP );
psSHP->sHooks.FFlush( psSHP->fpSHX );
}
/************************************************************************/
/* SHPOpen() */
/************************************************************************/
SHPHandle SHPAPI_CALL
SHPOpen( const char * pszLayer, const char * pszAccess )
{
SAHooks sHooks;
SASetupDefaultHooks( &sHooks );
return SHPOpenLL( pszLayer, pszAccess, &sHooks );
}
/************************************************************************/
/* SHPOpen() */
/* */
/* Open the .shp and .shx files based on the basename of the */
/* files or either file name. */
/************************************************************************/
SHPHandle SHPAPI_CALL
SHPOpenLL( const char * pszLayer, const char * pszAccess, SAHooks *psHooks )
{
char *pszFullname, *pszBasename;
SHPHandle psSHP;
uchar *pabyBuf;
int i;
double dValue;
/* -------------------------------------------------------------------- */
/* Ensure the access string is one of the legal ones. We */
/* ensure the result string indicates binary to avoid common */
/* problems on Windows. */
/* -------------------------------------------------------------------- */
if( strcmp(pszAccess,"rb+") == 0 || strcmp(pszAccess,"r+b") == 0
|| strcmp(pszAccess,"r+") == 0 )
pszAccess = "r+b";
else
pszAccess = "rb";
/* -------------------------------------------------------------------- */
/* Establish the byte order on this machine. */
/* -------------------------------------------------------------------- */
i = 1;
if( *((uchar *) &i) == 1 )
bBigEndian = FALSE;
else
bBigEndian = TRUE;
/* -------------------------------------------------------------------- */
/* Initialize the info structure. */
/* -------------------------------------------------------------------- */
psSHP = (SHPHandle) calloc(sizeof(SHPInfo),1);
psSHP->bUpdated = FALSE;
memcpy( &(psSHP->sHooks), psHooks, sizeof(SAHooks) );
/* -------------------------------------------------------------------- */
/* Compute the base (layer) name. If there is any extension */
/* on the passed in filename we will strip it off. */
/* -------------------------------------------------------------------- */
pszBasename = (char *) malloc(strlen(pszLayer)+5);
strcpy( pszBasename, pszLayer );
for( i = strlen(pszBasename)-1;
i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
&& pszBasename[i] != '\\';
i-- ) {}
if( pszBasename[i] == '.' )
pszBasename[i] = '\0';
/* -------------------------------------------------------------------- */
/* Open the .shp and .shx files. Note that files pulled from */
/* a PC to Unix with upper case filenames won't work! */
/* -------------------------------------------------------------------- */
pszFullname = (char *) malloc(strlen(pszBasename) + 5);
sprintf( pszFullname, "%s.shp", pszBasename ) ;
psSHP->fpSHP = psSHP->sHooks.FOpen(pszFullname, pszAccess );
if( psSHP->fpSHP == NULL )
{
sprintf( pszFullname, "%s.SHP", pszBasename );
psSHP->fpSHP = psSHP->sHooks.FOpen(pszFullname, pszAccess );
}
if( psSHP->fpSHP == NULL )
{
#ifdef USE_CPL
CPLError( CE_Failure, CPLE_OpenFailed,
"Unable to open %s.shp or %s.SHP.",
pszBasename, pszBasename );
#endif
free( psSHP );
free( pszBasename );
free( pszFullname );
return( NULL );
}
sprintf( pszFullname, "%s.shx", pszBasename );
psSHP->fpSHX = psSHP->sHooks.FOpen(pszFullname, pszAccess );
if( psSHP->fpSHX == NULL )
{
sprintf( pszFullname, "%s.SHX", pszBasename );
psSHP->fpSHX = psSHP->sHooks.FOpen(pszFullname, pszAccess );
}
if( psSHP->fpSHX == NULL )
{
#ifdef USE_CPL
CPLError( CE_Failure, CPLE_OpenFailed,
"Unable to open %s.shx or %s.SHX.",
pszBasename, pszBasename );
#endif
psSHP->sHooks.FClose( psSHP->fpSHP );
free( psSHP );
free( pszBasename );
free( pszFullname );
return( NULL );
}
free( pszFullname );
free( pszBasename );
/* -------------------------------------------------------------------- */
/* Read the file size from the SHP file. */
/* -------------------------------------------------------------------- */
pabyBuf = (uchar *) malloc(100);
psSHP->sHooks.FRead( pabyBuf, 100, 1, psSHP->fpSHP );
psSHP->nFileSize = (pabyBuf[24] * 256 * 256 * 256
+ pabyBuf[25] * 256 * 256
+ pabyBuf[26] * 256
+ pabyBuf[27]) * 2;
/* -------------------------------------------------------------------- */
/* Read SHX file Header info */
/* -------------------------------------------------------------------- */
if( psSHP->sHooks.FRead( pabyBuf, 100, 1, psSHP->fpSHX ) != 1
|| pabyBuf[0] != 0
|| pabyBuf[1] != 0
|| pabyBuf[2] != 0x27
|| (pabyBuf[3] != 0x0a && pabyBuf[3] != 0x0d) )
{
psSHP->sHooks.Error( ".shx file is unreadable, or corrupt." );
psSHP->sHooks.FClose( psSHP->fpSHP );
psSHP->sHooks.FClose( psSHP->fpSHX );
free( psSHP );
return( NULL );
}
psSHP->nRecords = pabyBuf[27] + pabyBuf[26] * 256
+ pabyBuf[25] * 256 * 256 + pabyBuf[24] * 256 * 256 * 256;
psSHP->nRecords = (psSHP->nRecords*2 - 100) / 8;
psSHP->nShapeType = pabyBuf[32];
if( psSHP->nRecords < 0 || psSHP->nRecords > 256000000 )
{
char szError[200];
sprintf( szError,
"Record count in .shp header is %d, which seems\n"
"unreasonable. Assuming header is corrupt.",
psSHP->nRecords );
psSHP->sHooks.Error( szError );
psSHP->sHooks.FClose( psSHP->fpSHP );
psSHP->sHooks.FClose( psSHP->fpSHX );
free( psSHP );
free(pabyBuf);
return( NULL );
}
/* -------------------------------------------------------------------- */
/* Read the bounds. */
/* -------------------------------------------------------------------- */
if( bBigEndian ) SwapWord( 8, pabyBuf+36 );
memcpy( &dValue, pabyBuf+36, 8 );
psSHP->adBoundsMin[0] = dValue;
if( bBigEndian ) SwapWord( 8, pabyBuf+44 );
memcpy( &dValue, pabyBuf+44, 8 );
psSHP->adBoundsMin[1] = dValue;
if( bBigEndian ) SwapWord( 8, pabyBuf+52 );
memcpy( &dValue, pabyBuf+52, 8 );
psSHP->adBoundsMax[0] = dValue;
if( bBigEndian ) SwapWord( 8, pabyBuf+60 );
memcpy( &dValue, pabyBuf+60, 8 );
psSHP->adBoundsMax[1] = dValue;
if( bBigEndian ) SwapWord( 8, pabyBuf+68 ); /* z */
memcpy( &dValue, pabyBuf+68, 8 );
psSHP->adBoundsMin[2] = dValue;
if( bBigEndian ) SwapWord( 8, pabyBuf+76 );
memcpy( &dValue, pabyBuf+76, 8 );
psSHP->adBoundsMax[2] = dValue;
if( bBigEndian ) SwapWord( 8, pabyBuf+84 ); /* z */
memcpy( &dValue, pabyBuf+84, 8 );
psSHP->adBoundsMin[3] = dValue;
if( bBigEndian ) SwapWord( 8, pabyBuf+92 );
memcpy( &dValue, pabyBuf+92, 8 );
psSHP->adBoundsMax[3] = dValue;
free( pabyBuf );
/* -------------------------------------------------------------------- */
/* Read the .shx file to get the offsets to each record in */
/* the .shp file. */
/* -------------------------------------------------------------------- */
psSHP->nMaxRecords = psSHP->nRecords;
psSHP->panRecOffset =
(int *) malloc(sizeof(int) * MAX(1,psSHP->nMaxRecords) );
psSHP->panRecSize =
(int *) malloc(sizeof(int) * MAX(1,psSHP->nMaxRecords) );
pabyBuf = (uchar *) malloc(8 * MAX(1,psSHP->nRecords) );
if (psSHP->panRecOffset == NULL ||
psSHP->panRecSize == NULL ||
pabyBuf == NULL)
{
char szError[200];
sprintf(szError,
"Not enough memory to allocate requested memory (nRecords=%d).\n"
"Probably broken SHP file",
psSHP->nRecords );
psSHP->sHooks.Error( szError );
psSHP->sHooks.FClose( psSHP->fpSHP );
psSHP->sHooks.FClose( psSHP->fpSHX );
if (psSHP->panRecOffset) free( psSHP->panRecOffset );
if (psSHP->panRecSize) free( psSHP->panRecSize );
if (pabyBuf) free( pabyBuf );
free( psSHP );
return( NULL );
}
if( (int) psSHP->sHooks.FRead( pabyBuf, 8, psSHP->nRecords, psSHP->fpSHX )
!= psSHP->nRecords )
{
char szError[200];
sprintf( szError,
"Failed to read all values for %d records in .shx file.",
psSHP->nRecords );
psSHP->sHooks.Error( szError );
/* SHX is short or unreadable for some reason. */
psSHP->sHooks.FClose( psSHP->fpSHP );
psSHP->sHooks.FClose( psSHP->fpSHX );
free( psSHP->panRecOffset );
free( psSHP->panRecSize );
free( pabyBuf );
free( psSHP );
return( NULL );
}
/* In read-only mode, we can close the SHX now */
if (strcmp(pszAccess, "rb") == 0)
{
psSHP->sHooks.FClose( psSHP->fpSHX );
psSHP->fpSHX = NULL;
}
for( i = 0; i < psSHP->nRecords; i++ )
{
int32 nOffset, nLength;
memcpy( &nOffset, pabyBuf + i * 8, 4 );
if( !bBigEndian ) SwapWord( 4, &nOffset );
memcpy( &nLength, pabyBuf + i * 8 + 4, 4 );
if( !bBigEndian ) SwapWord( 4, &nLength );
psSHP->panRecOffset[i] = nOffset*2;
psSHP->panRecSize[i] = nLength*2;
}
free( pabyBuf );
return( psSHP );
}
/************************************************************************/
/* SHPClose() */
/* */
/* Close the .shp and .shx files. */
/************************************************************************/
void SHPAPI_CALL
SHPClose(SHPHandle psSHP )
{
if( psSHP == NULL )
return;
/* -------------------------------------------------------------------- */
/* Update the header if we have modified anything. */
/* -------------------------------------------------------------------- */
if( psSHP->bUpdated )
SHPWriteHeader( psSHP );
/* -------------------------------------------------------------------- */
/* Free all resources, and close files. */
/* -------------------------------------------------------------------- */
free( psSHP->panRecOffset );
free( psSHP->panRecSize );
if ( psSHP->fpSHX != NULL)
psSHP->sHooks.FClose( psSHP->fpSHX );
psSHP->sHooks.FClose( psSHP->fpSHP );
if( psSHP->pabyRec != NULL )
{
free( psSHP->pabyRec );
}
free( psSHP );
}
/************************************************************************/
/* SHPGetInfo() */
/* */
/* Fetch general information about the shape file. */
/************************************************************************/
void SHPAPI_CALL
SHPGetInfo(SHPHandle psSHP, int * pnEntities, int * pnShapeType,
double * padfMinBound, double * padfMaxBound )
{
int i;
if( psSHP == NULL )
return;
if( pnEntities != NULL )
*pnEntities = psSHP->nRecords;
if( pnShapeType != NULL )
*pnShapeType = psSHP->nShapeType;
for( i = 0; i < 4; i++ )
{
if( padfMinBound != NULL )
padfMinBound[i] = psSHP->adBoundsMin[i];
if( padfMaxBound != NULL )
padfMaxBound[i] = psSHP->adBoundsMax[i];
}
}
/************************************************************************/
/* SHPCreate() */
/* */
/* Create a new shape file and return a handle to the open */
/* shape file with read/write access. */
/************************************************************************/
SHPHandle SHPAPI_CALL
SHPCreate( const char * pszLayer, int nShapeType )
{
SAHooks sHooks;
SASetupDefaultHooks( &sHooks );
return SHPCreateLL( pszLayer, nShapeType, &sHooks );
}
/************************************************************************/
/* SHPCreate() */
/* */
/* Create a new shape file and return a handle to the open */
/* shape file with read/write access. */
/************************************************************************/
SHPHandle SHPAPI_CALL
SHPCreateLL( const char * pszLayer, int nShapeType, SAHooks *psHooks )
{
char *pszBasename, *pszFullname;
int i;
SAFile fpSHP, fpSHX;
uchar abyHeader[100];
int32 i32;
double dValue;
/* -------------------------------------------------------------------- */
/* Establish the byte order on this system. */
/* -------------------------------------------------------------------- */
i = 1;
if( *((uchar *) &i) == 1 )
bBigEndian = FALSE;
else
bBigEndian = TRUE;
/* -------------------------------------------------------------------- */
/* Compute the base (layer) name. If there is any extension */
/* on the passed in filename we will strip it off. */
/* -------------------------------------------------------------------- */
pszBasename = (char *) malloc(strlen(pszLayer)+5);
strcpy( pszBasename, pszLayer );
for( i = strlen(pszBasename)-1;
i > 0 && pszBasename[i] != '.' && pszBasename[i] != '/'
&& pszBasename[i] != '\\';
i-- ) {}
if( pszBasename[i] == '.' )
pszBasename[i] = '\0';
/* -------------------------------------------------------------------- */
/* Open the two files so we can write their headers. */
/* -------------------------------------------------------------------- */
pszFullname = (char *) malloc(strlen(pszBasename) + 5);
sprintf( pszFullname, "%s.shp", pszBasename );
fpSHP = psHooks->FOpen(pszFullname, "wb" );
if( fpSHP == NULL )
{
psHooks->Error( "Failed to create file .shp file." );
return( NULL );
}
sprintf( pszFullname, "%s.shx", pszBasename );
fpSHX = psHooks->FOpen(pszFullname, "wb" );
if( fpSHX == NULL )
{
psHooks->Error( "Failed to create file .shx file." );
return( NULL );
}
free( pszFullname );
free( pszBasename );
/* -------------------------------------------------------------------- */
/* Prepare header block for .shp file. */
/* -------------------------------------------------------------------- */
for( i = 0; i < 100; i++ )
abyHeader[i] = 0;
abyHeader[2] = 0x27; /* magic cookie */
abyHeader[3] = 0x0a;
i32 = 50; /* file size */
ByteCopy( &i32, abyHeader+24, 4 );
if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
i32 = 1000; /* version */
ByteCopy( &i32, abyHeader+28, 4 );
if( bBigEndian ) SwapWord( 4, abyHeader+28 );
i32 = nShapeType; /* shape type */
ByteCopy( &i32, abyHeader+32, 4 );
if( bBigEndian ) SwapWord( 4, abyHeader+32 );
dValue = 0.0; /* set bounds */
ByteCopy( &dValue, abyHeader+36, 8 );
ByteCopy( &dValue, abyHeader+44, 8 );
ByteCopy( &dValue, abyHeader+52, 8 );
ByteCopy( &dValue, abyHeader+60, 8 );
/* -------------------------------------------------------------------- */
/* Write .shp file header. */
/* -------------------------------------------------------------------- */
if( psHooks->FWrite( abyHeader, 100, 1, fpSHP ) != 1 )
{
psHooks->Error( "Failed to write .shp header." );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Prepare, and write .shx file header. */
/* -------------------------------------------------------------------- */
i32 = 50; /* file size */
ByteCopy( &i32, abyHeader+24, 4 );
if( !bBigEndian ) SwapWord( 4, abyHeader+24 );
if( psHooks->FWrite( abyHeader, 100, 1, fpSHX ) != 1 )
{
psHooks->Error( "Failed to write .shx header." );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Close the files, and then open them as regular existing files. */
/* -------------------------------------------------------------------- */
psHooks->FClose( fpSHP );
psHooks->FClose( fpSHX );
return( SHPOpenLL( pszLayer, "r+b", psHooks ) );
}
/************************************************************************/
/* _SHPSetBounds() */
/* */
/* Compute a bounds rectangle for a shape, and set it into the */
/* indicated location in the record. */
/************************************************************************/
static void _SHPSetBounds( uchar * pabyRec, SHPObject * psShape )
{
ByteCopy( &(psShape->dfXMin), pabyRec + 0, 8 );
ByteCopy( &(psShape->dfYMin), pabyRec + 8, 8 );
ByteCopy( &(psShape->dfXMax), pabyRec + 16, 8 );
ByteCopy( &(psShape->dfYMax), pabyRec + 24, 8 );
if( bBigEndian )
{
SwapWord( 8, pabyRec + 0 );
SwapWord( 8, pabyRec + 8 );
SwapWord( 8, pabyRec + 16 );
SwapWord( 8, pabyRec + 24 );
}
}
/************************************************************************/
/* SHPComputeExtents() */
/* */
/* Recompute the extents of a shape. Automatically done by */
/* SHPCreateObject(). */
/************************************************************************/
void SHPAPI_CALL
SHPComputeExtents( SHPObject * psObject )
{
int i;
/* -------------------------------------------------------------------- */
/* Build extents for this object. */
/* -------------------------------------------------------------------- */
if( psObject->nVertices > 0 )
{
psObject->dfXMin = psObject->dfXMax = psObject->padfX[0];
psObject->dfYMin = psObject->dfYMax = psObject->padfY[0];
psObject->dfZMin = psObject->dfZMax = psObject->padfZ[0];
psObject->dfMMin = psObject->dfMMax = psObject->padfM[0];
}
for( i = 0; i < psObject->nVertices; i++ )
{
psObject->dfXMin = MIN(psObject->dfXMin, psObject->padfX[i]);
psObject->dfYMin = MIN(psObject->dfYMin, psObject->padfY[i]);
psObject->dfZMin = MIN(psObject->dfZMin, psObject->padfZ[i]);
psObject->dfMMin = MIN(psObject->dfMMin, psObject->padfM[i]);
psObject->dfXMax = MAX(psObject->dfXMax, psObject->padfX[i]);
psObject->dfYMax = MAX(psObject->dfYMax, psObject->padfY[i]);
psObject->dfZMax = MAX(psObject->dfZMax, psObject->padfZ[i]);
psObject->dfMMax = MAX(psObject->dfMMax, psObject->padfM[i]);
}
}
/************************************************************************/
/* SHPCreateObject() */
/* */
/* Create a shape object. It should be freed with */
/* SHPDestroyObject(). */
/************************************************************************/
SHPObject SHPAPI_CALL1(*)
SHPCreateObject( int nSHPType, int nShapeId, int nParts,
const int * panPartStart, const int * panPartType,
int nVertices, const double *padfX, const double *padfY,
const double * padfZ, const double * padfM )
{
SHPObject *psObject;
int i, bHasM, bHasZ;
psObject = (SHPObject *) calloc(1,sizeof(SHPObject));
psObject->nSHPType = nSHPType;
psObject->nShapeId = nShapeId;
psObject->bMeasureIsUsed = FALSE;
/* -------------------------------------------------------------------- */
/* Establish whether this shape type has M, and Z values. */
/* -------------------------------------------------------------------- */
if( nSHPType == SHPT_ARCM
|| nSHPType == SHPT_POINTM
|| nSHPType == SHPT_POLYGONM
|| nSHPType == SHPT_MULTIPOINTM )
{
bHasM = TRUE;
bHasZ = FALSE;
}
else if( nSHPType == SHPT_ARCZ
|| nSHPType == SHPT_POINTZ
|| nSHPType == SHPT_POLYGONZ
|| nSHPType == SHPT_MULTIPOINTZ
|| nSHPType == SHPT_MULTIPATCH )
{
bHasM = TRUE;
bHasZ = TRUE;
}
else
{
bHasM = FALSE;
bHasZ = FALSE;
}
/* -------------------------------------------------------------------- */
/* Capture parts. Note that part type is optional, and */
/* defaults to ring. */
/* -------------------------------------------------------------------- */
if( nSHPType == SHPT_ARC || nSHPType == SHPT_POLYGON
|| nSHPType == SHPT_ARCM || nSHPType == SHPT_POLYGONM
|| nSHPType == SHPT_ARCZ || nSHPType == SHPT_POLYGONZ
|| nSHPType == SHPT_MULTIPATCH )
{
psObject->nParts = MAX(1,nParts);
psObject->panPartStart = (int *)
malloc(sizeof(int) * psObject->nParts);
psObject->panPartType = (int *)
malloc(sizeof(int) * psObject->nParts);
psObject->panPartStart[0] = 0;
psObject->panPartType[0] = SHPP_RING;
for( i = 0; i < nParts; i++ )
{
psObject->panPartStart[i] = panPartStart[i];
if( panPartType != NULL )
psObject->panPartType[i] = panPartType[i];
else
psObject->panPartType[i] = SHPP_RING;
}
if( psObject->panPartStart[0] != 0 )
psObject->panPartStart[0] = 0;
}
/* -------------------------------------------------------------------- */
/* Capture vertices. Note that Z and M are optional, but X and */
/* Y are not. */
/* -------------------------------------------------------------------- */
if( nVertices > 0 )
{
psObject->padfX = (double *) calloc(sizeof(double),nVertices);
psObject->padfY = (double *) calloc(sizeof(double),nVertices);
psObject->padfZ = (double *) calloc(sizeof(double),nVertices);
psObject->padfM = (double *) calloc(sizeof(double),nVertices);
assert( padfX != NULL );
assert( padfY != NULL );
for( i = 0; i < nVertices; i++ )
{
psObject->padfX[i] = padfX[i];
psObject->padfY[i] = padfY[i];
if( padfZ != NULL && bHasZ )
psObject->padfZ[i] = padfZ[i];
if( padfM != NULL && bHasM )
psObject->padfM[i] = padfM[i];
}
if( padfM != NULL && bHasM )
psObject->bMeasureIsUsed = TRUE;
}
/* -------------------------------------------------------------------- */
/* Compute the extents. */
/* -------------------------------------------------------------------- */
psObject->nVertices = nVertices;
SHPComputeExtents( psObject );
return( psObject );
}
/************************************************************************/
/* SHPCreateSimpleObject() */
/* */
/* Create a simple (common) shape object. Destroy with */
/* SHPDestroyObject(). */
/************************************************************************/
SHPObject SHPAPI_CALL1(*)
SHPCreateSimpleObject( int nSHPType, int nVertices,
const double * padfX, const double * padfY,
const double * padfZ )
{
return( SHPCreateObject( nSHPType, -1, 0, NULL, NULL,
nVertices, padfX, padfY, padfZ, NULL ) );
}
/************************************************************************/
/* SHPWriteObject() */
/* */
/* Write out the vertices of a new structure. Note that it is */
/* only possible to write vertices at the end of the file. */
/************************************************************************/
int SHPAPI_CALL
SHPWriteObject(SHPHandle psSHP, int nShapeId, SHPObject * psObject )
{
int nRecordOffset, i, nRecordSize=0;
uchar *pabyRec;
int32 i32;
psSHP->bUpdated = TRUE;
/* -------------------------------------------------------------------- */
/* Ensure that shape object matches the type of the file it is */
/* being written to. */
/* -------------------------------------------------------------------- */
assert( psObject->nSHPType == psSHP->nShapeType
|| psObject->nSHPType == SHPT_NULL );
/* -------------------------------------------------------------------- */
/* Ensure that -1 is used for appends. Either blow an */
/* assertion, or if they are disabled, set the shapeid to -1 */
/* for appends. */
/* -------------------------------------------------------------------- */
assert( nShapeId == -1
|| (nShapeId >= 0 && nShapeId < psSHP->nRecords) );
if( nShapeId != -1 && nShapeId >= psSHP->nRecords )
nShapeId = -1;
/* -------------------------------------------------------------------- */
/* Add the new entity to the in memory index. */
/* -------------------------------------------------------------------- */
if( nShapeId == -1 && psSHP->nRecords+1 > psSHP->nMaxRecords )
{
psSHP->nMaxRecords =(int) ( psSHP->nMaxRecords * 1.3 + 100);
psSHP->panRecOffset = (int *)
SfRealloc(psSHP->panRecOffset,sizeof(int) * psSHP->nMaxRecords );
psSHP->panRecSize = (int *)
SfRealloc(psSHP->panRecSize,sizeof(int) * psSHP->nMaxRecords );
}
/* -------------------------------------------------------------------- */
/* Initialize record. */
/* -------------------------------------------------------------------- */
pabyRec = (uchar *) malloc(psObject->nVertices * 4 * sizeof(double)
+ psObject->nParts * 8 + 128);
/* -------------------------------------------------------------------- */
/* Extract vertices for a Polygon or Arc. */
/* -------------------------------------------------------------------- */
if( psObject->nSHPType == SHPT_POLYGON
|| psObject->nSHPType == SHPT_POLYGONZ
|| psObject->nSHPType == SHPT_POLYGONM
|| psObject->nSHPType == SHPT_ARC
|| psObject->nSHPType == SHPT_ARCZ
|| psObject->nSHPType == SHPT_ARCM
|| psObject->nSHPType == SHPT_MULTIPATCH )
{
int32 nPoints, nParts;
int i;
nPoints = psObject->nVertices;
nParts = psObject->nParts;
_SHPSetBounds( pabyRec + 12, psObject );
if( bBigEndian ) SwapWord( 4, &nPoints );
if( bBigEndian ) SwapWord( 4, &nParts );
ByteCopy( &nPoints, pabyRec + 40 + 8, 4 );
ByteCopy( &nParts, pabyRec + 36 + 8, 4 );
nRecordSize = 52;
/*
* Write part start positions.
*/
ByteCopy( psObject->panPartStart, pabyRec + 44 + 8,
4 * psObject->nParts );
for( i = 0; i < psObject->nParts; i++ )
{
if( bBigEndian ) SwapWord( 4, pabyRec + 44 + 8 + 4*i );
nRecordSize += 4;
}
/*
* Write multipatch part types if needed.
*/
if( psObject->nSHPType == SHPT_MULTIPATCH )
{
memcpy( pabyRec + nRecordSize, psObject->panPartType,
4*psObject->nParts );
for( i = 0; i < psObject->nParts; i++ )
{
if( bBigEndian ) SwapWord( 4, pabyRec + nRecordSize );
nRecordSize += 4;
}
}
/*
* Write the (x,y) vertex values.
*/
for( i = 0; i < psObject->nVertices; i++ )
{
ByteCopy( psObject->padfX + i, pabyRec + nRecordSize, 8 );
ByteCopy( psObject->padfY + i, pabyRec + nRecordSize + 8, 8 );
if( bBigEndian )
SwapWord( 8, pabyRec + nRecordSize );
if( bBigEndian )
SwapWord( 8, pabyRec + nRecordSize + 8 );
nRecordSize += 2 * 8;
}
/*
* Write the Z coordinates (if any).
*/
if( psObject->nSHPType == SHPT_POLYGONZ
|| psObject->nSHPType == SHPT_ARCZ
|| psObject->nSHPType == SHPT_MULTIPATCH )
{
ByteCopy( &(psObject->dfZMin), pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
ByteCopy( &(psObject->dfZMax), pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
for( i = 0; i < psObject->nVertices; i++ )
{
ByteCopy( psObject->padfZ + i, pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
}
}
/*
* Write the M values, if any.
*/
if( psObject->bMeasureIsUsed
&& (psObject->nSHPType == SHPT_POLYGONM
|| psObject->nSHPType == SHPT_ARCM
#ifndef DISABLE_MULTIPATCH_MEASURE
|| psObject->nSHPType == SHPT_MULTIPATCH
#endif
|| psObject->nSHPType == SHPT_POLYGONZ
|| psObject->nSHPType == SHPT_ARCZ) )
{
ByteCopy( &(psObject->dfMMin), pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
ByteCopy( &(psObject->dfMMax), pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
for( i = 0; i < psObject->nVertices; i++ )
{
ByteCopy( psObject->padfM + i, pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
}
}
}
/* -------------------------------------------------------------------- */
/* Extract vertices for a MultiPoint. */
/* -------------------------------------------------------------------- */
else if( psObject->nSHPType == SHPT_MULTIPOINT
|| psObject->nSHPType == SHPT_MULTIPOINTZ
|| psObject->nSHPType == SHPT_MULTIPOINTM )
{
int32 nPoints;
int i;
nPoints = psObject->nVertices;
_SHPSetBounds( pabyRec + 12, psObject );
if( bBigEndian ) SwapWord( 4, &nPoints );
ByteCopy( &nPoints, pabyRec + 44, 4 );
for( i = 0; i < psObject->nVertices; i++ )
{
ByteCopy( psObject->padfX + i, pabyRec + 48 + i*16, 8 );
ByteCopy( psObject->padfY + i, pabyRec + 48 + i*16 + 8, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + 48 + i*16 );
if( bBigEndian ) SwapWord( 8, pabyRec + 48 + i*16 + 8 );
}
nRecordSize = 48 + 16 * psObject->nVertices;
if( psObject->nSHPType == SHPT_MULTIPOINTZ )
{
ByteCopy( &(psObject->dfZMin), pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
ByteCopy( &(psObject->dfZMax), pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
for( i = 0; i < psObject->nVertices; i++ )
{
ByteCopy( psObject->padfZ + i, pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
}
}
if( psObject->bMeasureIsUsed
&& (psObject->nSHPType == SHPT_MULTIPOINTZ
|| psObject->nSHPType == SHPT_MULTIPOINTM) )
{
ByteCopy( &(psObject->dfMMin), pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
ByteCopy( &(psObject->dfMMax), pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
for( i = 0; i < psObject->nVertices; i++ )
{
ByteCopy( psObject->padfM + i, pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
}
}
}
/* -------------------------------------------------------------------- */
/* Write point. */
/* -------------------------------------------------------------------- */
else if( psObject->nSHPType == SHPT_POINT
|| psObject->nSHPType == SHPT_POINTZ
|| psObject->nSHPType == SHPT_POINTM )
{
ByteCopy( psObject->padfX, pabyRec + 12, 8 );
ByteCopy( psObject->padfY, pabyRec + 20, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + 12 );
if( bBigEndian ) SwapWord( 8, pabyRec + 20 );
nRecordSize = 28;
if( psObject->nSHPType == SHPT_POINTZ )
{
ByteCopy( psObject->padfZ, pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
}
if( psObject->bMeasureIsUsed
&& (psObject->nSHPType == SHPT_POINTZ
|| psObject->nSHPType == SHPT_POINTM) )
{
ByteCopy( psObject->padfM, pabyRec + nRecordSize, 8 );
if( bBigEndian ) SwapWord( 8, pabyRec + nRecordSize );
nRecordSize += 8;
}
}
/* -------------------------------------------------------------------- */
/* Not much to do for null geometries. */
/* -------------------------------------------------------------------- */
else if( psObject->nSHPType == SHPT_NULL )
{
nRecordSize = 12;
}
else
{
/* unknown type */
assert( FALSE );
}
/* -------------------------------------------------------------------- */
/* Establish where we are going to put this record. If we are */
/* rewriting and existing record, and it will fit, then put it */
/* back where the original came from. Otherwise write at the end. */
/* -------------------------------------------------------------------- */
if( nShapeId == -1 || psSHP->panRecSize[nShapeId] < nRecordSize-8 )
{
if( nShapeId == -1 )
nShapeId = psSHP->nRecords++;
psSHP->panRecOffset[nShapeId] = nRecordOffset = psSHP->nFileSize;
psSHP->panRecSize[nShapeId] = nRecordSize-8;
psSHP->nFileSize += nRecordSize;
}
else
{
nRecordOffset = psSHP->panRecOffset[nShapeId];
psSHP->panRecSize[nShapeId] = nRecordSize-8;
}
/* -------------------------------------------------------------------- */
/* Set the shape type, record number, and record size. */
/* -------------------------------------------------------------------- */
i32 = nShapeId+1; /* record # */
if( !bBigEndian ) SwapWord( 4, &i32 );
ByteCopy( &i32, pabyRec, 4 );
i32 = (nRecordSize-8)/2; /* record size */
if( !bBigEndian ) SwapWord( 4, &i32 );
ByteCopy( &i32, pabyRec + 4, 4 );
i32 = psObject->nSHPType; /* shape type */
if( bBigEndian ) SwapWord( 4, &i32 );
ByteCopy( &i32, pabyRec + 8, 4 );
/* -------------------------------------------------------------------- */
/* Write out record. */
/* -------------------------------------------------------------------- */
if( psSHP->sHooks.FSeek( psSHP->fpSHP, nRecordOffset, 0 ) != 0
|| psSHP->sHooks.FWrite( pabyRec, nRecordSize, 1, psSHP->fpSHP ) < 1 )
{
psSHP->sHooks.Error( "Error in psSHP->sHooks.FSeek() or fwrite() writing object to .shp file." );
free( pabyRec );
return -1;
}
free( pabyRec );
/* -------------------------------------------------------------------- */
/* Expand file wide bounds based on this shape. */
/* -------------------------------------------------------------------- */
if( psSHP->adBoundsMin[0] == 0.0
&& psSHP->adBoundsMax[0] == 0.0
&& psSHP->adBoundsMin[1] == 0.0
&& psSHP->adBoundsMax[1] == 0.0 )
{
if( psObject->nSHPType == SHPT_NULL || psObject->nVertices == 0 )
{
psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = 0.0;
psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = 0.0;
psSHP->adBoundsMin[2] = psSHP->adBoundsMax[2] = 0.0;
psSHP->adBoundsMin[3] = psSHP->adBoundsMax[3] = 0.0;
}
else
{
psSHP->adBoundsMin[0] = psSHP->adBoundsMax[0] = psObject->padfX[0];
psSHP->adBoundsMin[1] = psSHP->adBoundsMax[1] = psObject->padfY[0];
psSHP->adBoundsMin[2] = psSHP->adBoundsMax[2] = psObject->padfZ[0];
psSHP->adBoundsMin[3] = psSHP->adBoundsMax[3] = psObject->padfM[0];
}
}
for( i = 0; i < psObject->nVertices; i++ )
{
psSHP->adBoundsMin[0] = MIN(psSHP->adBoundsMin[0],psObject->padfX[i]);
psSHP->adBoundsMin[1] = MIN(psSHP->adBoundsMin[1],psObject->padfY[i]);
psSHP->adBoundsMin[2] = MIN(psSHP->adBoundsMin[2],psObject->padfZ[i]);
psSHP->adBoundsMin[3] = MIN(psSHP->adBoundsMin[3],psObject->padfM[i]);
psSHP->adBoundsMax[0] = MAX(psSHP->adBoundsMax[0],psObject->padfX[i]);
psSHP->adBoundsMax[1] = MAX(psSHP->adBoundsMax[1],psObject->padfY[i]);
psSHP->adBoundsMax[2] = MAX(psSHP->adBoundsMax[2],psObject->padfZ[i]);
psSHP->adBoundsMax[3] = MAX(psSHP->adBoundsMax[3],psObject->padfM[i]);
}
return( nShapeId );
}
/************************************************************************/
/* SHPReadObject() */
/* */
/* Read the vertices, parts, and other non-attribute information */
/* for one shape. */
/************************************************************************/
SHPObject SHPAPI_CALL1(*)
SHPReadObject( SHPHandle psSHP, int hEntity )
{
int nEntitySize, nRequiredSize;
SHPObject *psShape;
char pszErrorMsg[128];
/* -------------------------------------------------------------------- */
/* Validate the record/entity number. */
/* -------------------------------------------------------------------- */
if( hEntity < 0 || hEntity >= psSHP->nRecords )
return( NULL );
/* -------------------------------------------------------------------- */
/* Ensure our record buffer is large enough. */
/* -------------------------------------------------------------------- */
nEntitySize = psSHP->panRecSize[hEntity]+8;
if( nEntitySize > psSHP->nBufSize )
{
psSHP->pabyRec = (uchar *) SfRealloc(psSHP->pabyRec,nEntitySize);
if (psSHP->pabyRec == NULL)
{
char szError[200];
/* Reallocate previous successfull size for following features */
psSHP->pabyRec = (unsigned char*)malloc(psSHP->nBufSize);
sprintf( szError,
"Not enough memory to allocate requested memory (nBufSize=%d). "
"Probably broken SHP file", psSHP->nBufSize );
psSHP->sHooks.Error( szError );
return NULL;
}
/* Only set new buffer size after successfull alloc */
psSHP->nBufSize = nEntitySize;
}
/* In case we were not able to reallocate the buffer on a previous step */
if (psSHP->pabyRec == NULL)
{
return NULL;
}
/* -------------------------------------------------------------------- */
/* Read the record. */
/* -------------------------------------------------------------------- */
if( psSHP->sHooks.FSeek( psSHP->fpSHP, psSHP->panRecOffset[hEntity], 0 ) != 0
|| psSHP->sHooks.FRead( psSHP->pabyRec, nEntitySize, 1,
psSHP->fpSHP ) != 1 )
{
/*
* TODO - mloskot: Consider detailed diagnostics of shape file,
* for example to detect if file is truncated.
*/
psSHP->sHooks.Error( "Error in fseek() or fread() reading object from .shp file." );
return NULL;
}
/* -------------------------------------------------------------------- */
/* Allocate and minimally initialize the object. */
/* -------------------------------------------------------------------- */
psShape = (SHPObject *) calloc(1,sizeof(SHPObject));
psShape->nShapeId = hEntity;
psShape->bMeasureIsUsed = FALSE;
if ( 8 + 4 > nEntitySize )
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d : nEntitySize = %d",
hEntity, nEntitySize);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
memcpy( &psShape->nSHPType, psSHP->pabyRec + 8, 4 );
if( bBigEndian ) SwapWord( 4, &(psShape->nSHPType) );
/* ==================================================================== */
/* Extract vertices for a Polygon or Arc. */
/* ==================================================================== */
if( psShape->nSHPType == SHPT_POLYGON || psShape->nSHPType == SHPT_ARC
|| psShape->nSHPType == SHPT_POLYGONZ
|| psShape->nSHPType == SHPT_POLYGONM
|| psShape->nSHPType == SHPT_ARCZ
|| psShape->nSHPType == SHPT_ARCM
|| psShape->nSHPType == SHPT_MULTIPATCH )
{
int32 nPoints, nParts;
int i, nOffset;
if ( 40 + 8 + 4 > nEntitySize )
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d : nEntitySize = %d",
hEntity, nEntitySize);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
/* -------------------------------------------------------------------- */
/* Get the X/Y bounds. */
/* -------------------------------------------------------------------- */
memcpy( &(psShape->dfXMin), psSHP->pabyRec + 8 + 4, 8 );
memcpy( &(psShape->dfYMin), psSHP->pabyRec + 8 + 12, 8 );
memcpy( &(psShape->dfXMax), psSHP->pabyRec + 8 + 20, 8 );
memcpy( &(psShape->dfYMax), psSHP->pabyRec + 8 + 28, 8 );
if( bBigEndian ) SwapWord( 8, &(psShape->dfXMin) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfYMin) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfXMax) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfYMax) );
/* -------------------------------------------------------------------- */
/* Extract part/point count, and build vertex and part arrays */
/* to proper size. */
/* -------------------------------------------------------------------- */
memcpy( &nPoints, psSHP->pabyRec + 40 + 8, 4 );
memcpy( &nParts, psSHP->pabyRec + 36 + 8, 4 );
if( bBigEndian ) SwapWord( 4, &nPoints );
if( bBigEndian ) SwapWord( 4, &nParts );
if (nPoints < 0 || nParts < 0 ||
nPoints > 50 * 1000 * 1000 || nParts > 10 * 1000 * 1000)
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d, nPoints=%d, nParts=%d.",
hEntity, nPoints, nParts);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
/* With the previous checks on nPoints and nParts, */
/* we should not overflow here and after */
/* since 50 M * (16 + 8 + 8) = 1 600 MB */
nRequiredSize = 44 + 8 + 4 * nParts + 16 * nPoints;
if ( psShape->nSHPType == SHPT_POLYGONZ
|| psShape->nSHPType == SHPT_ARCZ
|| psShape->nSHPType == SHPT_MULTIPATCH )
{
nRequiredSize += 16 + 8 * nPoints;
}
if( psShape->nSHPType == SHPT_MULTIPATCH )
{
nRequiredSize += 4 * nParts;
}
if (nRequiredSize > nEntitySize)
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d, nPoints=%d, nParts=%d, nEntitySize=%d.",
hEntity, nPoints, nParts, nEntitySize);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
psShape->nVertices = nPoints;
psShape->padfX = (double *) calloc(nPoints,sizeof(double));
psShape->padfY = (double *) calloc(nPoints,sizeof(double));
psShape->padfZ = (double *) calloc(nPoints,sizeof(double));
psShape->padfM = (double *) calloc(nPoints,sizeof(double));
psShape->nParts = nParts;
psShape->panPartStart = (int *) calloc(nParts,sizeof(int));
psShape->panPartType = (int *) calloc(nParts,sizeof(int));
if (psShape->padfX == NULL ||
psShape->padfY == NULL ||
psShape->padfZ == NULL ||
psShape->padfM == NULL ||
psShape->panPartStart == NULL ||
psShape->panPartType == NULL)
{
snprintf(pszErrorMsg, 128,
"Not enough memory to allocate requested memory (nPoints=%d, nParts=%d) for shape %d. "
"Probably broken SHP file", hEntity, nPoints, nParts );
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
for( i = 0; i < nParts; i++ )
psShape->panPartType[i] = SHPP_RING;
/* -------------------------------------------------------------------- */
/* Copy out the part array from the record. */
/* -------------------------------------------------------------------- */
memcpy( psShape->panPartStart, psSHP->pabyRec + 44 + 8, 4 * nParts );
for( i = 0; i < nParts; i++ )
{
if( bBigEndian ) SwapWord( 4, psShape->panPartStart+i );
/* We check that the offset is inside the vertex array */
if (psShape->panPartStart[i] < 0 ||
psShape->panPartStart[i] >= psShape->nVertices)
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d : panPartStart[%d] = %d, nVertices = %d",
hEntity, i, psShape->panPartStart[i], psShape->nVertices);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
if (i > 0 && psShape->panPartStart[i] <= psShape->panPartStart[i-1])
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d : panPartStart[%d] = %d, panPartStart[%d] = %d",
hEntity, i, psShape->panPartStart[i], i - 1, psShape->panPartStart[i - 1]);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
}
nOffset = 44 + 8 + 4*nParts;
/* -------------------------------------------------------------------- */
/* If this is a multipatch, we will also have parts types. */
/* -------------------------------------------------------------------- */
if( psShape->nSHPType == SHPT_MULTIPATCH )
{
memcpy( psShape->panPartType, psSHP->pabyRec + nOffset, 4*nParts );
for( i = 0; i < nParts; i++ )
{
if( bBigEndian ) SwapWord( 4, psShape->panPartType+i );
}
nOffset += 4*nParts;
}
/* -------------------------------------------------------------------- */
/* Copy out the vertices from the record. */
/* -------------------------------------------------------------------- */
for( i = 0; i < nPoints; i++ )
{
memcpy(psShape->padfX + i,
psSHP->pabyRec + nOffset + i * 16,
8 );
memcpy(psShape->padfY + i,
psSHP->pabyRec + nOffset + i * 16 + 8,
8 );
if( bBigEndian ) SwapWord( 8, psShape->padfX + i );
if( bBigEndian ) SwapWord( 8, psShape->padfY + i );
}
nOffset += 16*nPoints;
/* -------------------------------------------------------------------- */
/* If we have a Z coordinate, collect that now. */
/* -------------------------------------------------------------------- */
if( psShape->nSHPType == SHPT_POLYGONZ
|| psShape->nSHPType == SHPT_ARCZ
|| psShape->nSHPType == SHPT_MULTIPATCH )
{
memcpy( &(psShape->dfZMin), psSHP->pabyRec + nOffset, 8 );
memcpy( &(psShape->dfZMax), psSHP->pabyRec + nOffset + 8, 8 );
if( bBigEndian ) SwapWord( 8, &(psShape->dfZMin) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfZMax) );
for( i = 0; i < nPoints; i++ )
{
memcpy( psShape->padfZ + i,
psSHP->pabyRec + nOffset + 16 + i*8, 8 );
if( bBigEndian ) SwapWord( 8, psShape->padfZ + i );
}
nOffset += 16 + 8*nPoints;
}
/* -------------------------------------------------------------------- */
/* If we have a M measure value, then read it now. We assume */
/* that the measure can be present for any shape if the size is */
/* big enough, but really it will only occur for the Z shapes */
/* (options), and the M shapes. */
/* -------------------------------------------------------------------- */
if( nEntitySize >= nOffset + 16 + 8*nPoints )
{
memcpy( &(psShape->dfMMin), psSHP->pabyRec + nOffset, 8 );
memcpy( &(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8 );
if( bBigEndian ) SwapWord( 8, &(psShape->dfMMin) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfMMax) );
for( i = 0; i < nPoints; i++ )
{
memcpy( psShape->padfM + i,
psSHP->pabyRec + nOffset + 16 + i*8, 8 );
if( bBigEndian ) SwapWord( 8, psShape->padfM + i );
}
psShape->bMeasureIsUsed = TRUE;
}
}
/* ==================================================================== */
/* Extract vertices for a MultiPoint. */
/* ==================================================================== */
else if( psShape->nSHPType == SHPT_MULTIPOINT
|| psShape->nSHPType == SHPT_MULTIPOINTM
|| psShape->nSHPType == SHPT_MULTIPOINTZ )
{
int32 nPoints;
int i, nOffset;
if ( 44 + 4 > nEntitySize )
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d : nEntitySize = %d",
hEntity, nEntitySize);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
memcpy( &nPoints, psSHP->pabyRec + 44, 4 );
if( bBigEndian ) SwapWord( 4, &nPoints );
if (nPoints < 0 || nPoints > 50 * 1000 * 1000)
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d : nPoints = %d",
hEntity, nPoints);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
nRequiredSize = 48 + nPoints * 16;
if( psShape->nSHPType == SHPT_MULTIPOINTZ )
{
nRequiredSize += 16 + nPoints * 8;
}
if (nRequiredSize > nEntitySize)
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d : nPoints = %d, nEntitySize = %d",
hEntity, nPoints, nEntitySize);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
psShape->nVertices = nPoints;
psShape->padfX = (double *) calloc(nPoints,sizeof(double));
psShape->padfY = (double *) calloc(nPoints,sizeof(double));
psShape->padfZ = (double *) calloc(nPoints,sizeof(double));
psShape->padfM = (double *) calloc(nPoints,sizeof(double));
if (psShape->padfX == NULL ||
psShape->padfY == NULL ||
psShape->padfZ == NULL ||
psShape->padfM == NULL)
{
snprintf(pszErrorMsg, 128,
"Not enough memory to allocate requested memory (nPoints=%d) for shape %d. "
"Probably broken SHP file", hEntity, nPoints );
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
for( i = 0; i < nPoints; i++ )
{
memcpy(psShape->padfX+i, psSHP->pabyRec + 48 + 16 * i, 8 );
memcpy(psShape->padfY+i, psSHP->pabyRec + 48 + 16 * i + 8, 8 );
if( bBigEndian ) SwapWord( 8, psShape->padfX + i );
if( bBigEndian ) SwapWord( 8, psShape->padfY + i );
}
nOffset = 48 + 16*nPoints;
/* -------------------------------------------------------------------- */
/* Get the X/Y bounds. */
/* -------------------------------------------------------------------- */
memcpy( &(psShape->dfXMin), psSHP->pabyRec + 8 + 4, 8 );
memcpy( &(psShape->dfYMin), psSHP->pabyRec + 8 + 12, 8 );
memcpy( &(psShape->dfXMax), psSHP->pabyRec + 8 + 20, 8 );
memcpy( &(psShape->dfYMax), psSHP->pabyRec + 8 + 28, 8 );
if( bBigEndian ) SwapWord( 8, &(psShape->dfXMin) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfYMin) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfXMax) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfYMax) );
/* -------------------------------------------------------------------- */
/* If we have a Z coordinate, collect that now. */
/* -------------------------------------------------------------------- */
if( psShape->nSHPType == SHPT_MULTIPOINTZ )
{
memcpy( &(psShape->dfZMin), psSHP->pabyRec + nOffset, 8 );
memcpy( &(psShape->dfZMax), psSHP->pabyRec + nOffset + 8, 8 );
if( bBigEndian ) SwapWord( 8, &(psShape->dfZMin) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfZMax) );
for( i = 0; i < nPoints; i++ )
{
memcpy( psShape->padfZ + i,
psSHP->pabyRec + nOffset + 16 + i*8, 8 );
if( bBigEndian ) SwapWord( 8, psShape->padfZ + i );
}
nOffset += 16 + 8*nPoints;
}
/* -------------------------------------------------------------------- */
/* If we have a M measure value, then read it now. We assume */
/* that the measure can be present for any shape if the size is */
/* big enough, but really it will only occur for the Z shapes */
/* (options), and the M shapes. */
/* -------------------------------------------------------------------- */
if( nEntitySize >= nOffset + 16 + 8*nPoints )
{
memcpy( &(psShape->dfMMin), psSHP->pabyRec + nOffset, 8 );
memcpy( &(psShape->dfMMax), psSHP->pabyRec + nOffset + 8, 8 );
if( bBigEndian ) SwapWord( 8, &(psShape->dfMMin) );
if( bBigEndian ) SwapWord( 8, &(psShape->dfMMax) );
for( i = 0; i < nPoints; i++ )
{
memcpy( psShape->padfM + i,
psSHP->pabyRec + nOffset + 16 + i*8, 8 );
if( bBigEndian ) SwapWord( 8, psShape->padfM + i );
}
psShape->bMeasureIsUsed = TRUE;
}
}
/* ==================================================================== */
/* Extract vertices for a point. */
/* ==================================================================== */
else if( psShape->nSHPType == SHPT_POINT
|| psShape->nSHPType == SHPT_POINTM
|| psShape->nSHPType == SHPT_POINTZ )
{
int nOffset;
psShape->nVertices = 1;
psShape->padfX = (double *) calloc(1,sizeof(double));
psShape->padfY = (double *) calloc(1,sizeof(double));
psShape->padfZ = (double *) calloc(1,sizeof(double));
psShape->padfM = (double *) calloc(1,sizeof(double));
if (20 + 8 + (( psShape->nSHPType == SHPT_POINTZ ) ? 8 : 0)> nEntitySize)
{
snprintf(pszErrorMsg, 128, "Corrupted .shp file : shape %d : nEntitySize = %d",
hEntity, nEntitySize);
psSHP->sHooks.Error( pszErrorMsg );
SHPDestroyObject(psShape);
return NULL;
}
memcpy( psShape->padfX, psSHP->pabyRec + 12, 8 );
memcpy( psShape->padfY, psSHP->pabyRec + 20, 8 );
if( bBigEndian ) SwapWord( 8, psShape->padfX );
if( bBigEndian ) SwapWord( 8, psShape->padfY );
nOffset = 20 + 8;
/* -------------------------------------------------------------------- */
/* If we have a Z coordinate, collect that now. */
/* -------------------------------------------------------------------- */
if( psShape->nSHPType == SHPT_POINTZ )
{
memcpy( psShape->padfZ, psSHP->pabyRec + nOffset, 8 );
if( bBigEndian ) SwapWord( 8, psShape->padfZ );
nOffset += 8;
}
/* -------------------------------------------------------------------- */
/* If we have a M measure value, then read it now. We assume */
/* that the measure can be present for any shape if the size is */
/* big enough, but really it will only occur for the Z shapes */
/* (options), and the M shapes. */
/* -------------------------------------------------------------------- */
if( nEntitySize >= nOffset + 8 )
{
memcpy( psShape->padfM, psSHP->pabyRec + nOffset, 8 );
if( bBigEndian ) SwapWord( 8, psShape->padfM );
psShape->bMeasureIsUsed = TRUE;
}
/* -------------------------------------------------------------------- */
/* Since no extents are supplied in the record, we will apply */
/* them from the single vertex. */
/* -------------------------------------------------------------------- */
psShape->dfXMin = psShape->dfXMax = psShape->padfX[0];
psShape->dfYMin = psShape->dfYMax = psShape->padfY[0];
psShape->dfZMin = psShape->dfZMax = psShape->padfZ[0];
psShape->dfMMin = psShape->dfMMax = psShape->padfM[0];
}
return( psShape );
}
/************************************************************************/
/* SHPTypeName() */
/************************************************************************/
const char SHPAPI_CALL1(*)
SHPTypeName( int nSHPType )
{
switch( nSHPType )
{
case SHPT_NULL:
return "NullShape";
case SHPT_POINT:
return "Point";
case SHPT_ARC:
return "Arc";
case SHPT_POLYGON:
return "Polygon";
case SHPT_MULTIPOINT:
return "MultiPoint";
case SHPT_POINTZ:
return "PointZ";
case SHPT_ARCZ:
return "ArcZ";
case SHPT_POLYGONZ:
return "PolygonZ";
case SHPT_MULTIPOINTZ:
return "MultiPointZ";
case SHPT_POINTM:
return "PointM";
case SHPT_ARCM:
return "ArcM";
case SHPT_POLYGONM:
return "PolygonM";
case SHPT_MULTIPOINTM:
return "MultiPointM";
case SHPT_MULTIPATCH:
return "MultiPatch";
default:
return "UnknownShapeType";
}
}
/************************************************************************/
/* SHPPartTypeName() */
/************************************************************************/
const char SHPAPI_CALL1(*)
SHPPartTypeName( int nPartType )
{
switch( nPartType )
{
case SHPP_TRISTRIP:
return "TriangleStrip";
case SHPP_TRIFAN:
return "TriangleFan";
case SHPP_OUTERRING:
return "OuterRing";
case SHPP_INNERRING:
return "InnerRing";
case SHPP_FIRSTRING:
return "FirstRing";
case SHPP_RING:
return "Ring";
default:
return "UnknownPartType";
}
}
/************************************************************************/
/* SHPDestroyObject() */
/************************************************************************/
void SHPAPI_CALL
SHPDestroyObject( SHPObject * psShape )
{
if( psShape == NULL )
return;
if( psShape->padfX != NULL )
free( psShape->padfX );
if( psShape->padfY != NULL )
free( psShape->padfY );
if( psShape->padfZ != NULL )
free( psShape->padfZ );
if( psShape->padfM != NULL )
free( psShape->padfM );
if( psShape->panPartStart != NULL )
free( psShape->panPartStart );
if( psShape->panPartType != NULL )
free( psShape->panPartType );
free( psShape );
}
/************************************************************************/
/* SHPRewindObject() */
/* */
/* Reset the winding of polygon objects to adhere to the */
/* specification. */
/************************************************************************/
int SHPAPI_CALL
SHPRewindObject( SHPHandle hSHP, SHPObject * psObject )
{
int iOpRing, bAltered = 0;
/* -------------------------------------------------------------------- */
/* Do nothing if this is not a polygon object. */
/* -------------------------------------------------------------------- */
if( psObject->nSHPType != SHPT_POLYGON
&& psObject->nSHPType != SHPT_POLYGONZ
&& psObject->nSHPType != SHPT_POLYGONM )
return 0;
if( psObject->nVertices == 0 || psObject->nParts == 0 )
return 0;
/* -------------------------------------------------------------------- */
/* Process each of the rings. */
/* -------------------------------------------------------------------- */
for( iOpRing = 0; iOpRing < psObject->nParts; iOpRing++ )
{
int bInner, iVert, nVertCount, nVertStart, iCheckRing;
double dfSum, dfTestX, dfTestY;
/* -------------------------------------------------------------------- */
/* Determine if this ring is an inner ring or an outer ring */
/* relative to all the other rings. For now we assume the */
/* first ring is outer and all others are inner, but eventually */
/* we need to fix this to handle multiple island polygons and */
/* unordered sets of rings. */
/* */
/* -------------------------------------------------------------------- */
/* Use point in the middle of segment to avoid testing
* common points of rings.
*/
dfTestX = ( psObject->padfX[psObject->panPartStart[iOpRing]]
+ psObject->padfX[psObject->panPartStart[iOpRing] + 1] ) / 2;
dfTestY = ( psObject->padfY[psObject->panPartStart[iOpRing]]
+ psObject->padfY[psObject->panPartStart[iOpRing] + 1] ) / 2;
bInner = FALSE;
for( iCheckRing = 0; iCheckRing < psObject->nParts; iCheckRing++ )
{
int iEdge;
if( iCheckRing == iOpRing )
continue;
nVertStart = psObject->panPartStart[iCheckRing];
if( iCheckRing == psObject->nParts-1 )
nVertCount = psObject->nVertices
- psObject->panPartStart[iCheckRing];
else
nVertCount = psObject->panPartStart[iCheckRing+1]
- psObject->panPartStart[iCheckRing];
for( iEdge = 0; iEdge < nVertCount; iEdge++ )
{
int iNext;
if( iEdge < nVertCount-1 )
iNext = iEdge+1;
else
iNext = 0;
/* Rule #1:
* Test whether the edge 'straddles' the horizontal ray from the test point (dfTestY,dfTestY)
* The rule #1 also excludes edges collinear with the ray.
*/
if ( ( psObject->padfY[iEdge+nVertStart] < dfTestY
&& dfTestY <= psObject->padfY[iNext+nVertStart] )
|| ( psObject->padfY[iNext+nVertStart] < dfTestY
&& dfTestY <= psObject->padfY[iEdge+nVertStart] ) )
{
/* Rule #2:
* Test if edge-ray intersection is on the right from the test point (dfTestY,dfTestY)
*/
double const intersect =
( psObject->padfX[iEdge+nVertStart]
+ ( dfTestY - psObject->padfY[iEdge+nVertStart] )
/ ( psObject->padfY[iNext+nVertStart] - psObject->padfY[iEdge+nVertStart] )
* ( psObject->padfX[iNext+nVertStart] - psObject->padfX[iEdge+nVertStart] ) );
if (intersect < dfTestX)
{
bInner = !bInner;
}
}
}
} /* for iCheckRing */
/* -------------------------------------------------------------------- */
/* Determine the current order of this ring so we will know if */
/* it has to be reversed. */
/* -------------------------------------------------------------------- */
nVertStart = psObject->panPartStart[iOpRing];
if( iOpRing == psObject->nParts-1 )
nVertCount = psObject->nVertices - psObject->panPartStart[iOpRing];
else
nVertCount = psObject->panPartStart[iOpRing+1]
- psObject->panPartStart[iOpRing];
dfSum = 0.0;
for( iVert = nVertStart; iVert < nVertStart+nVertCount-1; iVert++ )
{
dfSum += psObject->padfX[iVert] * psObject->padfY[iVert+1]
- psObject->padfY[iVert] * psObject->padfX[iVert+1];
}
dfSum += psObject->padfX[iVert] * psObject->padfY[nVertStart]
- psObject->padfY[iVert] * psObject->padfX[nVertStart];
/* -------------------------------------------------------------------- */
/* Reverse if necessary. */
/* -------------------------------------------------------------------- */
if( (dfSum < 0.0 && bInner) || (dfSum > 0.0 && !bInner) )
{
int i;
bAltered++;
for( i = 0; i < nVertCount/2; i++ )
{
double dfSaved;
/* Swap X */
dfSaved = psObject->padfX[nVertStart+i];
psObject->padfX[nVertStart+i] =
psObject->padfX[nVertStart+nVertCount-i-1];
psObject->padfX[nVertStart+nVertCount-i-1] = dfSaved;
/* Swap Y */
dfSaved = psObject->padfY[nVertStart+i];
psObject->padfY[nVertStart+i] =
psObject->padfY[nVertStart+nVertCount-i-1];
psObject->padfY[nVertStart+nVertCount-i-1] = dfSaved;
/* Swap Z */
if( psObject->padfZ )
{
dfSaved = psObject->padfZ[nVertStart+i];
psObject->padfZ[nVertStart+i] =
psObject->padfZ[nVertStart+nVertCount-i-1];
psObject->padfZ[nVertStart+nVertCount-i-1] = dfSaved;
}
/* Swap M */
if( psObject->padfM )
{
dfSaved = psObject->padfM[nVertStart+i];
psObject->padfM[nVertStart+i] =
psObject->padfM[nVertStart+nVertCount-i-1];
psObject->padfM[nVertStart+nVertCount-i-1] = dfSaved;
}
}
}
}
return bAltered;
}
| 36.958152 | 123 | 0.451004 | [
"object",
"shape",
"3d"
] |
65b7ff31ef1d0ae22d9c69cf50174b06ed5af1cf | 3,799 | cpp | C++ | Othuum/AhwassaGraphicsLib/Renderer/DiffuseMeshRenderer.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | 5 | 2021-04-20T17:00:41.000Z | 2022-01-18T20:16:03.000Z | Othuum/AhwassaGraphicsLib/Renderer/DiffuseMeshRenderer.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | 7 | 2021-08-22T21:30:50.000Z | 2022-01-14T16:56:34.000Z | Othuum/AhwassaGraphicsLib/Renderer/DiffuseMeshRenderer.cpp | Liech/Yathsou | 95b6dda3c053bc25789cce416088e22f54a743b4 | [
"MIT"
] | null | null | null | #include "DiffuseMeshRenderer.h"
#include "Core/Window.h"
#include "Core/ShaderProgram.h"
#include "Core/Camera.h"
#include "BufferObjects/Mesh.h"
#include "Vertex/PositionNormalVertex.h"
#include "Util.h"
#include "Uniforms/UniformVec3.h"
#include "Uniforms/UniformVecMat4.h"
#include "Uniforms/UniformVecVec3.h"
namespace Ahwassa {
DiffuseMeshRenderer::DiffuseMeshRenderer(std::shared_ptr<Camera> camera) {
_camera = camera;
_bufferSize = (Util::maxUniformAmount() - 10) / 2;
_lightDirection = glm::normalize(glm::vec3(25, 31, -21));
makeShader();
}
DiffuseMeshRenderer::~DiffuseMeshRenderer() {
}
void DiffuseMeshRenderer::setLightDirection(glm::vec3 dir) {
_lightDirection = dir;
}
glm::vec3 DiffuseMeshRenderer::getLightDirection() {
return _lightDirection;
}
void DiffuseMeshRenderer::addMesh(std::shared_ptr<DiffuseMeshRendererMesh> mesh) {
_meshes[mesh->mesh].push_back(mesh);
}
void DiffuseMeshRenderer::makeShader() {
std::string vertex_shader_source = R"(
out vec3 clr;
out vec3 nrm;
void main() {
mat4 view = )" + _camera->getName() + R"(Projection * )" + _camera->getName() + R"(View;
gl_Position = view * models[gl_InstanceID] *vec4(position , 1.0);
clr = colors[gl_InstanceID];
nrm = normal;
}
)";
std::string fragment_shader_source = R"(
in vec3 clr;
in vec3 nrm;
out vec4 frag_color;
void main() {
float ambientStrength = 0.5;
float diffuseStrength = 0.5;
float diff = max(dot(nrm, Light), 0.0) * diffuseStrength;
vec4 result = vec4(clr,1) * diff + vec4(clr,1) * ambientStrength;
result[3] = 1;
frag_color = result;
}
)";
std::vector<Uniform*> uniforms;
std::vector<Uniform*> cameraUniforms = _camera->getUniforms();
uniforms.insert(uniforms.end(), cameraUniforms.begin(), cameraUniforms.end());
_light = std::make_unique<UniformVec3>("Light");
_models = std::make_unique<UniformVecMat4>("models", _bufferSize);
_colors = std::make_unique<UniformVecVec3>("colors", _bufferSize);
_light->setValue(glm::normalize(glm::vec3(0)));
uniforms.push_back(_light .get());
uniforms.push_back(_models.get());
uniforms.push_back(_colors.get());
_shader = std::make_unique<ShaderProgram>(PositionNormalVertex::getBinding(), uniforms, vertex_shader_source, fragment_shader_source);
}
void DiffuseMeshRenderer::draw() {
std::vector< std::shared_ptr<Mesh<PositionNormalVertex>>> toDeleteMeshes;
Util::setDepthTest(true);
Util::setDepthFuncLess();
_shader->bind();
_camera->bind();
for (auto& meshVector : _meshes) {
std::vector<glm::mat4> models;
std::vector<glm::vec3> colors;
models.resize(_bufferSize);
colors.resize(_bufferSize);
std::vector<size_t> toDelete;
size_t currentPosition = 0;
for (size_t i = 0; i < meshVector.second.size(); i++) {
auto m = meshVector.second[i].lock();
if (!m)
{
toDelete.push_back(i);
continue;
}
models[currentPosition] = m->transformation;
colors[currentPosition] = m->color.to3();
currentPosition++;
}
_light ->setValue(getLightDirection());
_models->setValue(models);
_colors->setValue(colors);
_models->bind();
_colors->bind();
meshVector.first->drawInstanced(currentPosition);
for (int i = toDelete.size()-1; i >= 0; i--)
meshVector.second.erase(meshVector.second.begin() + i);
if (meshVector.second.size() == 0)
toDeleteMeshes.push_back(meshVector.first);
Util::setDepthTest(false);
}
for (auto x : toDeleteMeshes) {
_meshes.erase(x);
}
}
} | 29.449612 | 138 | 0.642011 | [
"mesh",
"vector"
] |
65bb75296b2b076da76db2e52b88ab9072bbc410 | 535 | cpp | C++ | LeetCode/Problems/Algorithms/#977_SquaresOfASortedArray_sol5_two_pointers_approach_O(N)_time_O(1)_extra_space_68ms_26.2MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#977_SquaresOfASortedArray_sol5_two_pointers_approach_O(N)_time_O(1)_extra_space_68ms_26.2MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#977_SquaresOfASortedArray_sol5_two_pointers_approach_O(N)_time_O(1)_extra_space_68ms_26.2MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
const int N = nums.size();
vector<int> answer(N);
int l = 0;
int r = N - 1;
for(int i = N - 1; i >= 0; --i){
if(nums[l] * nums[l] >= nums[r] * nums[r]){
answer[i] = nums[l] * nums[l];
l += 1;
}else{
answer[i] = nums[r] * nums[r];
r -= 1;
}
}
return answer;
}
}; | 25.47619 | 56 | 0.347664 | [
"vector"
] |
65be55debe0c91cf2376e56f9b94ced271ebf224 | 3,555 | cpp | C++ | 5227 Tom and game/main.cpp | sqc1999-oi/HDU | 5583755c5b7055e4a7254b2124f67982cc49b72d | [
"MIT"
] | 1 | 2016-07-18T12:05:44.000Z | 2016-07-18T12:05:44.000Z | 5227 Tom and game/main.cpp | sqc1999-oi/HDU | 5583755c5b7055e4a7254b2124f67982cc49b72d | [
"MIT"
] | null | null | null | 5227 Tom and game/main.cpp | sqc1999-oi/HDU | 5583755c5b7055e4a7254b2124f67982cc49b72d | [
"MIT"
] | null | null | null | #include <cstdio>
#include <algorithm>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdarg>
#include <cctype>
#include <cstring>
#include <map>
using namespace std;
const int N = 10000;
vector<int> g[N];
bool flag[N];
int sz[N], phi[N + 1];
long long ct[N + 1], sg[N], depw[N];
void get_nodes(int u, int fa, vector<int> &vi)
{
vi.push_back(u);
for (int i = 0; i < g[u].size(); i++)
{
int v = g[u][i];
if (v != fa && !flag[v])
get_nodes(v, u, vi);
}
}
void calc_size(int u, int fa)
{
sz[u] = 1;
for (int i = 0; i < g[u].size(); i++)
{
int v = g[u][i];
if (v != fa && !flag[v])
{
calc_size(v, u);
sz[u] += sz[v];
}
}
}
void calc_depw(int u, int fa)
{
for (int i = 0; i < g[u].size(); i++)
{
int v = g[u][i];
if (v != fa && !flag[v])
{
depw[v] = depw[u] ^ sg[v];
calc_depw(v, u);
}
}
}
void get_focus(int u, int fa, int n, int &ans, int &min)
{
int max = n - sz[u];
for (int i = 0; i < g[u].size(); i++)
{
int v = g[u][i];
if (v != fa && !flag[v])
{
max = ::max(max, sz[v]);
get_focus(v, u, n, ans, min);
}
}
if (max < min)
{
min = max;
ans = u;
}
}
int calc_ans(int u)
{
map<long long, int> m;
int ans = 0;
if (sg[u] == 0) ans++;
for (int i = 0; i < g[u].size(); i++)
{
int v = g[u][i];
if (flag[g[u][i]]) continue;
vector<int> vi;
get_nodes(v, -1, vi);
depw[v] = sg[v];
calc_depw(v, -1);
for (int j = 0; j < vi.size(); j++)
{
ans += (m[sg[u] ^ depw[vi[j]]]) * 2;
if ((sg[u] ^ depw[vi[j]]) == 0) ans += 2;
}
for (int j = 0; j < vi.size(); j++) m[depw[vi[j]]]++;
}
return ans;
}
int solve(int u)
{
calc_size(u, -1);
int x = INT_MAX;
get_focus(u, -1, sz[u], u, x);
flag[u] = true;
calc_size(u, -1);
depw[u] = 0;
calc_depw(u, -1);
int ans = calc_ans(u);
for (int i = 0; i < g[u].size(); i++)
if (!flag[g[u][i]]) ans += solve(g[u][i]);
return ans;
}
long long get(int n, int m)
{
long long res = 0;
if (n > m) swap(n, m);
for (int i = 1, j; i <= n; i = j + 1)
{
j = min(n / (n / i), m / (m / i));
res += (long long)(phi[j] - phi[i - 1]) * (n / i) * (m / i);
}
return res;
}
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a%b);
}
bool read(int n, ...)
{
va_list li;
va_start(li, n);
for (int i = 0; i < n; i++)
{
int &x = *va_arg(li, int *);
x = 0;
int ch;
do ch = getchar();
while (ch != EOF && !isdigit(ch));
if (ch == EOF) return false;
do
{
(x *= 10) += ch - '0';
ch = getchar();
} while (ch != EOF && isdigit(ch));
if (ch == EOF) return false;
}
va_end(li);
return true;
}
int main()
{
for (int i = 0; i <= N; i++) phi[i] = i;
for (int i = 2; i <= N; i++)
if (phi[i] == i)
for (int j = i; j <= N; j += i)
phi[j] = phi[j] / i * (i - 1);
for (int i = 2; i <= N; i++) phi[i] += phi[i - 1];
for (int i = 1; i <= N; i++)
ct[i] = get(i, i) + ct[i - 1];
int n;
while (read(1, &n))
{
memset(flag, 0x00, sizeof flag);
for (int i = 0; i < n; i++) g[i].clear();
for (int i = 0; i < n - 1; i++)
{
int a, b;
read(2, &a, &b);
g[a - 1].push_back(b - 1);
g[b - 1].push_back(a - 1);
}
for (int i = 0; i < n; i++)
{
int t, a, b, c;
read(4, &t, &a, &b, &c);
sg[i] = ct[t - 1] + c - 1;
sg[i] += get(a - 1, t);
sg[i] += get(a, b - 1) - get(a - 1, b - 1);
}
int ans = n*n - solve(0);
int x = gcd(ans, n*n);
printf("%d/%d\n", ans / x, n*n / x);
}
}
| 20.084746 | 63 | 0.440506 | [
"vector"
] |
65c97218347275896dad7c0dc8ceca0cb7a478ae | 3,366 | cpp | C++ | Alpha9/platform/windows/windows_input.cpp | Mind-Blown012/Alpha-9 | 02f44f56bd8811b6df467eb65a243d751b0023b7 | [
"MIT"
] | null | null | null | Alpha9/platform/windows/windows_input.cpp | Mind-Blown012/Alpha-9 | 02f44f56bd8811b6df467eb65a243d751b0023b7 | [
"MIT"
] | null | null | null | Alpha9/platform/windows/windows_input.cpp | Mind-Blown012/Alpha-9 | 02f44f56bd8811b6df467eb65a243d751b0023b7 | [
"MIT"
] | null | null | null | #include "a9pch.hpp"
#include "windows_input.hpp"
#ifdef A9_PLATFORM_WINDOWS
namespace Alpha9
{
const int Input::NumKeys = 119;
const int Input::NumMouseButtons = 8;
bool Input::s_isInitalized = false;
std::vector<int> Input::s_keys;
std::vector<int> Input::s_lastKeys;
std::vector<int> Input::s_mouseButtons;
std::vector<int> Input::s_lastMouseButtons;
void Input::Init()
{
if (!s_isInitalized)
{
// Binding key and mouse events
BIND_EVENT(KeyDownEvent, Input::onKeyDown);
BIND_EVENT(KeyUpEvent, Input::onKeyUp);
BIND_EVENT(MouseButtonDownEvent, Input::onMouseButtonDown);
BIND_EVENT(MouseButtonUpEvent, Input::onMouseButtonUp);
s_isInitalized = true;
}
}
void Input::Update()
{
s_lastKeys = s_keys;
s_lastMouseButtons = s_mouseButtons;
}
// Used by client
bool Input::GetKey(KeyCode code)
{
bool inKeys = std::find(s_keys.begin(), s_keys.end(), (int)code) != s_keys.end();
return inKeys;
}
bool Input::GetKeyDown(KeyCode code)
{
bool inKeys = std::find(s_keys.begin(), s_keys.end(), (int)code) != s_keys.end();
bool inLastKeys = std::find(s_lastKeys.begin(), s_lastKeys.end(), (int)code) != s_lastKeys.end();
return (inKeys && !inLastKeys);
}
bool Input::GetKeyUp(KeyCode code)
{
bool inKeys = std::find(s_keys.begin(), s_keys.end(), (int)code) != s_keys.end();
bool inLastKeys = std::find(s_lastKeys.begin(), s_lastKeys.end(), (int)code) != s_lastKeys.end();
return (!inKeys && inLastKeys);
}
bool Input::GetMouseButton(MouseButton button)
{
bool inMouseButtons = std::find(s_mouseButtons.begin(), s_mouseButtons.end(), (int)button) != s_mouseButtons.end();
return inMouseButtons;
}
bool Input::GetMouseButtonDown(MouseButton button)
{
bool inMouseButtons = std::find(s_mouseButtons.begin(), s_mouseButtons.end(), (int)button) != s_mouseButtons.end();
bool inLastMouseButtons = std::find(s_lastMouseButtons.begin(), s_lastMouseButtons.end(), (int)button) != s_lastMouseButtons.end();
return (inMouseButtons && !inLastMouseButtons);
}
bool Input::GetMouseButtonUp(MouseButton button)
{
bool inMouseButtons = std::find(s_mouseButtons.begin(), s_mouseButtons.end(), (int)button) != s_mouseButtons.end();
bool inLastMouseButtons = std::find(s_lastMouseButtons.begin(), s_lastMouseButtons.end(), (int)button) != s_lastMouseButtons.end();
return (!inMouseButtons && inLastMouseButtons);
}
void Input::onKeyDown(Event& e)
{
KeyDownEvent& en = static_cast<KeyDownEvent&>(e);
if(std::find(s_keys.begin(), s_keys.end(), en.GetKeyCode()) == s_keys.end())
s_keys.push_back(en.GetKeyCode());
}
void Input::onKeyUp(Event& e)
{
KeyUpEvent& en = static_cast<KeyUpEvent&>(e);
auto codePos = std::find(s_keys.begin(), s_keys.end(), en.GetKeyCode());
if (codePos != s_keys.end())
s_keys.erase(codePos);
}
void Input::onMouseButtonDown(Event& e)
{
MouseButtonDownEvent& en = static_cast<MouseButtonDownEvent&>(e);
if (std::find(s_mouseButtons.begin(), s_mouseButtons.end(), en.GetButton()) == s_mouseButtons.end())
s_mouseButtons.push_back(en.GetButton());
}
void Input::onMouseButtonUp(Event& e)
{
MouseButtonUpEvent& en = static_cast<MouseButtonUpEvent&>(e);
auto codePos = std::find(s_mouseButtons.begin(), s_mouseButtons.end(), en.GetButton());
if (codePos != s_mouseButtons.end())
s_mouseButtons.erase(codePos);
}
}
#endif | 31.166667 | 133 | 0.709745 | [
"vector"
] |
65daf8c56a5ea754995e1a25d00aba2763d8f3ab | 716 | cpp | C++ | binarysearch.io/medium/Zero-Matrix.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | binarysearch.io/medium/Zero-Matrix.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | binarysearch.io/medium/Zero-Matrix.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | #include "solution.hpp"
using namespace std;
class Solution {
public:
vector<vector<int>> solve(vector<vector<int>>& matrix) {
vector<vector<int>> ans;
unordered_map<int,int> r,c;
int m=matrix.size();
if(m==0) return matrix;
int n=matrix[0].size();
if(n==0) return matrix;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(matrix[i][j]==0){
r[i]=1, c[j]=1;
}
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(r[i]||c[j]){
matrix[i][j]=0;
}
}
}
return matrix;
}
};
| 23.096774 | 60 | 0.395251 | [
"vector"
] |
65e3c5ac09b9226c05ed2ec7048795458fc5c1d2 | 3,263 | cpp | C++ | src/caffe/layers/euclidean_loss_layer.cpp | Andeling/caffe_unet | f713104e5c76eea1b618b21b3a3f303dd673081c | [
"Intel",
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/euclidean_loss_layer.cpp | Andeling/caffe_unet | f713104e5c76eea1b618b21b3a3f303dd673081c | [
"Intel",
"BSD-2-Clause"
] | null | null | null | src/caffe/layers/euclidean_loss_layer.cpp | Andeling/caffe_unet | f713104e5c76eea1b618b21b3a3f303dd673081c | [
"Intel",
"BSD-2-Clause"
] | null | null | null | #include <vector>
#include "caffe/layers/euclidean_loss_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void EuclideanLossLayer<Dtype>::Reshape(
const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::Reshape(bottom, top);
CHECK_EQ(bottom[0]->count(1), bottom[1]->count(1))
<< "Inputs must have the same dimension.";
if (bottom.size() > 2) {
CHECK_EQ(bottom[2]->shape(1), 1) << "Weights may only contain one channel.";
CHECK_EQ(bottom[0]->count(2), bottom[2]->count(2))
<< "Weights must have the same spatial shape as the input blobs.";
}
diff_.ReshapeLike(*bottom[0]);
if (bottom.size() > 2) weightedDiff_.ReshapeLike(*bottom[0]);
}
template <typename Dtype>
void EuclideanLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
int count = bottom[0]->count();
caffe_sub(
count,
bottom[0]->cpu_data(),
bottom[1]->cpu_data(),
diff_.mutable_cpu_data());
Dtype normalizer, dot;
if (bottom.size() == 2) {
dot = caffe_cpu_dot(count, diff_.cpu_data(), diff_.cpu_data());
normalizer = bottom[0]->num();
}
else {
for (int n = 0; n < bottom[0]->shape(0); ++n) {
for (int c = 0; c < bottom[0]->shape(1); ++c) {
caffe_mul(
bottom[0]->count(2),
diff_.cpu_data() + n * diff_.count(1) + c * diff_.count(2),
bottom[2]->cpu_data() + n * bottom[2]->count(2),
weightedDiff_.mutable_cpu_data() + n * diff_.count(1) +
c * diff_.count(2));
}
}
weightSum_ = caffe_cpu_asum(bottom[2]->count(), bottom[2]->cpu_data());
dot = caffe_cpu_dot(count, diff_.cpu_data(), weightedDiff_.cpu_data());
normalizer = bottom[0]->shape(1) * std::max(Dtype(1), weightSum_);
}
top[0]->mutable_cpu_data()[0] = dot / Dtype(2) / normalizer;
}
template <typename Dtype>
void EuclideanLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
if (bottom.size() > 2 && propagate_down[2]) {
LOG(FATAL) << this->type()
<< " Layer cannot backpropagate to weight inputs.";
}
for (int i = 0; i < 2; ++i) {
if (propagate_down[i]) {
const Dtype sign = (i == 0) ? 1 : -1;
if (bottom.size() == 2) {
const Dtype alpha = sign * top[0]->cpu_diff()[0] / bottom[i]->num();
caffe_cpu_axpby(
bottom[i]->count(), // count
alpha, // alpha
diff_.cpu_data(), // a
Dtype(0), // beta
bottom[i]->mutable_cpu_diff()); // b
}
else {
const Dtype alpha =
sign * top[0]->cpu_diff()[0] / bottom[i]->shape(1) /
std::max(Dtype(1), weightSum_);
caffe_cpu_axpby(
bottom[i]->count(),
alpha,
weightedDiff_.cpu_data(),
Dtype(0),
bottom[i]->mutable_cpu_diff());
}
}
}
}
#ifdef CPU_ONLY
STUB_GPU(EuclideanLossLayer);
#endif
INSTANTIATE_CLASS(EuclideanLossLayer);
REGISTER_LAYER_CLASS(EuclideanLoss);
} // namespace caffe
| 33.639175 | 80 | 0.575544 | [
"shape",
"vector"
] |
65eec637a02091c76624e11c95ad6b55da273abf | 737 | cpp | C++ | Game/Scripts/ObjectPlacer.cpp | JohnHonkanen/ProjectM | 881171ad749e8fe7db6188ee9486239a37256569 | [
"Unlicense"
] | null | null | null | Game/Scripts/ObjectPlacer.cpp | JohnHonkanen/ProjectM | 881171ad749e8fe7db6188ee9486239a37256569 | [
"Unlicense"
] | null | null | null | Game/Scripts/ObjectPlacer.cpp | JohnHonkanen/ProjectM | 881171ad749e8fe7db6188ee9486239a37256569 | [
"Unlicense"
] | null | null | null |
#include "ObjectPlacer.h"
#include "core\GameEngine.h"
ObjectPlacer * ObjectPlacer::Create(GameObject * gameObject, GameObject * itemToBuild, TerrainSnapper * snapper)
{
ObjectPlacer *p = new ObjectPlacer();
p->itemToBuild = itemToBuild;
p->snapper = snapper;
gameObject->AddComponent(p);
return p;
}
void ObjectPlacer::Update()
{
if (!buildOnce) {
if (GameEngine::manager.inputManager.GetKey("build") == 1) {
buildOnce = true;
GameObject * go = itemToBuild->Instantiate();
vec3 pos = go->transform->GetPosition();
std::cout << "Creating "<< go->name << " at " << pos.x << "||" << pos.y << "||" << pos.z << std::endl;
}
}
if (GameEngine::manager.inputManager.GetKey("build") == 0)
buildOnce = false;
}
| 23.03125 | 112 | 0.652646 | [
"transform"
] |
5a0a21228b07e204f509007443fc0b55ff59a193 | 4,151 | cpp | C++ | src/regalloc/regalloc.cpp | martinogden/mer | 33b4b39b1604ce0708b0d3d1c809b95683a2f4cb | [
"Unlicense"
] | 2 | 2019-11-17T22:54:16.000Z | 2020-08-07T20:53:25.000Z | src/regalloc/regalloc.cpp | martinogden/mer | 33b4b39b1604ce0708b0d3d1c809b95683a2f4cb | [
"Unlicense"
] | null | null | null | src/regalloc/regalloc.cpp | martinogden/mer | 33b4b39b1604ce0708b0d3d1c809b95683a2f4cb | [
"Unlicense"
] | null | null | null | #include <set>
#include <unordered_map>
#include "counter.hpp"
#include "inst/operand.hpp"
#include "regalloc/regalloc.hpp"
#include "regalloc/ig-builder.hpp"
typedef std::unordered_map<Operand, uint> Colors;
Alloc::Alloc() :
num_spilled(0)
{}
Operand Alloc::lookup(const Operand& operand) const {
switch (operand.getType()) {
case Operand::REG:
case Operand::TMP: {
assert(map.find(operand) != map.end());
return map.at(operand);
}
case Operand::MEM: {
Operand mem = operand.getMemOperand();
assert(map.find(mem) != map.end());
return { map.at(mem).getReg(), operand.getMemOffset() };
}
case Operand::IMM:
case Operand::LBL:
return operand;
}
}
void Alloc::assign(const Operand& src, const Operand& dst) {
assert(map.find(src) == map.end());
map[src] = dst;
}
// ir operands already assigned a register are precolored
Colors getPrecoloring(const InstFun& fun) {
Colors colors;
for (uint i=0; i<=MAX_REG; ++i)
colors[static_cast<Reg>(i)] = i;
return colors;
}
std::vector<Operand> mcs(IGPtr& G, Colors& precoloring) {
uint n = G->numVertices();
assert(n > 0);
std::unordered_set<Operand> V = G->getVertices();
std::vector<Operand> order(n);
Counter<Operand> weights(V);
for (auto& c : precoloring) {
Operand u = c.first;
for (auto const& v : G->getAdj(u))
weights.incr(v);
}
for (uint i=0; i<n; ++i) {
Operand u = weights.getMostCommon();
for (auto const& v : G->getAdj(u)) {
if (V.find(v) != V.end())
weights.incr(v);
}
V.erase(u);
weights.erase(u);
order[i] = u;
}
return order;
}
// find minimum excluded elmt
inline uint mex(std::unordered_set<uint>& set) {
uint m = 0;
while (set.find(m) != set.end())
m++;
return m;
}
inline uint leastUnusedColor(std::unordered_set<Operand>& vertices, Colors& colors) {
std::unordered_set<uint> usedColors;
for (auto const& v : vertices) {
if (colors.find(v) != colors.end())
usedColors.insert(colors[v]);
}
return mex(usedColors);
}
Colors greedyColor(IGPtr& G, std::vector<Operand>& order, Colors& precoloring) {
Colors colors;
// precolor vertices
for (auto& item : precoloring)
colors[item.first] = item.second;
for (auto const& u : order) {
// ignore precolored vertices
if (colors.find(u) != colors.end())
continue;
// color vertex using least unused color among neighbors
std::unordered_set<Operand> adj = G->getAdj(u);
colors[u] = leastUnusedColor(adj, colors);
}
return colors;
}
Alloc toColoring(const Colors& colors) {
Alloc alloc;
uint offset = callerSaved.size() + 1;
std::set<Reg> used_regs; // keeps regs in order
for (auto const& pair : colors) {
if (pair.second <= MAX_REG) {
Reg reg = static_cast<Reg>(pair.second);
alloc.assign(pair.first, reg);
if (!pair.first.is(Operand::REG))
used_regs.insert(reg);
}
else {
alloc.assign(pair.first, Operand(Reg::RBP, -8 * (pair.second - offset)));
alloc.num_spilled++;
}
}
std::vector<Reg> used(used_regs.begin(), used_regs.end());
alloc.used_regs = used;
return alloc;
}
Alloc regAlloc(const InstFun& fun) {
IGBuilder builder(fun);
IGPtr IG = builder.run();
Colors precoloring = getPrecoloring(fun);
std::vector<Operand> order = mcs(IG, precoloring);
Colors colors = greedyColor(IG, order, precoloring);
return toColoring(colors);
}
InstFun regAssign(const InstFun& fun, const Alloc& alloc) {
std::vector<Inst> insts;
for (auto &inst : fun.insts) {
Inst::OpCode opcode = inst.getOpcode();
if (opcode == Inst::LBL) {
insts.push_back(inst);
continue;
}
switch (inst.getParity()) {
case 0:
insts.push_back(inst);
break;
case 1:
insts.emplace_back(
opcode,
alloc.lookup(inst.getDst())
);
break;
case 2:
insts.emplace_back(
opcode,
alloc.lookup(inst.getDst()),
alloc.lookup(inst.getSrc1())
);
break;
case 3:
insts.emplace_back(
opcode,
alloc.lookup(inst.getDst()),
alloc.lookup(inst.getSrc1()),
alloc.lookup(inst.getSrc2())
);
break;
default:
throw 1; // TODO: we should never get here
}
}
return {fun.id, fun.params, insts};
}
| 20.24878 | 85 | 0.649241 | [
"vector"
] |
5a147e1d29f8378cae8f969c0406d7723f8cc77e | 3,192 | hh | C++ | TEvtGen/EvtGen/EvtGenModels/EvtLambdaP_BarGamma.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TEvtGen/EvtGen/EvtGenModels/EvtLambdaP_BarGamma.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TEvtGen/EvtGen/EvtGenModels/EvtLambdaP_BarGamma.hh | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | //--------------------------------------------------------------------------
//
// Environment:
// This software is part of the EvtGen package developed jointly
// for the BaBar and CLEO collaborations. If you use all or part
// of it, please give an appropriate acknowledgement.
//
// Copyright Information: See EvtGen/COPYRIGHT
// Copyright (C) 2003 Caltech
//
// Module: EvtGen/EvtRadiativeBaryonicPenguins.hh
//
// Description:Implementation of the decay B- -> lambda p_bar gamma according to
// Cheng, Yang; hep-ph/0201015
//
// Modification history:
//
// JFS December 16th, 2003 Module created
//
//------------------------------------------------------------------------
#ifndef EVTLAMBDAPBARGAMMA_HH
#define EVTLAMBDAPBARGAMMA_HH
#include "EvtGenBase/EvtDecayAmp.hh"
#include "EvtGenBase/EvtPDL.hh"
#include "EvtGenBase/EvtComplex.hh"
#include "EvtGenBase/EvtParticle.hh"
#include "EvtGenBase/EvtConst.hh"
class EvtLambdaP_BarGamma : public EvtDecayAmp {
public:
EvtLambdaP_BarGamma();
~EvtLambdaP_BarGamma() {;}
std::string getName();
EvtDecayBase* clone();
void decay(EvtParticle* p);
void init();
void initProbMax();
private:
// some constants to make the code easier to read and maintain
// these three should be constants... (implementation of getMass() prohibits this)
double _mLambdab; // = 5.624; // Lambda_b mass
double _mLambda0; // = 1.115684; // Lambda0 mass
double _c7Eff; // = -0.31; // Wilson coefficient
double _mb; // = 4.4; // running b mass
double _mV; // = 5.42; // pole mass vector current
double _mA; // = 5.86; // pole mass axial current
double _GF; // = 1.166E-5; // Fermi constant
double _gLambdab; // = 16; // coupling constant Lambda_b -> B- p
double _e0; // = 1; // electromagnetic coupling (+1)
double _g1; // = 0.64; // heavy-light form factors at q_mSqare
double _g2; // = -0.10;
double _f1; // = 0.64;
double _f2; // = -0.31;
double _VtbVtsStar;// = 0.038; // |V_tb V_ts^*|
// user never needs to call this -> private
// baryonic form factors f(p), g(p), at p=0
double f0(const double f_qm, int n=1) const ; // calculate f(0) with f(q_max)
double g0(const double f_qm, int n=1) const ; // calculate g(0) with g(q_max)
// shorthand for constants a and b in the formula
double constA() const;
double constB() const;
// initialize phasespace and calculate the amplitude for one (i=0,1) state of the photon
EvtComplex calcAmpliude(const EvtParticle* p, const unsigned int polState);
};
#endif
| 40.923077 | 120 | 0.513158 | [
"vector"
] |
5a168d66a0c88609801c063ec4d68d0495a38043 | 1,735 | cpp | C++ | src/ui/ofxImGuiPatchParamsUI.cpp | MacFurax/ofxPDSPTools | a2c7af9035d771287abc9414cfadd299e9a8dd41 | [
"MIT"
] | 12 | 2019-09-17T15:43:50.000Z | 2021-07-20T09:46:44.000Z | src/ui/ofxImGuiPatchParamsUI.cpp | MacFurax/ofxPDSPTools | a2c7af9035d771287abc9414cfadd299e9a8dd41 | [
"MIT"
] | null | null | null | src/ui/ofxImGuiPatchParamsUI.cpp | MacFurax/ofxPDSPTools | a2c7af9035d771287abc9414cfadd299e9a8dd41 | [
"MIT"
] | null | null | null | #include "ofxImGuiPatchParamsUI.h"
ofxImGuiPatchParamsUI::ofxImGuiPatchParamsUI()
{
}
ofxImGuiPatchParamsUI::ofxImGuiPatchParamsUI(PatchParams& patchParam)
{
_patchParams = patchParam;
}
ofxImGuiPatchParamsUI::~ofxImGuiPatchParamsUI()
{
}
void ofxImGuiPatchParamsUI::setPatchParams( PatchParams& patchParam)
{
_patchParams = patchParam;
}
void ofxImGuiPatchParamsUI::draw()
{
auto mainSettings = ofxImGui::Settings();
for (auto subGroup : _patchParams.getRootParamGroup()->getSubGroups())
{
ofxImGui::BeginWindow(subGroup->getName(), mainSettings, false);
drawParams(subGroup->getParams());
drawGroups(subGroup);
ofxImGui::EndWindow(mainSettings);
}
}
void ofxImGuiPatchParamsUI::drawParams(vector<shared_ptr<ParamDesc>> & params)
{
for (auto param : params)
{
if (param->layout == ParamLayouts::SameLine)
{
ImGui::SameLine();
}
switch (param->widget)
{
case ParamWidgets::Combo:
ofxImGui::AddCombo(
param->pdspParameter->getOFParameterInt(),
param->comboOptions
);
break;
case ParamWidgets::Knob:
ofxImGui::AddKnob(
param->pdspParameter->getOFParameterFloat()
);
break;
case ParamWidgets::HSlider:
ofLogError() << "Drawing HSlider not yet implemented";
break;
case ParamWidgets::VSlider:
ofLogError() << "Drawing VSlider not yet implemented";
break;
default:
ofLogError() << "Unknown widget type " << static_cast<int>(param->widget);
}
}
}
void ofxImGuiPatchParamsUI::drawGroups(shared_ptr<ParamGroup>& groups)
{
for (auto subGroup : groups->getSubGroups())
{
if (ImGui::CollapsingHeader(subGroup->getName().c_str(), ImGuiTreeNodeFlags_DefaultOpen))
{
drawParams(subGroup->getParams());
drawGroups(subGroup);
}
}
}
| 20.174419 | 91 | 0.719885 | [
"vector"
] |
5a18ef7bdbe1091283b5e5704cd658858550e5e6 | 920 | cpp | C++ | Headers/OGL/QuadVao.cpp | baku89/RichterStrip | 223c40c54cda0a028f20167a78ea61710e06f480 | [
"MIT",
"Unlicense"
] | 6 | 2020-11-30T05:31:17.000Z | 2020-12-01T12:40:20.000Z | Headers/OGL/QuadVao.cpp | baku89/RichterStrip | 223c40c54cda0a028f20167a78ea61710e06f480 | [
"MIT",
"Unlicense"
] | null | null | null | Headers/OGL/QuadVao.cpp | baku89/RichterStrip | 223c40c54cda0a028f20167a78ea61710e06f480 | [
"MIT",
"Unlicense"
] | 1 | 2020-12-02T03:04:52.000Z | 2020-12-02T03:04:52.000Z | #include "QuadVao.h"
namespace {
static const struct {
float x, y;
} quadVertices[4] = {{0, 0}, {1, 0}, {0, 1}, {1, 1}};
} // namespace
namespace OGL {
QuadVao::QuadVao() {
glGenBuffers(1, &this->quad);
glBindBuffer(GL_ARRAY_BUFFER, this->quad);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices,
GL_STATIC_DRAW);
glGenVertexArrays(1, &this->ID);
glBindVertexArray(this->ID);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, this->quad);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(quadVertices[0]),
nullptr);
}
void QuadVao::render() {
glBindVertexArray(this->ID);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindVertexArray(0);
}
QuadVao::~QuadVao() {
if (this->ID) {
glDeleteBuffers(1, &this->quad);
glDeleteVertexArrays(1, &this->ID);
}
}
} // namespace OGL
| 23.589744 | 76 | 0.628261 | [
"render"
] |
5a1b84a44bd503f7bd0c39aa8610b1b6ab42c476 | 11,119 | cpp | C++ | src/unittest/CSVReader.cpp | lssjByron/teamsirus | 21f5f26f410eb0262754006d7c4a024c160e6401 | [
"MIT"
] | null | null | null | src/unittest/CSVReader.cpp | lssjByron/teamsirus | 21f5f26f410eb0262754006d7c4a024c160e6401 | [
"MIT"
] | null | null | null | src/unittest/CSVReader.cpp | lssjByron/teamsirus | 21f5f26f410eb0262754006d7c4a024c160e6401 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <sstream>
#include "../database/CSVReader.h"
int CSVReader::validHeaders(){
//vectors that store the headers of each file type
std::vector<std::string> teachHeaderCheck = {"Record Info", "Last Modified User", "Last Modified Date", "ID", "Member Name", "Primary Domain", "Start Date", "End Date", "Program", "Type of Course / Activity", "Course / Activity", "Geographical Scope", "Institution / Organization", "Faculty", "Department", "Division", "Location", "Hours per Teaching Session or Week", "Number of Teaching Sessions or Weeks", "Faculty Member Additional Comments", "Number Of Trainees", "Student Name(s)", "Initial Lecture", "Faculty Development", "Stipend Received", "Comment", "Other Details (doesn't print)", "Total Hours"};
std::vector<std::string> publicationsHeaderCheck = {"Record Info", "Last Modified User", "Last Modified Date", "ID", "Member Name", "Primary Domain", "Publication Status", "Pubmed Article ID", "Type", "Area", "Status Date", "Role", "Peer Reviewed?", "Number Of Contributors", "Author #", "Journal Name | Published In | Book Title | etc.", "Volume", "Issue", "Page Range", "DOI", "Website", "Number of Citations", "Journal Impact Factor", "International", "Publication Country", "Publication Province", "Publication City", "Publisher", "Level of Contribution", "Is Presentation?", "Impact", "Open Access?", "Personal Remuneration", "Is Trainee?", "Trainee Details", "Is Most Significant Publication?", "Most Significant Contribution Details", "Education Publication", "Other Details (doesn't print)", "Author(s)", "Title", "Rest of Citation", "ISBNISSN", "Funding Reference Number"};
std::vector<std::string> presentationsHeaderCheck = {"Record Info", "Last Modified User", "Last Modified Date", "ID", "Member Name", "Primary Domain", "Date", "Type", "Area", "Role", "Activity Type", "Geographical Scope", "Host", "Country", "Province", "City", "Number of Attendees", "Main Audience", "Hours", "Teaching Effectiveness Score", "URL", "Competitive", "Education Presentation", "Remarks", "Funding Organization", "Authorship", "Title", "Rest of Citation", "Personal Remuneration", "Other Details (doesn't print)"};
std::vector<std::string> fundingHeaderCheck = {"Record Info", "Last Modified User", "Last Modified Date", "ID", "Member Name", "Primary Domain", "Start Date", "End Date", "Funding Type", "Status", "Peer Reviewed?", "Industry Grant?", "Role", "Short Title", "Title", "Application Summary", "Grant Purpose", "Area", "Principal Investigator", "Co-Investigators", "Grant and/or Account #", "Prorated Amount", "Administered By", "Funding Source", "Project", "Currency", "Received Amount", "Total Amount", "Member Share", "Monetary", "Rpt", "Hours Per Week", "Personnel Paid", "Rnw", "Education Grant", "Duplicate Reported", "Other Details (doesn't print)", "Year"};
// Another set of vectors. These were made since the 'expanded' csv in the /projectInfromation directory had different headers
std::vector<std::string> teachExpandedHeaderCheck = {"Record Info","Last Modified User","Last Modified Date","ID","Member Name","Primary Domain","Start Date","End Date","Program","Type of Course / Activity","Course / Activity","Geographical Scope","Institution / Organization","Faculty","Department","Division","Location","Hours per Teaching Session or Week","Number of Teaching Sessions or Weeks","Faculty Member Additional Comments","Number Of Trainees","Student Name(s)","Initial Lecture","Faculty Development","Comment","Other Details (doesn't print)","Total Hours"};
std::vector<std::string> publicationsExpandedHeaderCheck = {"Record Info","Last Modified User","Last Modified Date","ID","Member Name","Primary Domain","Publication Status","Pubmed Article ID","Type","Area","Status Date *","Role *","Peer Reviewed?","Author #","Journal Name | Published In | Book Title | etc.","Volume","Issue","Page Range","DOI","Website","Journal Impact Factor","International","Publisher","Is Presentation?","Personal Remuneration","Trainee Details","Is Most Significant Publication?","Most Significant Contribution Details","Education Publication","Other Details (doesn't print)","Author(s)","Title","Rest of Citation","ISBNISSN"};
std::vector<std::string> presentationsExpandedHeaderCheck = {"Record Info","Last Modified User","Last Modified Date","ID","Member Name","Primary Domain","Date","Type","Area","Role","Activity Type","Geographical Scope","Host","Country","Province","City","Number of Attendees","Hours","Teaching Effectiveness Score","Education Presentation","Remarks","Authorship","Title","Rest of Citation","Personal Remuneration"};
std::vector<std::string> grantsExpandedHeaderCheck = {"Record Info","Last Modified User","Last Modified Date","ID","Member Name","Primary Domain","Start Date","End Date","Funding Type","Status","Peer Reviewed?","Industry Grant?","Role","Short Title","Title","Application Summary","Grant Purpose","Area","Principal Investigator","Co-Investigators","Grant and/or Account #","Administered By","Funding Source","Project","Currency","Received Amount","Total Amount","Member Share","Monetary","Rpt","Hours Per Week","Personnel Paid","Rnw","Education Grant","Duplicate Reported","Other Details (doesn't print)","Year"};
//store the header check vectors onto a vector and get the headers of the csvreader object
std::vector<std::vector<std::string>> headerCheck = {teachHeaderCheck,publicationsHeaderCheck,presentationsHeaderCheck,fundingHeaderCheck,teachExpandedHeaderCheck,publicationsExpandedHeaderCheck,presentationsExpandedHeaderCheck,grantsExpandedHeaderCheck};
std::vector<std::string> header = this->getHeaders();
// To check if the input file is valid:
//simply check for equality between the input header and the header to the corresponding CSV type, and return the type
//associated with the file type
if(header == headerCheck[0] || header == headerCheck[4])//Teach
return 0;
else if(header == headerCheck[1] || header == headerCheck[5])//Publications
return 1;
else if(header == headerCheck[2] || header == headerCheck[6])//presentations
return 2;
else if(header == headerCheck[3] || header == headerCheck[7])//fund
return 3;
// otherwise return -1
return -1;
}
// Loads the CSV file at file_name.
void CSVReader::loadCSV(std::string file_name) {
std::ifstream myfile(file_name.c_str());
if (myfile.fail()) {
std::cout << "Couldn't open file \"" << file_name << "\"." << std::endl;
return;
}
if (myfile.is_open()) {
std::stringstream sstr;
sstr << myfile.rdbuf();
std::string f = sstr.str();
myfile.close();
size_t len = f.length();
bool setHeaders = false;
size_t pos = 0;
while( pos < len ) { // While the file's not empty
std::vector<std::string> line;
while( f.at( pos ) != '\n' && pos < len ) { // For each character in the line
std::string element = "";
while( f.at( pos ) != ',' && pos < len && f.at( pos ) != '\n' && f.at( pos ) != '\r' ) { // For each element
if( f.at( pos ) == '"' ) { // If we have a quote, continue till the next quote
pos++;
while( f[pos] != '"' && pos < len ) {
element += f.at( pos );
pos++;
}
pos++; // Last quote
} else {
element += f.at( pos );
pos++;
}
}
line.push_back( element );
if ( f.at( pos ) == '\n') {
break;
}
pos++;
}
if( !setHeaders ) {
setHeaders = true;
headers = line;
} else {
//checks if element in line is just whitespace, if it is change it to an empty string
all_data.push_back( line );
}
pos++;
}
}
}
void CSVReader::loadCSVFixed(std::string file_name) {
std::ifstream myfile(file_name.c_str());
if (myfile.fail()) {
std::cout << "Couldn't open file \"" << file_name << "\"." << std::endl;
return;
}
if (myfile.is_open()) {
std::stringstream sstr;
sstr << myfile.rdbuf();
std::string f = sstr.str();
myfile.close();
size_t len = f.length();
bool setHeaders = false;
size_t pos = 0;
while( pos < len ) { // While the file's not empty
std::vector<std::string> line;
while( f.at( pos ) != '\n' && pos < len ) { // For each character in the line
std::string element = "";
while( f.at( pos ) != ',' && pos < len && f.at( pos ) != '\n' && f.at( pos ) != '\r' ) { // For each element
if( f.at( pos ) == '"' ) { // If we have a quote, continue till the next quote
pos++;
while( f[pos] != '"' && pos < len ) {
if(pos == len -1)
break;
element += f.at( pos );
pos++;
}
pos++; // Last quote
} else {
element += f.at( pos );
pos++;
}
if(pos == len - 1)
break;
}
line.push_back( element );
if ( f.at( pos ) == '\n' || pos == len - 1) {
break;
}
pos++;
}
if( !setHeaders ) {
setHeaders = true;
headers = line;
} else {
for(size_t i = 0; i < line.size(); i++){
if(line[i].find_first_not_of (' ') == line[i].npos)
line[i] = "";
}
if(!std::equal(line.begin() + 1, line.end(), line.begin())){
all_data.push_back( line );
}
}
pos++;
}
}
}
// Returns the year in a date string.
int CSVReader::parseDateString(std::string dateString) {
int year;
sscanf(dateString.c_str(), "%4d", &year); // The only 4-digit number in a date field is a year, period
return year;
}
// Returns the header vector for a CSV
std::vector<std::string> CSVReader::getHeaders() {
return headers;
}
// Returns all data from a CSV
std::vector<std::vector<std::string> > CSVReader::getData() {
return all_data;
}
CSVReader::CSVReader() {
}
CSVReader::CSVReader(std::string file) {
loadCSV(file);
}
CSVReader::CSVReader(std::string file, bool is_fixed) {
if(is_fixed)
loadCSVFixed(file);
else
loadCSV(file);
}
| 56.156566 | 889 | 0.584675 | [
"object",
"vector"
] |
5a1e4c7560b7b17549368102306a06233d8f3903 | 7,133 | cxx | C++ | TransformProcessor/qSlicerTransformProcessorModule.cxx | markasselin/SlicerIGT | 907f3114986968d672afd5f7c1dfd879e251ab51 | [
"BSD-3-Clause"
] | 57 | 2015-10-10T12:35:51.000Z | 2022-03-17T06:58:21.000Z | TransformProcessor/qSlicerTransformProcessorModule.cxx | markasselin/SlicerIGT | 907f3114986968d672afd5f7c1dfd879e251ab51 | [
"BSD-3-Clause"
] | 149 | 2015-03-18T17:57:19.000Z | 2021-12-02T16:31:22.000Z | TransformProcessor/qSlicerTransformProcessorModule.cxx | markasselin/SlicerIGT | 907f3114986968d672afd5f7c1dfd879e251ab51 | [
"BSD-3-Clause"
] | 55 | 2015-03-17T21:30:46.000Z | 2021-10-05T12:57:42.000Z | /*==============================================================================
Program: 3D Slicer
Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
==============================================================================*/
// Slicer includes
#include "qSlicerCoreApplication.h"
// Qt includes
#include <QtPlugin>
#include <QTimer>
// TransformProcessor Logic includes
#include <vtkSlicerTransformProcessorLogic.h>
#include <vtkMRMLTransformProcessorNode.h>
// TransformProcessor includes
#include "qSlicerTransformProcessorModule.h"
#include "qSlicerTransformProcessorModuleWidget.h"
static const double UPDATE_OUTPUTS_PERIOD_SEC = 0.033; // about 30 fps update rate
//-----------------------------------------------------------------------------
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
#include <QtPlugin>
Q_EXPORT_PLUGIN2(qSlicerTransformProcessorModule, qSlicerTransformProcessorModule);
#endif
//-----------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_TransformProcessor
class qSlicerTransformProcessorModulePrivate
{
public:
qSlicerTransformProcessorModulePrivate();
QTimer UpdateAllOutputsTimer;
};
//-----------------------------------------------------------------------------
// qSlicerTransformProcessorModulePrivate methods
//-----------------------------------------------------------------------------
qSlicerTransformProcessorModulePrivate::qSlicerTransformProcessorModulePrivate()
{
}
//-----------------------------------------------------------------------------
// qSlicerTransformProcessorModule methods
//-----------------------------------------------------------------------------
qSlicerTransformProcessorModule::qSlicerTransformProcessorModule(QObject* _parent)
: Superclass(_parent)
, d_ptr(new qSlicerTransformProcessorModulePrivate)
{
Q_D(qSlicerTransformProcessorModule);
connect(&d->UpdateAllOutputsTimer, SIGNAL(timeout()), this, SLOT(updateAllOutputs()));
vtkMRMLScene* scene = qSlicerCoreApplication::application()->mrmlScene();
if (scene)
{
// Need to listen for any new watchdog nodes being added to start/stop timer
this->qvtkConnect(scene, vtkMRMLScene::NodeAddedEvent, this, SLOT(onNodeAddedEvent(vtkObject*, vtkObject*)));
this->qvtkConnect(scene, vtkMRMLScene::NodeRemovedEvent, this, SLOT(onNodeRemovedEvent(vtkObject*, vtkObject*)));
}
}
//-----------------------------------------------------------------------------
QStringList qSlicerTransformProcessorModule::categories()const
{
return QStringList() << "IGT";
}
//-----------------------------------------------------------------------------
qSlicerTransformProcessorModule::~qSlicerTransformProcessorModule()
{
}
//-----------------------------------------------------------------------------
QString qSlicerTransformProcessorModule::helpText()const
{
return "This module allows combining, inverting, stabilizing, termporal smoothing of transforms in real-time."
" For more information, visit <a href='https://github.com/SlicerIGT/SlicerIGT/#user-documentation'>SlicerIGT project website</a>.";
}
//-----------------------------------------------------------------------------
QString qSlicerTransformProcessorModule::acknowledgementText()const
{
return "This work was partially funded by Cancer Care Ontario and the Ontario Consortium for Adaptive Interventions in Radiation Oncology (OCAIRO),"
" and by National Institute of Health (grants 5P01CA067165, 5R01CA124377, 5R01CA138586, 2R44DE019322, 7R01CA124377, 5R42CA137886, 8P41EB015898).";
}
//-----------------------------------------------------------------------------
QStringList qSlicerTransformProcessorModule::contributors()const
{
QStringList moduleContributors;
moduleContributors << QString("Franklin King (PerkLab, Queen's University)")
<< QString("Thomas Vaughan (PerkLab, Queen's University)")
<< QString("Andras Lasso (PerkLab, Queen's University)")
<< QString("Tamas Ungi (PerkLab, Queen's University)")
<< QString("Laurent Chauvin (BWH)")
<< QString("Jayender Jagadeesan (BWH)");
return moduleContributors;
}
//-----------------------------------------------------------------------------
QIcon qSlicerTransformProcessorModule::icon()const
{
return QIcon(":/Icons/TransformProcessor.png");
}
//-----------------------------------------------------------------------------
void qSlicerTransformProcessorModule::setup()
{
this->Superclass::setup();
}
//-----------------------------------------------------------------------------
qSlicerAbstractModuleRepresentation * qSlicerTransformProcessorModule::createWidgetRepresentation()
{
return new qSlicerTransformProcessorModuleWidget;
}
//-----------------------------------------------------------------------------
vtkMRMLAbstractLogic* qSlicerTransformProcessorModule::createLogic()
{
return vtkSlicerTransformProcessorLogic::New();
}
// --------------------------------------------------------------------------
void qSlicerTransformProcessorModule::onNodeAddedEvent(vtkObject*, vtkObject* node)
{
Q_D(qSlicerTransformProcessorModule);
vtkMRMLTransformProcessorNode* processorNode = vtkMRMLTransformProcessorNode::SafeDownCast(node);
if (processorNode)
{
// If the timer is not active
if (!d->UpdateAllOutputsTimer.isActive())
{
d->UpdateAllOutputsTimer.start(UPDATE_OUTPUTS_PERIOD_SEC * 1000.0);
}
}
}
// --------------------------------------------------------------------------
void qSlicerTransformProcessorModule::onNodeRemovedEvent(vtkObject*, vtkObject* node)
{
Q_D(qSlicerTransformProcessorModule);
vtkMRMLTransformProcessorNode* processorNode = vtkMRMLTransformProcessorNode::SafeDownCast(node);
if (processorNode)
{
// If the timer is active
if (d->UpdateAllOutputsTimer.isActive())
{
// Check if there is any other sequence browser node left in the Scene
vtkMRMLScene* scene = qSlicerCoreApplication::application()->mrmlScene();
if (scene)
{
std::vector<vtkMRMLNode*> nodes;
this->mrmlScene()->GetNodesByClass("vtkMRMLTransformProcessorNode", nodes);
if (nodes.size() == 0)
{
// The last sequence browser was removed
d->UpdateAllOutputsTimer.stop();
}
}
}
}
}
//-----------------------------------------------------------------------------
void qSlicerTransformProcessorModule::updateAllOutputs()
{
Q_D(qSlicerTransformProcessorModule);
vtkSlicerTransformProcessorLogic* processorLogic = vtkSlicerTransformProcessorLogic::SafeDownCast(this->Superclass::logic());
if (!processorLogic)
{
return;
}
processorLogic->UpdateAllOutputs();
}
| 36.768041 | 150 | 0.598346 | [
"vector",
"3d"
] |
5a28bb598632a339960abf26de4baee3948724f3 | 4,560 | hpp | C++ | mdtransform.hpp | vbirds/MarkdownParser | 85d955bbbfac5b18b91116f328e48e855c93097c | [
"MIT"
] | 1 | 2017-11-26T10:03:24.000Z | 2017-11-26T10:03:24.000Z | mdtransform.hpp | vbirds/MarkdownParser | 85d955bbbfac5b18b91116f328e48e855c93097c | [
"MIT"
] | null | null | null | mdtransform.hpp | vbirds/MarkdownParser | 85d955bbbfac5b18b91116f328e48e855c93097c | [
"MIT"
] | 1 | 2022-03-28T08:49:38.000Z | 2022-03-28T08:49:38.000Z |
#ifndef MD2HTML
#define MD2HTML
#include <string.h>
#include <string>
#include <vector>
#include <utility>
#define maxLength 10000
// 词法关键字枚举
enum{
nul = 0,
paragraph = 1,
href = 2,
ul = 3,
ol = 4,
li = 5,
em = 6,
strong = 7,
hr = 8,
br = 9,
image = 10,
quote = 11,
h1 = 12,
h2 = 13,
h3 = 14,
h4 = 15,
h5 = 16,
h6 = 17,
blockcode = 18,
code = 19
};
// HTML 前置标签
const std::string frontTag[] = {
"","<p>","","<ul>","<ol>","<li>","<em>","<strong>",
"<hr color=#CCCCCC size=1 />","<br />",
"","<blockquote>",
"<h1 ","<h2 ","<h3 ","<h4 ","<h5 ","<h6 ", // 右边的尖括号预留给添加其他的标签属性, 如 id
"<pre><code>","<code>"
};
// HTML 后置标签
const std::string backTag[] = {
"","</p>","","</ul>","</ol>","</li>","</em>","</strong>",
"","","","</blockquote>",
"</h1>","</h2>","</h3>","</h4>","</h5>","</h6>",
"</code></pre>","</code>"
};
//保存目录的结构
typedef struct Cnode
{
std::vector<Cnode *> ch;
std::string heading;
std::string tag;
Cnode (const std::string & hd) : heading(hd) {}
} Cnode;
typedef struct node
{
int type; //节点代表类型
std::vector<node *> ch;
// 用来存放三个重要的属性, elem[0] 保存了要显示的内容
//elem[1] 保存连接 elem[2] 保存了 title
std::string elem[3];
node (int _type) : type(_type) {}
} node;
class MarkdownTransform{
private:
node *root, *now;
Cnode *Croot;
std::string content, TOC;
int cntTag = 0;
char s[maxLength];
public:
/*!
* \brief start 开始解析一行中开始的空格和 Tab
* \param src 源串
* \return 由空格数和有内容处的 char* 指针组成的 std::pair
*/
inline std::pair<int, char*> start(char *src)
{
if (src == nullptr || 0 == (int)strlen(src))
{
return std::make_pair(0, nullptr);
}
//统计空格键和Tab键的个数
int cntspace = 0, cnttab = 0;
for (int i = 0; src[i] != '\0'; ++i)
{
if ( ' ' == src[i])
{
++cntspace;
continue;
}
else if ('\t' == src[i])
{
++cnttab;
continue;
}
// 如果内容前有空格和 Tab,那么将其统一按 Tab 的个数处理,
// 其中, 一个 Tab = 四个空格
return std::make_pair(cnttab + cntspace / 4, src + i);
}
return std::make_pair(0, nullptr);
}
/*!
* \brief judgeType 判断当前行的类型
* \param str 源串
* \return 当前行的类型和除去行标志性关键字的正是内容的 char* 指针组成的 std::pair
*/
inline std::pair<int, char*> judgeType(char * src)
{
char * ptr = src;
//跳过 '#'
while ('#' == *ptr)
{
++ptr;
}
// 如果出现空格, 则说明是 `<h>` 标签
if (ptr - src > 0 && ' ' == *ptr)
{
return std::make_pair(ptr - src + h1 - 1, ptr + 1);
}
ptr = src;
// 如果出现 ``` 则说明是代码块
if (0 == strncmp(ptr, "```", 3))
{
return std::make_pair(blockcode, ptr + 3);
}
// 如果出现 * + -, 并且他们的下一个字符为空格,则说明是列表
if (0 == strncmp(ptr, "- ", 2) || \
0 == strncmp(ptr, "* ", 2) || \
0 == strncmp(ptr, "+ ", 2) )
{
return std::make_pair(ul, ptr + 1);
}
// 如果出现的是数字, 且下一个字符是 . 则说明是是有序列表
char *ptr1 = ptr;
while (*ptr1 && (isdigit(*ptr1)))
{
++ptr1;
}
if (ptr1 != ptr && *ptr1 == '.' && ptr1[1] == ' ')
{
return std::make_pair(ol, ptr1 + 1);
}
// 如果出现 > 且下一个字符为空格,则说明是引用
if ('>' == *ptr && (' ' == ptr[1]))
{
return std::make_pair(quote, ptr + 1);
}
// 否则,就是普通段落
return std::make_pair(paragraph, ptr);
}
// 判断是否为标题
inline bool isHeading(node *v)
{
return (v->type >= h1 && v->type <= h6);
}
// 判断是否为图片
inline bool isImage(node *v)
{
return (v->type == image);
}
// 判断是否为超链接
inline bool isHref(node *v)
{
return (v->type == href);
}
public:
// 构造函数
MarkdownTransform(const std::string &filename){}
// 获得 Markdown 目录
std::string getTableOfContents() { return TOC; }
// 获得 Markdown 内容
std::string getContents() { return content; }
// 析构函数
~MarkdownTransform(){}
};
#endif
| 21.923077 | 74 | 0.422368 | [
"vector"
] |
5a29679950cd8e394f6eb2e2d0d268225c7ce4ea | 463 | cpp | C++ | src/0389.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | src/0389.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | src/0389.cpp | killf/leetcode_cpp | d1f308a9c3da55ae5416ea28ec2e7a3146533ae9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
#include <map>
#include <set>
#include <hash_map>
#include <hash_set>
#include <queue>
#include <stack>
using namespace std;
class Solution {
public:
char findTheDifference(string s, string t) {
int m[26] = {0};
for (auto c:s)m[c - 'a']++;
for (auto c:t) {
int k = c - 'a';
if (m[k] == 0)return c;
m[k]--;
}
return 0;
}
}; | 16.535714 | 46 | 0.585313 | [
"vector"
] |
5a2c61d504173f7d123d20056010289bbed915d4 | 4,060 | cpp | C++ | tc 160+/Library.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/Library.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/Library.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <set>
#include <map>
using namespace std;
bool intersects(const set<string> &a, const set<string> &b) {
vector<string> t;
set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(t));
return t.size() > 0;
}
class Library {
public:
int documentAccess(vector <string> records, vector <string> userGroups, vector <string> roomRights) {
set<string> G(userGroups.begin(), userGroups.end());
set<string> R(roomRights.begin(), roomRights.end());
map< string, set<string> > A;
map< string, set<string> > B;
for (int i=0; i<(int)records.size(); ++i) {
istringstream is(records[i]);
string d, r, u;
is >> d >> r >> u;
A[d].insert(r);
B[d].insert(u);
}
int sol = 0;
for (map<string, set<string> >::const_iterator it=A.begin(); it!=A.end(); ++it) {
if (intersects(G, B[it->first]) && intersects(R, A[it->first])) {
++sol;
}
}
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"diary computers editor","fairytale gardening editor","comix cars author","comix cars librarian"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"employee","editor","author"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"history","cars","computers"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(0, Arg3, documentAccess(Arg0, Arg1, Arg2)); }
void test_case_1() { string Arr0[] = {"diary computers editor","fairytale gardening editor","comix cars author","comix cars librarian"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"employee","editor","author","librarian"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"history","cars","computers"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(1, Arg3, documentAccess(Arg0, Arg1, Arg2)); }
void test_case_2() { string Arr0[] = {"diary computers editor","fairytale gardening editor","comix cars author","comix cars librarian"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"employee","editor","author","librarian"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; verify_case(2, Arg3, documentAccess(Arg0, Arg1, Arg2)); }
void test_case_3() { string Arr0[] = {"a b c","a b d","b b c","b b d","e c d","e c b","e c c","t d e"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"c","d","x"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"a","b","c"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 3; verify_case(3, Arg3, documentAccess(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Library ___test;
___test.run_test(-1);
}
// END CUT HERE
| 54.864865 | 525 | 0.610837 | [
"vector"
] |
5a3b86c4c559238fb0cd84ac7e82ee3dde825787 | 3,258 | hpp | C++ | src/realm/impl/copy_replication.hpp | aleyooop/realm-core | 9874d5164927ea39273b241a5af14b596a3233e9 | [
"Apache-2.0"
] | null | null | null | src/realm/impl/copy_replication.hpp | aleyooop/realm-core | 9874d5164927ea39273b241a5af14b596a3233e9 | [
"Apache-2.0"
] | null | null | null | src/realm/impl/copy_replication.hpp | aleyooop/realm-core | 9874d5164927ea39273b241a5af14b596a3233e9 | [
"Apache-2.0"
] | null | null | null | /*************************************************************************
*
* Copyright 2021 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#ifndef REALM_COPY_REPLICATION_HPP
#define REALM_COPY_REPLICATION_HPP
#include <realm/replication.hpp>
#include <realm/db.hpp>
namespace realm::impl {
class CopyReplication : public Replication {
public:
CopyReplication(TransactionRef tr)
: m_tr(tr)
{
}
using version_type = _impl::History::version_type;
void add_class(TableKey, StringData name, bool is_embedded) override;
void add_class_with_primary_key(TableKey, StringData name, DataType type, StringData pk_name,
bool nullable) override;
void insert_column(const Table* t, ColKey col_key, DataType type, StringData name, Table* dest) override;
void create_object_with_primary_key(const Table* t, ObjKey key, Mixed primary_key) override;
void set(const Table* t, ColKey col_key, ObjKey key, Mixed value, _impl::Instruction) override;
void list_clear(const CollectionBase& coll) override;
void list_insert(const CollectionBase& coll, size_t idx, Mixed value, size_t) override;
void set_insert(const CollectionBase& coll, size_t, Mixed value) override;
void dictionary_insert(const CollectionBase& coll, size_t, Mixed key, Mixed value) override;
private:
Table* get_table_in_destination_realm()
{
auto& dest = m_table_map[m_current.table];
if (!dest) {
dest = m_tr->get_table(m_current.table->get_name()).unchecked_ptr();
}
return dest;
}
ColKey get_colkey_in_destination_realm(ColKey c)
{
auto col_name = m_current.table->get_column_name(c);
return get_table_in_destination_realm()->get_column_key(col_name);
}
void sync(const CollectionBase& coll)
{
auto t = coll.get_table();
auto obj_key = coll.get_owner_key();
sync(t.unchecked_ptr(), obj_key);
}
// Make m_current state match the input parameters
void sync(const Table* t, ObjKey obj_key);
// Returns link to target object - null if embedded object
Mixed handle_link(ColKey col_key, Mixed val, util::FunctionRef<void(TableRef)> create_embedded_func);
TransactionRef m_tr;
struct State {
// Table and object in source realm
const Table* table = nullptr;
ObjKey obj_key;
// Corresponding object in destination realm
Obj obj_in_destination;
};
State m_current;
std::vector<State> m_states;
std::map<const Table*, Table*> m_table_map;
};
} // namespace realm::impl
#endif /* REALM_COPY_REPLICATION_HPP */
| 36.606742 | 109 | 0.671578 | [
"object",
"vector"
] |
5a444449523d5e3901d3428f4ca58b594e06a0a0 | 9,295 | cpp | C++ | src/DeviceDiscoverer/Impl/QBtDeviceDiscoverer_symbian.cpp | ftylitak/QBluetoothZero | 3e4a018a5e62705b62fa2cbc64a27c3f66059982 | [
"Apache-2.0"
] | 2 | 2018-02-05T13:22:49.000Z | 2019-01-19T12:04:20.000Z | src/DeviceDiscoverer/Impl/QBtDeviceDiscoverer_symbian.cpp | ftylitak/QBluetoothZero | 3e4a018a5e62705b62fa2cbc64a27c3f66059982 | [
"Apache-2.0"
] | 1 | 2018-02-04T18:37:50.000Z | 2018-02-05T23:16:31.000Z | src/DeviceDiscoverer/Impl/QBtDeviceDiscoverer_symbian.cpp | ftylitak/QBluetoothZero | 3e4a018a5e62705b62fa2cbc64a27c3f66059982 | [
"Apache-2.0"
] | 3 | 2018-05-24T02:35:43.000Z | 2019-02-28T16:38:52.000Z | /*
* QBtDeviceDiscoverer_symbian.cpp
*
*
* Author: Ftylitakis Nikolaos, Luis Valente
*
* 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 "../QBtDeviceDiscoverer_symbian.h"
#include "../QBtDeviceDiscoverer.h"
#include <bt_sock.h>
#include <bttypes.h>
_LIT(KBTLinkManagerTxt,"BTLinkManager");
QBtDeviceDiscovererPrivate* QBtDeviceDiscovererPrivate::NewL(QBtDeviceDiscoverer *publicClass)
{
QBtDeviceDiscovererPrivate* self = QBtDeviceDiscovererPrivate::NewLC(publicClass);
CleanupStack::Pop(self);
return self;
}
QBtDeviceDiscovererPrivate* QBtDeviceDiscovererPrivate::NewLC(QBtDeviceDiscoverer *publicClass)
{
QBtDeviceDiscovererPrivate* self = new (ELeave) QBtDeviceDiscovererPrivate(publicClass);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
void QBtDeviceDiscovererPrivate::ConstructL()
{
User::LeaveIfError(iSocketServ.Connect());
TProtocolName protocolName(KBTLinkManagerTxt);
User::LeaveIfError(iSocketServ.FindProtocol(protocolName,iProtocolInfo));
}
// ----------------------------------------------------------------------------
// CDeviceDiscoverer::CDeviceDiscoverer(RSocketServ *aSocketServ,
// MDeviceDiscoObserver *aObserver)
//
// constructor
// ----------------------------------------------------------------------------
QBtDeviceDiscovererPrivate::QBtDeviceDiscovererPrivate (QBtDeviceDiscoverer *publicClass)
: CActive (CActive::EPriorityStandard),
sizeOfListeningQueue(4),
p_ptr(publicClass),
iLIAC (false),
iIsBusy (false)
{
CActiveScheduler::Add(this);
iDevList = new QBtDevice::List();
}
// ----------------------------------------------------------------------------
// CDeviceDiscoverer::~CDeviceDiscoverer()
//
// destructor
// ----------------------------------------------------------------------------
QBtDeviceDiscovererPrivate::~QBtDeviceDiscovererPrivate()
{
// cancel active object
if(IsActive())
Cancel();
//iResolver.Close();
delete iDevList;
}
// ----------------------------------------------------------------------------
// CDeviceDiscoverer::DiscoverDevicesL(TDeviceDataList *aDevDataList)
//
// discover remote devices. RHostResolver will be used to do the discovery.
// any found devices will be placed in aDevDataList.
// ----------------------------------------------------------------------------
void QBtDeviceDiscovererPrivate::DiscoverDevices()
{
if (!IsActive())
{
// initialize host resolver
// load protocol for discovery
iResolver.Close();
TInt err = iResolver.Open(iSocketServ, iProtocolInfo.iAddrFamily, iProtocolInfo.iProtocol);
if (err)
{
EmitErrorSignal (QBtDeviceDiscoverer::BluetoothInUse);
return;
}
// set as busy
iIsBusy = true;
// wipe existing device data list, start fresh
iDevList->clear();
// start device discovery by invoking remote address lookup
TUint myIAC(iLIAC ? KLIAC : KGIAC);
iAddr.SetIAC(myIAC);
iAddr.SetAction(KHostResInquiry|KHostResName|KHostResIgnoreCache);
iResolver.GetByAddress(iAddr, iEntry, iStatus);
emit p_ptr->discoveryStarted();
SetActive();
}
else
{
EmitErrorSignal (QBtDeviceDiscoverer::BluetoothInUse) ;
return;
}
}
void QBtDeviceDiscovererPrivate::RunL()
{
// RHostResolver.GetByAddress(..) has completed, process results
if ( iStatus == KErrNone )
{
TBTSockAddr address = iEntry().iAddr;
TBTDevAddr btAddress = address.BTAddr();
//QByteArray btAddressArray((const char*)btAddress.Des().Ptr(), 6);
QBtAddress qtBtDeviceAddress(btAddress);
THostName nameDevice = iEntry().iName;
QString qtNameDevice = QString::fromUtf16(nameDevice.Ptr(),nameDevice.Length());
TInquirySockAddr& sa = TInquirySockAddr::Cast( iEntry().iAddr );
//TUint8 minorClass = sa.MinorClassOfDevice();
//quint8 qMinorClass = quint8(minorClass);
//Set major device class
TUint16 majorClass = sa.MajorClassOfDevice();
QBtDevice::DeviceMajor qtDeviceMajorClass;
switch (majorClass) {
case 0x00: //computer
qtDeviceMajorClass = QBtDevice::Miscellaneous;
break;
case 0x01:
qtDeviceMajorClass = QBtDevice::Computer;
break;
case 0x02:
qtDeviceMajorClass = QBtDevice::Phone;
break;
case 0x03:
qtDeviceMajorClass = QBtDevice::LANAccess;
break;
case 0x04:
qtDeviceMajorClass = QBtDevice::AudioVideo;
break;
case 0x05:
qtDeviceMajorClass = QBtDevice::Peripheral;
break;
case 0x06:
qtDeviceMajorClass = QBtDevice::Imaging;
break;
case 0x07:
qtDeviceMajorClass = QBtDevice::Wearable;
break;
case 0x08:
qtDeviceMajorClass = QBtDevice::Toy;
break;
default:
qtDeviceMajorClass = QBtDevice::Uncategorized;
break;
}
//QBtDevice* remoteDevice = new QBtDevice(qtNameDevice, qtBtDeviceAddress, qtDeviceMajorClass);
QBtDevice remoteDevice (qtNameDevice, qtBtDeviceAddress, qtDeviceMajorClass);
QT_TRYCATCH_LEAVING (EmitNewDeviceFoundSignal (remoteDevice));
// store on list
iDevList->append (remoteDevice);
// next
iResolver.Next(iEntry,iStatus);
SetActive();
}
else if (iStatus == KErrHostResNoMoreResults) {
// Note emit may throw. We translate to Leave here.
QT_TRYCATCH_LEAVING (EmitDiscoveryStoppedSignal() );
}
else {
QT_TRYCATCH_LEAVING (EmitDiscoveryStoppedSignal() );
//ErrorConvertToLocalL(iStatus.Int());
}
}
void QBtDeviceDiscovererPrivate::DoCancel()
{
// Note that must trap any errors here - Cancel is called in destructor and destructor must not throw.
QT_TRY
{
EmitDiscoveryStoppedSignal();
}
QT_CATCH (std::exception& e)
{}
iResolver.Cancel();
}
// ----------------------------------------------------------------------------
// CDeviceDiscoverer::HasDevices()
//
// returns true if any devices were discovered
// ----------------------------------------------------------------------------
TBool QBtDeviceDiscovererPrivate::HasDevices()
{
//TBool exists = EFalse;
return iDevList->size() > 0;
}
// ----------------------------------------------------------------------------
// CBluetoothPMPExampleEngine::SetLIAC
// ----------------------------------------------------------------------------
void QBtDeviceDiscovererPrivate::SetLIAC( TBool aState )
{
iLIAC = aState;
}
// ----------------------------------------------------------------------------
// CBluetoothPMPExampleEngine::StopDiscovery
// ----------------------------------------------------------------------------
void QBtDeviceDiscovererPrivate::StopDiscovery()
{
if (IsActive())
Cancel();
else
{
// Note, may throw. That is OK, stopSearch() is called from Qt code only.
EmitErrorSignal (QBtDeviceDiscoverer::BluetoothAlreadyStopped) ;
}
}
// ----------------------------------------------------------------------------
// QBtDeviceDiscovererPrivate::GetInquiredDevices
// Gets the list of devices that where found during the last search
// ----------------------------------------------------------------------------
const QBtDevice::List& QBtDeviceDiscovererPrivate::GetInquiredDevices() const
{
return *iDevList;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
TBool QBtDeviceDiscovererPrivate::IsBusy() const
{
return iIsBusy;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void QBtDeviceDiscovererPrivate::EmitErrorSignal (QBtDeviceDiscoverer::DeviceDiscoveryErrors error)
{
try
{
emit p_ptr->error (error);
iIsBusy = false;
}
catch (...)
{
iIsBusy = false;
throw;
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void QBtDeviceDiscovererPrivate::EmitDiscoveryStoppedSignal()
{
try
{
emit p_ptr->discoveryStopped();
iIsBusy = false;
}
catch (...)
{
iIsBusy = false;
throw;
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void QBtDeviceDiscovererPrivate::EmitNewDeviceFoundSignal (const QBtDevice & device)
{
try
{
emit p_ptr->newDeviceFound (device);
iIsBusy = false;
}
catch (...)
{
iIsBusy = false;
throw;
}
}
| 28.77709 | 104 | 0.56213 | [
"object"
] |
5a4ebd6f3de555acccd72c61bd377ffd8ce69780 | 3,378 | cc | C++ | paddle/fluid/framework/ir/fc_fuse_pass.cc | lijiancheng0614/Paddle | f980b29e6259b8e51f4ee04260e3a84233f337df | [
"Apache-2.0"
] | null | null | null | paddle/fluid/framework/ir/fc_fuse_pass.cc | lijiancheng0614/Paddle | f980b29e6259b8e51f4ee04260e3a84233f337df | [
"Apache-2.0"
] | null | null | null | paddle/fluid/framework/ir/fc_fuse_pass.cc | lijiancheng0614/Paddle | f980b29e6259b8e51f4ee04260e3a84233f337df | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/framework/ir/fc_fuse_pass.h"
#include <string>
#include <vector>
#include "paddle/fluid/platform/enforce.h"
namespace paddle {
namespace framework {
namespace ir {
std::unique_ptr<ir::Graph> FCFusePass::ApplyImpl(
std::unique_ptr<ir::Graph> graph) const {
PADDLE_ENFORCE(graph.get());
FusePassBase::Init("fc_fuse", graph.get());
std::unordered_set<Node*> nodes2delete;
GraphPatternDetector gpd;
// BuildFCPattern(gpd.mutable_pattern());
auto* x = gpd.mutable_pattern()
->NewNode("fc_fuse/x")
->AsInput()
->assert_is_op_input("mul", "X");
patterns::FC(gpd.mutable_pattern(), "fc_fuse", x, true /*with bias*/);
#define GET_NODE(id) \
PADDLE_ENFORCE(subgraph.count(gpd.pattern().RetrieveNode("fc_fuse/" #id)), \
"pattern has no Node called %s", #id); \
auto* id = subgraph.at(gpd.pattern().RetrieveNode("fc_fuse/" #id)); \
PADDLE_ENFORCE_NOT_NULL(id, "subgraph has no node %s", "fc_fuse/" #id);
int found_fc_count = 0;
auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
Graph* g) {
VLOG(4) << "handle FC fuse";
// Currently, there is no FC op available, so I will just simulate the
// scenerio.
// FC's fusion is simple, just op fuse, no need to process the
// parameters.
GET_NODE(x); // x
GET_NODE(w); // Y
GET_NODE(fc_bias); // bias
GET_NODE(fc_out); // Out
GET_NODE(mul); // MUL op
GET_NODE(elementwise_add); // ELEMENT_ADD op
GET_NODE(mul_out); // tmp
#undef GET_NODE
// Create an FC Node.
OpDesc desc;
std::string fc_x_in = x->Name();
std::string fc_Y_in = w->Name();
std::string fc_bias_in = fc_bias->Name();
std::string fc_out_out = fc_out->Name();
desc.SetInput("Input", std::vector<std::string>({fc_x_in}));
desc.SetInput("W", std::vector<std::string>({fc_Y_in}));
desc.SetInput("Bias", std::vector<std::string>({fc_bias_in}));
desc.SetOutput("Out", std::vector<std::string>({fc_out_out}));
desc.SetType("fc");
auto fc_node = g->CreateOpNode(&desc); // OpDesc will be copied.
GraphSafeRemoveNodes(graph.get(), {mul, elementwise_add, mul_out});
IR_NODE_LINK_TO(x, fc_node);
IR_NODE_LINK_TO(w, fc_node);
IR_NODE_LINK_TO(fc_bias, fc_node);
IR_NODE_LINK_TO(fc_node, fc_out);
found_fc_count++;
};
gpd(graph.get(), handler);
AddStatis(found_fc_count);
return graph;
}
} // namespace ir
} // namespace framework
} // namespace paddle
REGISTER_PASS(fc_fuse_pass, paddle::framework::ir::FCFusePass);
| 35.557895 | 78 | 0.637655 | [
"vector"
] |
99009bca896c9b5d8b522c4952bad6d88f628c28 | 5,639 | cc | C++ | qset.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | 1 | 2015-07-25T15:09:11.000Z | 2015-07-25T15:09:11.000Z | qset.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | 1 | 2015-09-19T00:44:24.000Z | 2015-09-21T16:47:12.000Z | qset.cc | JoeyEremondi/treewidth-memoization | 5cd6be9e05bba189d14409f28c37805948ef11b3 | [
"BSD-3-Clause"
] | null | null | null |
#include <cstdlib>
#include <iostream>
#include <climits>
#include <algorithm>
#include <vector>
#include <utility>
#include <ctime>
#include "qset.hh"
#include "graphTypes.hh"
#include <boost/graph/visitors.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/subgraph.hpp>
//Basically just a DFS
//We start at v, and search
//We expand vertices in S
//And we add to our count (without expanding) for those not in S
int sizeQ(int n, const VSet &S, Vertex v, const Graph& G)
{
//std::cout << "Q: starting with S = " << showSet(S) << "\n";
//int n = boost::num_vertices(G);
std::vector<Vertex> open; //TODO replace
open.reserve(n);
open.push_back(v);
//Uses more memory than VSet, but is faster
VSet closed; //TODO replace
int numInQ = 0;
while (!open.empty())
{
Vertex w = open.back();
open.pop_back();
auto outEdges = boost::out_edges(w, G);
auto loopEnd = outEdges.second;
for (auto iter = outEdges.first; iter != loopEnd; ++iter)
{
Edge e = *iter;
Vertex u = boost::target(e, G);
if (!closed.contains(u))
{
closed.insert(u);
if (S.contains(u) && u != v )
{
open.push_back(u);
}
else if (u != v)
{
numInQ++;
}
}
}
}
return numInQ;
}
void findQvalues(int n, const VSet &S, const Graph &G, std::vector<int>& outValues)
{
//Store which vertices we've seen over all DFSes, makes sure we get all connected components
VSet globalUnseen = S;
//Store the set of vertices each connected component can reach
std::vector<VSet> canReach(n);
//For each vertex not in S, store which connected components it connects to
std::vector<std::vector<Vertex>> reachableFrom(n);
for (auto& subVec : reachableFrom)
{
subVec.reserve(n);
}
//Also store it as a set, to keep the vector as small as possible
std::vector<VSet> reachableFromSet(n);
if (!S.empty())
{
while (!globalUnseen.empty())
{
std::vector<Vertex> open;
Vertex first = globalUnseen.first();
Vertex currentCC = first;
//std::cout << "CC " << currentCC << "\n";
open.push_back(first);
//Vertices we've already seen
VSet closed;
while (!open.empty())
{
Vertex w = open.back();
open.pop_back();
//Mark that we've seen this vertex in our connected component search
globalUnseen.erase(w);
auto outEdges = boost::out_edges(w, G);
//std::cout << "Q: expanding " << w << "\n";
for (auto iter = outEdges.first; iter != outEdges.second; ++iter)
{
Vertex u = boost::target(*iter, G);
//std::cout << "Q: found neighbour " << u << "\n";
if (!closed.contains(u))
{
//std::cout << "Q: adding " << u << " to closed\n";
closed.insert(u);
if (S.contains(u))
{
//std::cout << "Q: adding " << u << " to queue\n";
open.push_back(u);
reachableFrom[u].push_back(currentCC);
}
else if (!reachableFromSet[u].contains(currentCC))
{
//Mark that this CC and our vertex u, not in s, can reach each other
reachableFrom[u].push_back(currentCC);
reachableFromSet[u].insert(currentCC);
canReach[currentCC].insert(u);
//std::cout << "Reached " << u << " from " << w << " in CC " << currentCC << "\n";
}
}
}
}
}
}
//For each vertex, we union the reachable vertices from each connected component
//and take the number of elements
//We also add in any vertices immediately adjacent to v which aren't in S
auto vertInfo = vertices(G);
for (auto iter = vertInfo.first; iter != vertInfo.second; ++iter)
{
Vertex v = *iter;
VSet allReachableVerts;
auto loopEnd = reachableFrom[v].end();
for (auto connComp = reachableFrom[v].begin(); connComp != loopEnd; ++connComp)
{
allReachableVerts.addAll(canReach[*connComp]);
}
auto outEdges = boost::out_edges(v, G);
//std::cout << "Q: expanding " << w << "\n";
//Every edge of our current vertex is also in its Q set, unless it's in S
for (auto iter = outEdges.first; iter != outEdges.second; ++iter)
{
//Edge e = *iter;
Vertex u = boost::target(*iter, G);
if (!S.contains(u))
{
allReachableVerts.insert(u);
;
}
}
allReachableVerts.erase(v);
outValues[v] = allReachableVerts.size();
}
}
int qCheck(int n, VSet S, Vertex v, Graph G)
{
int numInQ = 0;
auto vertInfo = vertices(G);
auto edgeInfo = edges(G);
for (auto iter = vertInfo.first; iter != vertInfo.second; iter++)
{
Vertex u = *iter;
if (u != v && !S.contains(u))
{
VSet inducingSet = S;
inducingSet.insert(v);
inducingSet.insert(u);
std::vector<Vertex> members;
inducingSet.members(members);
Graph GG;
for (auto addVert = vertInfo.first; addVert != vertInfo.second; addVert++)
{
boost::add_vertex(GG);
}
for (auto edgeIter = edgeInfo.first; edgeIter != edgeInfo.second; edgeIter++)
{
Vertex from = boost::source(*edgeIter, G);
Vertex to = boost::target(*edgeIter, G);
if (inducingSet.contains(to) && inducingSet.contains(from))
{
boost::add_edge(to, from, GG);
}
}
std::vector<int> distances(boost::num_vertices(G) + 1);
boost::breadth_first_search(GG,
v,
boost::visitor(boost::make_bfs_visitor(boost::record_distances(&distances[0], boost::on_tree_edge()))));
if (distances[u] != 0)
{
numInQ++;
}
}
}
return numInQ;
}
std::string showSet(VSet S) {
std::ostringstream result;
result << "{";
std::vector<Vertex> members;
S.members(members);
for (auto iter = members.begin(); iter != members.end(); ++iter)
{
result << *iter << " ; ";
}
result << "}";
return result.str();
}
| 21.359848 | 108 | 0.618549 | [
"vector"
] |
990166cc52f90f24ffca854527287c02e7d12bd3 | 4,384 | hpp | C++ | Source/Runtime/Engine/Public/GameFramework/Actor.hpp | Othereum/NoEngineGame | e3c9c9a330ba8e724cd96f98355b556d24e73d9d | [
"MIT"
] | 23 | 2020-05-21T06:25:29.000Z | 2021-04-06T03:37:28.000Z | Source/Runtime/Engine/Public/GameFramework/Actor.hpp | Othereum/NoEngineGame | e3c9c9a330ba8e724cd96f98355b556d24e73d9d | [
"MIT"
] | 72 | 2020-06-09T04:46:27.000Z | 2020-12-07T03:20:51.000Z | Source/Runtime/Engine/Public/GameFramework/Actor.hpp | Othereum/NoEngineGame | e3c9c9a330ba8e724cd96f98355b556d24e73d9d | [
"MIT"
] | 4 | 2020-06-10T02:23:54.000Z | 2022-03-28T07:22:08.000Z | #pragma once
#include "Camera/CameraTypes.hpp"
#include "TimerManager.hpp"
#include <unordered_set>
namespace logcat
{
extern ENGINE_API const LogCategory kActor;
}
namespace oeng
{
inline namespace engine
{
class World;
class Engine;
class ActorComponent;
class SceneComponent;
class ENGINE_API AActor : public Object
{
CLASS_BODY(AActor)
public:
void Destroy();
template <class T> T& AddComponent()
{
auto ptr = MakeShared<T>();
auto& ref = *ptr;
RegisterComponent(std::move(ptr));
return ref;
}
template <class T> T& AddComponent(int update_order)
{
auto ptr = MakeShared<T>();
auto& ref = *ptr;
ref.update_order_ = update_order;
RegisterComponent(std::move(ptr));
return ref;
}
[[nodiscard]] virtual ViewInfo CalcCamera() const;
/**
* Add tag.
* @param tag Name of the tag to be added.
* @return `true` if added successfully. `false` if already exists.
*/
bool AddTag(Name tag)
{
return tags_.insert(tag).second;
}
/**
* Remove tag.
* @param tag Name of the tag to be removed.
* @return `true` if removed successfully. `false` if not found.
*/
bool RemoveTag(Name tag)
{
return tags_.erase(tag);
}
/**
* Check if the actor has given tag.
* @param tag Name of the tag.
* @return `true` if found.
*/
[[nodiscard]] bool HasTag(Name tag) const noexcept
{
return tags_.contains(tag);
}
/**
* Set root component of this actor. Root component represents this actor's transform.
* @param new_root New root component. It can be null or MUST be owned by this actor.
*/
void SetRootComponent(SceneComponent* new_root) noexcept;
[[nodiscard]] SceneComponent* GetRootComponent() const noexcept
{
return root_;
}
[[nodiscard]] bool IsPendingKill() const noexcept
{
return pending_kill_;
}
/**
* Set actor's lifespan. Default is 0 (infinite). Timer is updated when called.
* @param in_seconds New lifespan in seconds. <=0 means infinite.
*/
void SetLifespan(Float in_seconds);
[[nodiscard]] Float GetLifespan() const noexcept;
[[nodiscard]] Float GetInitialLifespan() const noexcept
{
return init_lifespan_;
}
void SetPos(const Vec3& pos) const noexcept;
void SetRot(const Quat& rot) const noexcept;
void SetScale(const Vec3& scale) const noexcept;
void SetTrsf(const Transform& trsf) const noexcept;
[[nodiscard]] const Vec3& GetPos() const noexcept;
[[nodiscard]] const Quat& GetRot() const noexcept;
[[nodiscard]] const Vec3& GetScale() const noexcept;
[[nodiscard]] const Transform& GetTrsf() const noexcept;
[[nodiscard]] UVec3 GetForward() const noexcept;
[[nodiscard]] UVec3 GetRight() const noexcept;
[[nodiscard]] UVec3 GetUp() const noexcept;
[[nodiscard]] bool HasBegunPlay() const noexcept
{
return begun_play_;
}
void SetOwner(WeakPtr<AActor> new_owner);
[[nodiscard]] auto& GetOwner() const noexcept
{
return owner_;
}
[[nodiscard]] World& GetWorld() const noexcept
{
assert(world_);
return *world_;
}
[[nodiscard]] Engine& GetEngine() const noexcept;
/**
* If false, the actor will not being updated. `true` by default.
* Components are not affected by this property.
*/
bool update_enabled = true;
/**
* @brief If true, invoking Destroy() will not delete the actor.
*/
bool immortal = false;
protected:
virtual void OnBeginPlay()
{
}
virtual void OnEndPlay()
{
}
virtual void OnUpdate([[maybe_unused]] Float delta_seconds)
{
}
virtual void OnSetOwner()
{
}
private:
friend World;
void BeginPlay();
void EndPlay();
void Update(Float delta_seconds);
void RegisterComponent(SharedRef<ActorComponent>&& comp);
World* world_ = nullptr;
SceneComponent* root_ = nullptr;
WeakPtr<AActor> owner_;
std::vector<SharedRef<ActorComponent>> comps_;
std::unordered_set<Name> tags_;
TimerHandle lifespan_timer_;
Float init_lifespan_ = 0;
bool pending_kill_ = false;
bool begun_play_ = false;
};
} // namespace engine
} // namespace oeng
| 22.95288 | 90 | 0.631843 | [
"object",
"vector",
"transform"
] |
990b703a981e143664eaf24678e580d5d0d7c8ea | 29,948 | cpp | C++ | release/src/SearchResultSet.cpp | adamfowleruk/mlcplusplus | bd8b47b8e92c7f66a22ecfe98353f3e8a621802d | [
"Apache-2.0"
] | 4 | 2016-04-21T06:27:40.000Z | 2017-01-20T12:10:54.000Z | release/src/SearchResultSet.cpp | marklogic/mlcplusplus | bd8b47b8e92c7f66a22ecfe98353f3e8a621802d | [
"Apache-2.0"
] | 239 | 2015-11-26T23:10:33.000Z | 2017-01-03T23:48:23.000Z | release/src/SearchResultSet.cpp | marklogic-community/mlcplusplus | bd8b47b8e92c7f66a22ecfe98353f3e8a621802d | [
"Apache-2.0"
] | 3 | 2017-11-01T15:52:51.000Z | 2021-12-02T05:22:49.000Z | /*
* SearchResultSet.cpp
*
* Created on: 25 May 2016
* Author: adamfowler
*/
#include "mlclient/SearchResultSet.hpp"
#include "mlclient/SearchResult.hpp"
#include "mlclient/Connection.hpp"
#include "mlclient/SearchDescription.hpp"
#include "mlclient/Response.hpp"
#include "mlclient/NoCredentialsException.hpp"
#include "mlclient/utilities/CppRestJsonDocumentContent.hpp"
#include "mlclient/utilities/PugiXmlHelper.hpp"
#include "mlclient/utilities/DocumentHelper.hpp"
#include "mlclient/logging.hpp"
// We can use the following, because cpprest is an internal API dependency
#include "mlclient/utilities/CppRestJsonHelper.hpp"
#include <cpprest/json.h>
#include <string>
namespace mlclient {
class SearchResultSet::Impl {
public:
Impl(SearchResultSet* set,IConnection* conn,SearchDescription* desc) : mConn(conn), mInitialDescription(desc),
mResults(), mFetchException(), mIter(new SearchResultSetIterator(set)), mCachedEnd(nullptr), start(0),
pageLength(0), total(0),totalTime(""), queryResolutionTime(""),snippetResolutionTime(""),m_maxResults(0), lastFetched(-1),
fetchTask(nullptr) /*, fetchMtx(), resultsMtx()*/ {
//TIMED_FUNC(SearchResultSet_Impl_constructor);
//LOG(DEBUG) << "In SearchResultSet::Impl ctor";
//LOG(DEBUG) << "mInitialDescription: " << mInitialDescription->getPayload()->getContent();
}
void incrementIter(web::json::array::const_iterator iter) {
//TIMED_FUNC(SearchResultSet_Impl_incrementIter);
++iter;
}
bool iterCompare(web::json::array::const_iterator& iter,const web::json::array::const_iterator& jsonArrayIterEnd) {
//TIMED_FUNC(SearchResultSet_Impl_iterCompare);
return (iter != jsonArrayIterEnd);
}
bool handleFetchResults(Response * resp) {
//TIMED_FUNC(SearchResultSet_Impl_handleFetchResults);
//LOG(DEBUG) << "SearchResultSet::handleFetchResults Response value: " << resp->getContent();
// TODO handle request errors
//const web::json::value value(utilities::CppRestJsonHelper::fromResponse(*resp));
ITextDocumentContent* respDoc = (ITextDocumentContent*)mlclient::utilities::DocumentHelper::contentFromResponse(*resp);
IDocumentNavigator* nav = respDoc->navigate(true); // look below first element, if response is XML
//std::unique_lock<std::mutex> lck (resultsMtx,std::defer_lock);
{
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processMetrics()");
// extract top level summary information for the result set
IDocumentNode* snNode = nav->at("snippet-format");
if (nullptr == snNode) {
LOG(DEBUG) << "WARNING: snippet-format not found in results";
snippetFormat = "custom"; // should never happen unless snippeting is disabled
} else {
snippetFormat = snNode->asString();
}
LOG(DEBUG) << "Snippet format: " << snippetFormat;
total = nav->at("total")->asInteger();
if (0 == m_maxResults) {
//lck.lock();
mResults.reserve(total);
//lck.unlock();
} else {
//lck.lock();
mResults.reserve(m_maxResults);
//lck.unlock();
}
pageLength = nav->at("page-length")->asInteger();
start = nav->at("start")->asInteger();
// extract metrics, if they exist
// TODO better way to check for response metrics being present, without exception throwing
try {
IDocumentNode* metrics = nav->at("search:metrics");
queryResolutionTime = metrics->at("search:query-resolution-time")->asString();
snippetResolutionTime = metrics->at("search:snippet-resolution-time")->asString();
totalTime = metrics->at("search:total-time")->asString();
//CLOG(INFO, "performance") << "Executed [marklogic::rest::search::queryResolutionTime()] in [" << queryResolutionTime.substr(2,queryResolutionTime.length() - 3) << " ms]";
//CLOG(INFO, "performance") << "Executed [marklogic::rest::search::snippetResolutionTime()] in [" << snippetResolutionTime.substr(2,snippetResolutionTime.length() - 3) << " ms]";
//CLOG(INFO, "performance") << "Executed [marklogic::rest::search::totalTime()] in [" << totalTime.substr(2,totalTime.length() - 3) << " ms]";
} catch (std::exception& me) {
// no metrics element - possible due to search options
// silently fail - not a huge issue
// TODO flag this to support hasMetrics()
//LOG(DEBUG) << "SearchResultSet::handleFetchResults COULD NOT PARSE RESPONSE METRICS!!!" << me.what();
}
} // end timed scope for metrics
LOG(DEBUG) << "Extracted metrics";
// TODO preallocate total results (or limit, if set and lower) in mImpl->mResults vector - speeds up append operations
//SearchResult::DETAIL detail(SearchResult::DETAIL::NONE);
static std::string raw("raw"); // always the same
static std::string custom("custom"); // always the same
//std::string ct;
{
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processResultSet()");
bool isRaw = (raw == snippetFormat);
bool isCustom = (custom == snippetFormat);
// take the response, and parse it
// NOT NEEDED const web::json::value& resv = value.at(U("results"));
//const web::json::array res(value.at(U("results")).as_array());
bool hasResults = nav->has("search:result");
IDocumentNode* res = nullptr;
if (hasResults) {
res = nav->at("search:result"); // this fails if it doesn't exist
} else {
//res = res->asArray();
if (!hasResults || nullptr == res) {
hasResults = nav->has("search:results");
if (hasResults) {
res = nav->at("search:results");
} else {
if (!hasResults || nullptr != res) {
//res = res->asArray();
// TODO safely fail - no search results in search response (may have values, etc. instead)
LOG(DEBUG) << "WARNING: No search:result or search:results element in result JSON from REST API";
}
} // end second has results
}
} // end if has results
//{
// TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::asArray()");
// const web::json::array resCount = value.at(U("results")).as_array(); // TODO remove once counted in PERF logger
//}
//LOG(DEBUG) << "SearchResultSet::handleFetchResults We have a results JSON array";
//web::json::array::const_iterator iter(res.begin());
//const web::json::array::const_iterator jsonArrayIterEnd(res.end()); // see if a single call saves us time... nope
// TODO check if res is nullptr (i.e. return-results is false in search options)
LOG(DEBUG) << "Is result set empty?: " << (nullptr == res);
if (nullptr != res) {
int arrayLength = res->size();
LOG(DEBUG) << "Search result array length: " << arrayLength;
//mlclient::IDocumentContent* ct;
std::shared_ptr<IDocumentNode> ctValPtr;
SearchResult::Detail detail;
std::string mimeType;
Format format;
//web::json::object row = web::json::value::object().as_object();
IDocumentNode* row;
{
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processResultSetLoopOnly()");
//for (; iter != jsonArrayIterEnd;++iter) {
for (int i = 0;i < arrayLength;i++) {
{
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processRow()");
//auto& rowdata = *iter;
//row = iter->as_object();
if (res->isArray()) {
row = res->at(i);
} else {
row = res; // single result in response!
}
{
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processRowObject()");
//LOG(DEBUG) << "Row: " << iter->as_string();
//const web::json::object& row = iter.as_object();
detail = SearchResult::Detail::NONE;
mimeType = "";
format = Format::JSON;
//web::json::value ctVal;
//IDocumentNode* ctVal = nullptr;
//ct = "";
LOG(DEBUG) << "Processing search results";
// if snippet-format = raw
if (isRaw) {
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processContent()");
if (row->has("search:content")) {
try {
ctValPtr.reset(row->at("search:content")->asObject()); // at is rvalue, moved to lvalue by json's move contructor
LOG(DEBUG) << "SearchResultSet::handleFetchResults Got content";
} catch (std::exception& e) {
LOG(DEBUG) << "SearchResultSet::handleFetchResults Row does not have content... trying snippet..." << e.what();
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processContentEXCEPTION()");
// element doesn't exist - no result content, or has a snippet
} // end content catch
} else {
// no content element, just use entire element
LOG(DEBUG) << "SearchResultSet::handleFetchResults No content node but raw, so entire content is the document";
ctValPtr.reset(row);
}
} else if (isCustom) {
LOG(DEBUG) << "Custom snippet format result";
// Assume the custom snippet information is within the <snippet> element in the search response
try {
IDocumentNode* snippet = row->at("search:snippet");
// If search result format type is XML, but content is JSON, convert the search snippet to the right doc type
std::string docFormat = row->at("format")->asString();
if ("json" == docFormat) {
// get content of snippet as string
std::string json = snippet->asString();
// parse as JSON document, and set pointer accordingly
web::json::value val = mlclient::utilities::CppRestJsonHelper::fromString(json);
IDocumentContent* jsonDoc = mlclient::utilities::CppRestJsonHelper::toDocument(val);
ctValPtr.reset(((ITextDocumentContent*)jsonDoc)->navigate(false)->firstChild()); // TODO verify this is correct
} else {
//IDocumentNode* snippetObject = snippet->asObject();
//ctValPtr.reset(snippetObject->at(snippetObject->keys()[0]));
ctValPtr.reset(snippet->asObject());
}
detail = SearchResult::Detail::SNIPPETS;
} catch (std::exception& ex) {
// no snippet element, must be some sort of content...
detail = SearchResult::Detail::CONTENT;
LOG(DEBUG) << "SearchResultSet::handleFetchResults Result has no snippet element" << ex.what();
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processMatchesEXCEPTION()");
}
} else {
LOG(DEBUG) << "Fetching search result content from matches element";
try {
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processMatches()");
ctValPtr.reset(row->at("search:matches")->asObject());
/*
mimeType = utility::conversions::to_utf8string(row.at(U("mimetype")).as_string());
std::string formatStr = utility::conversions::to_utf8string(row.at(U("format")).as_string());
//LOG(DEBUG) << "SearchResultSet::handleFetchResults Got snippet content" << ct;
if ("json" == formatStr) {
format = Format::JSON;
} else if ("xml" == formatStr) {
format = Format::XML;
} else if ("binary" == formatStr) {
format = Format::BINARY;
} else if ("text" == formatStr) {
format = Format::TEXT;
} else {
format = Format::NONE;
}
*/
/*
ct = new mlclient::utilities::CppRestJsonDocumentContent();
ct->setMimeType(IDocumentContent::MIME_JSON);
ct->setContent(ctVal);
*/
//ct = divineDocumentContent(formatStr,mimeType,ctVal);
//ct = utility::conversions::to_utf8string(ctVal.as_string());
detail = SearchResult::Detail::SNIPPETS;
} catch (std::exception& ex) {
// no snippet element, must be some sort of content...
detail = SearchResult::Detail::CONTENT;
LOG(DEBUG) << "SearchResultSet::handleFetchResults Result has no matches element" << ex.what();
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::processMatchesEXCEPTION()");
}
}
mimeType = row->at("mimetype")->asString();
//LOG(DEBUG) << "SearchResultSet::handleFetchResults Got mimetype";
std::string formatStr = row->at("format")->asString();
if ("json" == formatStr) {
format = Format::JSON;
} else if ("xml" == formatStr) {
format = Format::XML;
} else if ("binary" == formatStr) {
format = Format::BINARY;
} else if ("text" == formatStr) {
format = Format::TEXT;
} else {
format = Format::NONE;
}
//LOG(DEBUG) << "SearchResultSet::handleFetchResults Got format";
//LOG(DEBUG) << "SearchResultSet::handleFetchResults Row content: " << ct;
//ct = divineDocumentContent(formatStr,mimeType,ctVal);
LOG(DEBUG) << "Search results ctVal is null?: " << (nullptr == ctValPtr.get());
// TODO handle empty result or no search metrics in the below - at the moment they could throw!!!
{
//TIMED_SCOPE(SearchResultSet_Impl_handleFetchResult, "mlclient::SearchResultSet::Impl::handleFetchResult::appendToVector()");
//SearchResult sr(row.at(U("index")).as_integer(), utility::conversions::to_utf8string(row.at(U("uri")).as_string()),
//utility::conversions::to_utf8string(row.at(U("path")).as_string()),row.at(U("score")).as_integer(),
//row.at(U("confidence")).as_double(),row.at(U("fitness")).as_double(),detail,ct,mimeType,format );
//lck.lock();
mResults.push_back(
new SearchResult(
row->at("index")->asInteger(),
row->at("uri")->asString(),
row->at("path")->asString(),
row->at("score")->asInteger(),
row->at("confidence")->asDouble(),
row->at("fitness")->asDouble(),
detail,ctValPtr,mimeType,format
)
);
lastFetched = mResults.size() - 1;
//lck.unlock();
} // end timed scope
}
}
} // end loop
} // end timed scope loop only
} else {
LOG(DEBUG) << "Results from REST API does not contain a search:result element or results property";
} // end res is null guard if
} // end process result set scope
return true;
};
/*
ITextDocumentContent* divineDocumentContent(const std::string& format,const std::string& mimeType,IDocumentNode* ctVal) {
ITextDocumentContent* ct;
if ("xml" == format) {
// XML
ct = mlclient::utilities::PugiXmlHelper::toDocument(utility::conversions::to_utf8string(ctVal.as_string()));
} else if ("json" == format) {
// JSON
ct = new mlclient::utilities::CppRestJsonDocumentContent();
((mlclient::utilities::CppRestJsonDocumentContent*)ct)->setContent(ctVal); // passes reference to function in cpprestjsondocumentcontent
} else if ("text" == format) {
// TEXT
ct = new GenericTextDocumentContent;
((GenericTextDocumentContent*)ct)->setContent(utility::conversions::to_utf8string(ctVal.as_string()));
} else if ("binary" == format) {
// BINARY
//LOG(DEBUG) << "WARNING: Binary document content not yet supported!!!";
ct = new GenericTextDocumentContent;
((GenericTextDocumentContent*)ct)->setContent("Binary support has not yet been added to SearchResultSet.cpp");
}
ct->setMimeType(mimeType); // don't override the one the server tells us - may be an XML format (E.g. GML), but not application/xml.
return ct;
}
*/
bool fetchInitial() {
//LOG(DEBUG) << "In fetchInitial";
//LOG(DEBUG) << "mInitialDescription: " << mInitialDescription->getPayload()->getContent();
// make this async
Impl& mImpl = (*this);
//std::unique_lock<std::mutex> lck (fetchMtx,std::defer_lock);
//lck.lock();
fetchTask = new pplx::task<void>([&mImpl] () {
//LOG(DEBUG) << "Began initial fetch task...";
try {
// perform the request to search in the connection
if (0 != mImpl.m_maxResults && mImpl.m_maxResults < mImpl.start + mImpl.pageLength - 1) { // E.g. Page 2, 11 results => 11 < 11 + 10 - 1 => 11 < 20 (i.e. max result requires limiting this page's length)
mImpl.mInitialDescription->setPageLength(mImpl.m_maxResults - mImpl.start + 1); // E.g. Page 2, 11 results => 11 - 11 + 1 = 1 results max on page 2
}
Response* resp = mImpl.mConn->search(*mImpl.mInitialDescription);
bool success = mImpl.handleFetchResults(resp);
LOG(DEBUG) << "Initial fetch task a success? : " << success;
delete(resp); // TODO ensure this does not invalidate any of our variables in search result set or searchresult instances
//return success;
} catch (std::exception& ref) {
mImpl.mFetchException = ref;
//LOG(DEBUG) << "Exception in initial fetch task";
//return false;
}
//LOG(DEBUG) << "End initial fetch task";
});
// BLOCK for first result set to ensure all variables for the result set (E.g. total) are set up before next function calls
// No way to avoid this blocking really.
fetchTask->wait();
//lck.unlock();
return true;
};
// Returning false means no fetchTask is running or created, return true means we can safely call wait()
bool fetchNext() {
//TIMED_FUNC(SearchResultSet_Impl_fetchNext);
//LOG(DEBUG) << "In fetchNext";
// TODO check if we need to wait for the last thread
if (nullptr == fetchTask) {
//LOG(DEBUG) << " Returning: fetchTask is null";
return false;
}
if (!fetchTask->is_done()) {
//LOG(DEBUG) << " Returning: fetchTask is still in progress";
return true; // rely on caller in iterator checking and calling wait() on mImpl;
}
//LOG(DEBUG) << "Previous fetch complete";
// lastfetched is 0 based - E.g. 0-499
// m_maxResults is 1 based - E.g. 1-500 - COULD BE 0 IF NOT SET!
if ((0 != m_maxResults && lastFetched >= m_maxResults - 1) || (lastFetched >= total - 1)) {
// No need to fetch any more
//LOG(DEBUG) << "lastFetched has reached maxResults - not fetching";
return false;
}
//LOG(DEBUG) << "Creating new fetch task...";
//std::unique_lock<std::mutex> lck (fetchMtx,std::defer_lock);
//lck.lock();
// TODO make this async
Impl& mImpl(*this);
fetchTask = new pplx::task<void>([&mImpl] () {
//LOG(DEBUG) << "Started another fetchTask";
// private method - called internally only
// use start and pageLength to determine next start value
// if total <= start + pageLenth - 1, then we are already at the end! So don't fetch.
//LOG(DEBUG) << "In fetchNext()";
if (mImpl.total > mImpl.start + mImpl.pageLength - 1) {
//LOG(DEBUG) << "Fetching next page...";
// fetch more results
// TODO support point in time query, so totals are always consistent
SearchDescription newDescription = *(mImpl.mInitialDescription); // force copy
//LOG(DEBUG) << " Got new description";
// override settings in search options for start value
newDescription.setStart(mImpl.start + mImpl.pageLength);
if (0 != mImpl.m_maxResults && mImpl.m_maxResults < mImpl.start + mImpl.pageLength - 1) { // E.g. Page 2, 11 results => 11 < 11 + 10 - 1 => 11 < 20 (i.e. max result requires limiting this page's length)
newDescription.setPageLength(mImpl.m_maxResults - mImpl.start + 1); // E.g. Page 2, 11 results => 11 - 11 + 1 = 1 results max on page 2
}
//LOG(DEBUG) << " set start on new description";
//LOG(DEBUG) << "Validating search payload: " << newDescription.getPayload()->getContent();
//LOG(DEBUG) << " mConn is nullptr?: " << (nullptr == mImpl.mConn);
//LOG(DEBUG) << " mConn address: " << mImpl.mConn;
Response* resp = mImpl.mConn->search(newDescription);
//LOG(DEBUG) << " Completed search... calling handleFetchResults()";
mImpl.handleFetchResults(resp);
// TODO delete resp???
} else {
//LOG(DEBUG) << "No more pages to fetch";
;
}
//return true;
//LOG(DEBUG) << "Ended another fetchTask";
}); // end task block
//lck.unlock();
return true;
};
SearchResult* getResult(long position) {
//std::unique_lock<std::mutex> lck (resultsMtx,std::defer_lock);
//lck.lock();
SearchResult* res = mResults.at(position);
//lck.unlock();
return res;
}
const long getLastFetched() const {
return lastFetched;
};
void wait() {
//LOG(DEBUG) << "In wait()";
//std::unique_lock<std::mutex> lck (fetchMtx,std::defer_lock);
//lck.lock();
if (fetchTask->is_done()) {
//LOG(DEBUG) << " Returning: Task is complete";
return;
}
//LOG(DEBUG) << " Waiting for completion";
fetchTask->wait();
//lck.unlock();
};
IConnection* mConn;
SearchDescription* mInitialDescription;
std::vector<SearchResult*> mResults;
std::exception mFetchException;
SearchResultSetIterator* mIter;
SearchResultSetIterator* mCachedEnd;
long start;
long total;
long pageLength;
std::string snippetFormat;
std::string queryResolutionTime; // W3C Duration String
std::string snippetResolutionTime; // W3C Duration String
std::string totalTime; // W3C Duration String
// count - E.g. 500
long m_maxResults; // max number of results to return across all requests (total)
// 0 based - i.e. for 500 results, at start it would be -1, at end it would 499
long lastFetched;
pplx::task<void>* fetchTask;
//std::mutex fetchMtx;
//std::mutex resultsMtx;
};
SearchResultSet::SearchResultSet(IConnection* conn,SearchDescription* desc) : mImpl(new Impl(this,conn,desc)) {
//TIMED_FUNC(SearchResultSet_SearchResultSet);
//LOG(DEBUG) << "SearchResultSet ctor";
//LOG(DEBUG) << "mInitialDescription: " << desc->getPayload()->getContent();
//mImpl = new SearchResultSet::Impl(this,conn,desc);
}
bool SearchResultSet::fetch() {
//TIMED_FUNC(SearchResultSet_fetch);
//LOG(DEBUG) << "SearchResultSet::fetch";
return mImpl->fetchInitial();
}
std::exception SearchResultSet::getFetchException() {
//TIMED_FUNC(SearchResultSet_getFetchException);
return mImpl->mFetchException;
}
void SearchResultSet::setMaxResults(long maxResults) {
//TIMED_FUNC(SearchResultSet_setMaxResults);
mImpl->m_maxResults = maxResults;
// preallocate this size in mImpl->mResults vector (done in initial fetch function, NOT here)
}
SearchResultSetIterator* SearchResultSet::begin() const {
//TIMED_FUNC(SearchResultSet_begin);
//return mImpl->mResults.begin();
SearchResultSetIterator* beginIter = mImpl->mIter->begin();
mImpl->mCachedEnd = mImpl->mIter->end(); // cache end iterator to prevent poorly written code from instantiating many iterator instances
return beginIter;
}
SearchResultSetIterator* SearchResultSet::end() const {
//TIMED_FUNC(SearchResultSet_end);
return mImpl->mCachedEnd;
}
const long SearchResultSet::getStart() {
//TIMED_FUNC(SearchResultSet_getStart);
return mImpl->start;
}
const long SearchResultSet::getTotal() {
//TIMED_FUNC(SearchResultSet_getTotal);
if (0 != mImpl->m_maxResults) { // may be returning less than is in the database
if (mImpl->m_maxResults < mImpl->total) {
return mImpl->m_maxResults;
}
}
return mImpl->total;
}
const long SearchResultSet::getPageLength() {
return mImpl->pageLength;
}
const std::string& SearchResultSet::getSnippetFormat() const {
return mImpl->snippetFormat;
}
const std::string& SearchResultSet::getQueryResolutionTime() const {
return mImpl->queryResolutionTime;
}
const std::string& SearchResultSet::getSnippetResolutionTime() const {
return mImpl->snippetResolutionTime;
}
const std::string& SearchResultSet::getTotalTime() const {
return mImpl->totalTime;
}
const long SearchResultSet::getPageCount() const {
//TIMED_FUNC(SearchResultSet_getPageCount);
// TODO validate type safety of the below
return (long)std::ceil(((double)mImpl->total) / ((double)mImpl->pageLength));
}
SearchResultSetIterator::SearchResultSetIterator() : mResultSet(nullptr), position(1) {
//TIMED_FUNC(SearchResultSetIterator_defaultConstructor);
}
SearchResultSetIterator::SearchResultSetIterator(SearchResultSet* set) : mResultSet(set), position(1) {
//TIMED_FUNC(SearchResultSetIterator_resultSetConstructor);
}
SearchResultSetIterator::SearchResultSetIterator(SearchResultSet* set, long pos) : mResultSet(set), position(pos) {
//TIMED_FUNC(SearchResultSetIterator_resultSetPositionConstructor);
}
SearchResultSetIterator* SearchResultSetIterator::begin() {
//TIMED_FUNC(SearchResultSetIterator_begin);
long st = 1; // assume at least one result
if (mResultSet->getTotal() == 0) {
st = 0; // stops vector overflow where end = 0 (no results) and start = 1 (because of being 1 based in MarkLogic Server)
}
SearchResultSetIterator* iter = new SearchResultSetIterator(mResultSet, st);
return iter;
}
SearchResultSetIterator* SearchResultSetIterator::end() {
//TIMED_FUNC(SearchResultSetIterator_end);
long st = mResultSet->getTotal();
if (0 == st) {
//st = 0; // stops vector overflow where end = 0 (no results) and start = 1 (because of being 1 based in MarkLogic Server)
} else {
st++; // past end of vector, if at least one result
}
SearchResultSetIterator* iter = new SearchResultSetIterator(mResultSet, st); // ensure end is PAST last result
return iter;
}
bool SearchResultSetIterator::operator==(const SearchResultSetIterator& other) {
//TIMED_FUNC(SearchResultSetIterator_operatorEquals);
//LOG(DEBUG) << "operator== position: " << position << ", other.position: " << other.position;
return position == other.position;
}
bool SearchResultSetIterator::operator!=(const SearchResultSetIterator& other) {
//TIMED_FUNC(SearchResultSetIterator_operatorInequals);
//LOG(DEBUG) << "operator!= position: " << position << ", other.position: " << other.position;
return position != other.position;
}
void SearchResultSetIterator::operator++() {
//TIMED_FUNC(SearchResultSetIterator_operatorPlusPlus);
// see if we're at the very end. If so, do nothing
// check to see if we're at the end of the current result set, and need to fetch more
// otherwise, just increment position
//LOG(DEBUG) << " incrementing, currently: " << position;
long lastFetched = mResultSet->mImpl->getLastFetched();
if (-1 == lastFetched) {
// wait for initial fetch
//LOG(DEBUG) << "No initial fetch happened (IMPOSSIBLE), waiting...";
mResultSet->mImpl->wait();
//LOG(DEBUG) << "Awake!";
}
if (position >= mResultSet->getTotal()) {
// at end. No nothing
//LOG(DEBUG) << "in final position of result set (total)";
} else {
// check if we've just started the next result set
if (position > lastFetched) { // this is not lastFetched + 1 as we haven't incremented position yet!!! That gets done at the END of the function
// need next result set NOW
//LOG(DEBUG) << "At end of result set - calling fetchNext...";
if (mResultSet->mImpl->fetchNext()) {
mResultSet->mImpl->wait();
}
}
if (position > lastFetched + 1 - mResultSet->mImpl->pageLength) {
// within 1 page of the end - go fetch more results
//LOG(DEBUG) << "On last page of result set - calling fetchNext (lastFetched currently: " << lastFetched << ", position currently: " << position << ", maxResults currently: " << mResultSet->mImpl->m_maxResults << ")...";
mResultSet->mImpl->fetchNext();
}
/*
// OLD fetch code - fetched and blocked at end of result set
if ((mResultSet->getStart() + mResultSet->getPageLength() - 1) == position) {
//LOG(DEBUG) << " fetching next set of results";
// fetch next page
bool ok = mResultSet->mImpl->fetchNext();
// TODO do something if ok == false
}
//LOG(DEBUG) << "incrementing by 1";
*/
}
++position;
// sanity check position, and set to end if beyond it - ODBC layer in particular does this a lot.
if (position > mResultSet->mImpl->total + 1) {
position = mResultSet->mImpl->total + 1;
}
//LOG(DEBUG) << " position now: " << position;
}
const SearchResult SearchResultSetIterator::operator*() {
//TIMED_FUNC(SearchResultSetIterator_operatorDereference);
//try {
return *(mResultSet->mImpl->getResult(position - 1)); // MarkLogic Server is 1 based, not 0
/*} catch (std::exception& e) {
std::ostringstream os;
os << "Exception trying to read index: " << (position - 1);
std::cout << os.str() << std::endl;
throw mlclient::NoCredentialsException(os.str().c_str());
}*/
}
SearchResultSetIterator SearchResultSetIterator::operator=(const SearchResultSetIterator& other) {
//TIMED_FUNC(SearchResultSetIterator_operatorAssignment);
mResultSet = other.mResultSet;
position = other.position;
return other;
}
const SearchResult& SearchResultSetIterator::first() const {
//TIMED_FUNC(SearchResultSetIterator_first);
return *(mResultSet->mImpl->getResult(position - 1)); // MarkLogic Server is 1 based, not 0
}
} // end namespace mlclient
| 39.096606 | 226 | 0.653099 | [
"object",
"vector"
] |
993f7cfacb9b0afa0f7875f8c72522a04178f56e | 4,708 | hpp | C++ | ql/experimental/math/randomsequencegenerator_multithreaded.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 4 | 2016-03-28T15:05:23.000Z | 2020-02-17T23:05:57.000Z | ql/experimental/math/randomsequencegenerator_multithreaded.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 1 | 2015-02-02T20:32:43.000Z | 2015-02-02T20:32:43.000Z | ql/experimental/math/randomsequencegenerator_multithreaded.hpp | pcaspers/quantlib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 10 | 2015-01-26T14:50:24.000Z | 2015-10-23T07:41:30.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2015 Peter Caspers
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file randomsequencegenerator_multithreaded
\brief Random sequence generator based on a pseudo-random number generator
(multithreaded)
*/
#ifndef quantlib_random_sequence_generator_multithreaded_hpp
#define quantlib_random_sequence_generator_multithreaded_hpp
#include <ql/methods/montecarlo/sample.hpp>
#include <ql/errors.hpp>
#include <vector>
namespace QuantLib {
//! Random sequence generator based on a pseudo-random number generator
//! (multithreaded)
/*! Random sequence generator based on a pseudo-random number
generator RNG_MT (multithreaded).
Class RNG_MT must implement the following interface:
\code
RNG_MT::sample_type RNG::next(int threadId) const;
\endcode
If a client of this class wants to use the nextInt32Sequence method,
class RNG must also implement
\code
unsigned long RNG_MT::nextInt32(int threadId) const;
\endcode
\warning do not use with low-discrepancy sequence generator.
*/
template <class RNG_MT> class RandomSequenceGeneratorMultiThreaded {
public:
typedef Sample<std::vector<Real> > sample_type;
static const Size maxNumberOfThreads = RNG_MT::maxNumberOfThreads;
RandomSequenceGeneratorMultiThreaded(Size dimensionality,
const RNG_MT &rng_mt)
: dimensionality_(dimensionality), rng_mt_(rng_mt),
sequence_(std::vector<sample_type>(
maxNumberOfThreads,
sample_type(std::vector<Real>(dimensionality), 1.0))),
int32Sequence_(std::vector<std::vector<BigNatural> >(
RNG_MT::maxNumberOfThreads,
std::vector<BigNatural>(dimensionality))) {
QL_REQUIRE(dimensionality > 0, "dimensionality must be greater than 0");
}
RandomSequenceGeneratorMultiThreaded(Size dimensionality,
BigNatural seed = 0)
: dimensionality_(dimensionality), rng_mt_(seed),
sequence_(std::vector<sample_type>(
maxNumberOfThreads,
sample_type(std::vector<Real>(dimensionality), 1.0))),
int32Sequence_(std::vector<std::vector<BigNatural> >(
RNG_MT::maxNumberOfThreads,
std::vector<BigNatural>(dimensionality))) {}
const sample_type &nextSequence(unsigned int threadId) const {
QL_REQUIRE(threadId < RNG_MT::maxNumberOfThreads,
"thread id (" << threadId << ") out of bounds [0..."
<< RNG_MT::maxNumberOfThreads - 1 << "]");
sequence_[threadId].weight = 1.0;
for (Size i = 0; i < dimensionality_; i++) {
typename RNG_MT::sample_type x(rng_mt_.next(threadId));
sequence_[threadId].value[i] = x.value;
sequence_[threadId].weight *= x.weight;
}
return sequence_[threadId];
}
std::vector<BigNatural> nextInt32Sequence(unsigned int threadId) const {
QL_REQUIRE(threadId < RNG_MT::maxNumberOfThreads,
"thread id (" << threadId << ") out of bounds [0..."
<< RNG_MT::maxNumberOfThreads - 1 << "]");
for (Size i = 0; i < dimensionality_; i++) {
int32Sequence_[threadId][i] = rng_mt_[threadId].nextInt32(threadId);
}
return int32Sequence_[threadId];
}
const sample_type &lastSequence(unsigned int threadId) const {
QL_REQUIRE(threadId < RNG_MT::maxNumberOfThreads,
"thread id (" << threadId << ") out of bounds [0..."
<< RNG_MT::maxNumberOfThreads - 1 << "]");
return sequence_[threadId];
}
Size dimension() const { return dimensionality_; }
private:
Size dimensionality_;
RNG_MT rng_mt_;
mutable std::vector<sample_type> sequence_;
mutable std::vector<std::vector<BigNatural> > int32Sequence_;
};
} // namespace QuantLib
#endif
| 39.233333 | 80 | 0.658879 | [
"vector"
] |
99456fafb52701335b13a6470c6ba3d179b52261 | 1,321 | cpp | C++ | problems/NQueen.cpp | rishinpandit09/data-structure-and-algorithms | 929e8dd3aa3c747c6cc20fc0248751f62d2884e5 | [
"Apache-2.0"
] | 53 | 2020-09-26T19:44:33.000Z | 2021-09-30T20:38:52.000Z | problems/NQueen.cpp | rishinpandit09/data-structure-and-algorithms | 929e8dd3aa3c747c6cc20fc0248751f62d2884e5 | [
"Apache-2.0"
] | 197 | 2020-08-25T18:13:56.000Z | 2021-06-19T07:26:19.000Z | problems/NQueen.cpp | rishinpandit09/data-structure-and-algorithms | 929e8dd3aa3c747c6cc20fc0248751f62d2884e5 | [
"Apache-2.0"
] | 204 | 2020-08-24T09:21:02.000Z | 2022-02-13T06:13:42.000Z | #include<bits/stdc++.h>
using namespace std;
bool check(long int a, long int b, vector<pair<long int, long int> >vp)
{
//cout<<"inside check"<<endl;
//cout<<"size of vp "<<vp.size()<<endl;
long int size = vp.size();
for(long int i=0;i<=size-1;i++)
{
//cout<<"inside loop"<<endl;
if(vp[i].first == a || vp[i].second == b)
return false;
if(abs(a-vp[i].first) == abs(b-vp[i].second))
return false;
}
return true;
}
bool recur_fill(long int a, long int b, vector<pair<long int, long int> >&vp, long int n)
{
if(b == n && a < n)
return false;
if(a == n)
return true;
bool result = check(a, b, vp);
if(result == true)
{
vp.push_back(make_pair(a, b));
bool val = recur_fill(a+1, 0, vp, n);
if(val == false)
{
pair<long int, long int>tmp = vp.back();
vp.pop_back();
return recur_fill(tmp.first, tmp.second+1, vp, n);
}
}
else
{
return recur_fill(a, b+1, vp, n);
}
return true;
}
int main()
{
vector<pair<long int, long int> >vp;
vp.clear();
long int n;
cin>>n;
recur_fill(0, 0, vp, n);
for(long int i=0;i<=vp.size()-1;i++)
{
long int c = vp[i].second;
for(long int j=0;j<c;j++)
{
cout<<" * ";
}
cout<<" Q ";
for(long int j=c+1;j<n;j++)
{
cout<<" * ";
}
cout<<endl;
}
} | 19.426471 | 89 | 0.535201 | [
"vector"
] |
994f301f73dba853e603c60002f2d9ea0a3d0ca8 | 1,123 | hpp | C++ | src/bemb_loc/my_headers.hpp | rodonn/nested-factorization | f55bef387a05d7b2a5ff5649209da2fcab1fea7c | [
"MIT"
] | null | null | null | src/bemb_loc/my_headers.hpp | rodonn/nested-factorization | f55bef387a05d7b2a5ff5649209da2fcab1fea7c | [
"MIT"
] | null | null | null | src/bemb_loc/my_headers.hpp | rodonn/nested-factorization | f55bef387a05d7b2a5ff5649209da2fcab1fea7c | [
"MIT"
] | null | null | null | #ifndef MY_HEADERS_HPP
#define MY_HEADERS_HPP
#include <math.h>
#include <climits>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <time.h>
#include <ctime>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
//#include <thread>
//#include <matrix.h>
//#include <gsl/gsl_math.h>
#include <gsl/gsl_sf_gamma.h>
#include <gsl/gsl_sf_psi.h>
//#include <gsl/gsl_matrix.h>
//#include <gsl/gsl_vector.h>
//#include <gsl/gsl_linalg.h>
//#include <gsl/gsl_blas.h>
#include <gsl/gsl_sf_exp.h>
#include <gsl/gsl_sf_log.h>
//#include "gsl/gsl_cdf.h"
#include "gsl/gsl_randist.h"
//#include "mex.h"
/*
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
//#include <curand.h>
//#include <curand_kernel.h>
#include <thrust/extrema.h>
#include <thrust/device_ptr.h>
#include <thrust/host_vector.h>
*/
using namespace std;
//#include "my_gsl_utilities.hpp"
//#include "vi_matrices.hpp"
//#include "vi_basic.hpp"
#endif
| 19.701754 | 37 | 0.71683 | [
"vector"
] |
99532e7db5ab7fe9d5e0deb5734290f23423709e | 2,368 | hpp | C++ | include/libp2p/protocol/gossip/impl/stream_writer.hpp | Alexey-N-Chernyshov/cpp-libp2p | 8b52253f9658560a4b1311b3ba327f02284a42a6 | [
"Apache-2.0",
"MIT"
] | null | null | null | include/libp2p/protocol/gossip/impl/stream_writer.hpp | Alexey-N-Chernyshov/cpp-libp2p | 8b52253f9658560a4b1311b3ba327f02284a42a6 | [
"Apache-2.0",
"MIT"
] | null | null | null | include/libp2p/protocol/gossip/impl/stream_writer.hpp | Alexey-N-Chernyshov/cpp-libp2p | 8b52253f9658560a4b1311b3ba327f02284a42a6 | [
"Apache-2.0",
"MIT"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef LIBP2P_PROTOCOL_GOSSIP_STREAM_WRITER_HPP
#define LIBP2P_PROTOCOL_GOSSIP_STREAM_WRITER_HPP
#include <deque>
#include <functional>
#include <libp2p/connection/stream.hpp>
#include <libp2p/protocol/common/scheduler.hpp>
#include <libp2p/protocol/gossip/impl/common.hpp>
namespace libp2p::protocol::gossip {
/// Writes RPC messages to connected stream
class StreamWriter : public std::enable_shared_from_this<StreamWriter> {
public:
/// Feedback interface from writer to its owning object (i.e. pub-sub
/// server)
using Feedback = std::function<void(const PeerContextPtr &from,
outcome::result<Success> event)>;
/// Ctor. N.B. StreamWriter instance cannot live longer than its creators
/// by design, so dependencies are stored by reference.
/// Also, peer is passed separately because it cannot be fetched from stream
/// once the stream is dead
StreamWriter(const Config &config, Scheduler &scheduler,
const Feedback &feedback,
std::shared_ptr<connection::Stream> stream,
PeerContextPtr peer);
/// Writes an outgoing message to stream, if there is serialization error
/// it will be posted in asynchronous manner
void write(outcome::result<SharedBuffer> serialization_res);
/// Closes writer and discards all outgoing messages
void close();
private:
void onMessageWritten(outcome::result<size_t> res);
void beginWrite(SharedBuffer buffer);
void endWrite();
void asyncPostError(Error error);
const Scheduler::Ticks timeout_;
Scheduler &scheduler_;
const Feedback &feedback_;
std::shared_ptr<connection::Stream> stream_;
PeerContextPtr peer_;
std::deque<SharedBuffer> pending_buffers_;
/// Number of bytes being awaited in active wrote operation
size_t writing_bytes_ = 0;
// TODO(artem): limit pending bytes and close slow streams that way
size_t pending_bytes_ = 0;
/// Dont send feedback or schedule writes anymore
bool closed_ = false;
/// Handle for current operation timeout guard
Scheduler::Handle timeout_handle_;
};
} // namespace libp2p::protocol::gossip
#endif // LIBP2P_PROTOCOL_GOSSIP_STREAM_WRITER_HPP
| 32.888889 | 80 | 0.707348 | [
"object"
] |
995c5862b47bd752c2958158f86763e0cf2b0586 | 4,719 | cpp | C++ | Example/CubeMap/CubeMap.cpp | Sqazine/SGL | 4897e66c135ca8703609978eed3b66c3aac6735a | [
"Apache-2.0"
] | null | null | null | Example/CubeMap/CubeMap.cpp | Sqazine/SGL | 4897e66c135ca8703609978eed3b66c3aac6735a | [
"Apache-2.0"
] | null | null | null | Example/CubeMap/CubeMap.cpp | Sqazine/SGL | 4897e66c135ca8703609978eed3b66c3aac6735a | [
"Apache-2.0"
] | 1 | 2021-09-22T07:57:46.000Z | 2021-09-22T07:57:46.000Z | #include <memory>
#include <vector>
#include <cassert>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include "Engine/Engine.h"
class TextureShaderProgram
: public SGL::GraphicsShaderProgram
{
public:
TextureShaderProgram() {}
~TextureShaderProgram() {}
uniform std::vector<SGL::Vector3f> positions;
uniform SGL::Matrix4f modelMatrix;
uniform SGL::Matrix4f viewMatrix;
uniform SGL::Matrix4f projectionMatrix;
SGL::Vector4f VertexShader(uint32_t vertexIndex, SGL::Varyings &varyings) override
{
varyings.CommitVector3fVarying("vTexcoord", positions[vertexIndex]);
//viewMatrix.elements[12]=viewMatrix.elements[13]=viewMatrix.elements[14]=0.0f;
return projectionMatrix * viewMatrix * SGL::Vector4f(positions[vertexIndex], 1.0f);
}
uniform SGL::TextureCube textureCube;
SGL::Vector4f FragmentShader(const SGL::Varyings &varyings) override
{
return textureCube.GetTexel(varyings.GetVector3fVarying("vTexcoord"));
}
};
class ExampleCube : public Application
{
public:
ExampleCube(const std::string &appName, const SGL::Vector2u32 &frameExtent) : Application(appName, frameExtent), cube(Mesh(MeshType::CUBE)) {}
~ExampleCube() {}
void Init() override
{
Application::Init();
m_InputSystem->GetMouse()->SetReleativeMode(true);
std::vector<std::string> filePaths;
filePaths.resize(6, ASSET_DIR);
filePaths[0].append("skybox/right.jpg");
filePaths[1].append("skybox/left.jpg");
filePaths[2].append("skybox/top.jpg");
filePaths[3].append("skybox/bottom.jpg");
filePaths[4].append("skybox/front.jpg");
filePaths[5].append("skybox/back.jpg");
int width, height, channel;
stbi_set_flip_vertically_on_load(true);
std::array<uint8_t *, 6> pixels;
for (size_t i = 0; i < 6; ++i)
{
pixels[i] = stbi_load(filePaths[i].c_str(), &width, &height, &channel, STBI_default);
assert(pixels[i] != nullptr);
}
SGL::TextureCubeCreateInfo textureCubeCreateInfo{};
if (channel == STBI_rgb)
textureCubeCreateInfo.channelMode = SGL::TextureChannelMode::RGB8;
else if (channel == STBI_rgb_alpha)
textureCubeCreateInfo.channelMode = SGL::TextureChannelMode::RGBA8;
textureCubeCreateInfo.width = width;
textureCubeCreateInfo.height = height;
textureCubeCreateInfo.wrapModeS = SGL::TextureWrapMode::CLAMP_TO_EDGE;
textureCubeCreateInfo.wrapModeT = SGL::TextureWrapMode::CLAMP_TO_EDGE;
textureCubeCreateInfo.data[0] = pixels[0];
textureCubeCreateInfo.data[1] = pixels[1];
textureCubeCreateInfo.data[2] = pixels[2];
textureCubeCreateInfo.data[3] = pixels[3];
textureCubeCreateInfo.data[4] = pixels[4];
textureCubeCreateInfo.data[5] = pixels[5];
auto textureCube = SGL::TextureCube(textureCubeCreateInfo);
fpCamera = std::make_shared<FPCamera>(SGL::Math::ToRadian(60), m_FrameExtent.x / m_FrameExtent.y, 0.1f, 1000.0f);
shader = std::make_shared<TextureShaderProgram>();
shader->positions = cube.GetPositions();
shader->textureCube = textureCube;
SGL::GraphicsPipelineCreateInfo info;
info.defaultBufferExtent = m_FrameExtent;
info.shaderProgram = shader.get();
info.renderType = SGL::RenderType::SOLID_TRIANGLE;
info.clearBufferType = SGL::BufferType::COLOR_BUFFER | SGL::BufferType::DEPTH_BUFFER;
info.clearColor = SGL::Vector4f(0.5f, 0.6f, 0.7f, 1.0f);
m_GraphicsPipeline = std::make_unique<SGL::GraphicsPipeline>(info);
}
void ProcessInput() override
{
Application::ProcessInput();
if (m_InputSystem->GetEventType() == SDL_QUIT || m_InputSystem->GetKeyboard()->GetKeyState(KEYCODE_ESCAPE) == BUTTON_STATE::PRESS)
m_Status = ApplicationStatus::EXIT;
fpCamera->ProcessInput(m_InputSystem);
}
void Update() override
{
Application::Update();
fpCamera->Update();
}
void Draw() override
{
Application::Draw();
shader->viewMatrix = fpCamera->GetViewMatrix();
shader->projectionMatrix = fpCamera->GetProjectionMatrix();
m_GraphicsPipeline->ClearBuffer();
m_GraphicsPipeline->DrawElements(0, cube.GetIndices());
}
private:
Mesh cube;
std::shared_ptr<FPCamera> fpCamera;
std::shared_ptr<TextureShaderProgram> shader;
};
#undef main
int main(int argc, char **argv)
{
std::unique_ptr<Application> app = std::make_unique<ExampleCube>("Example Cube", SGL::Vector2u32(800, 600));
app->Run();
return 0;
} | 35.216418 | 146 | 0.667938 | [
"mesh",
"vector"
] |
995f53a0eb3c101123c0503336646c8c75d0d9ba | 34,034 | cpp | C++ | Source/Falcor/Scene/Importers/PBRTImporter/Parser.cpp | gonsolo/Falcor | db27e6fa0efb1c04a51333c14ddfeac309995145 | [
"BSD-3-Clause"
] | null | null | null | Source/Falcor/Scene/Importers/PBRTImporter/Parser.cpp | gonsolo/Falcor | db27e6fa0efb1c04a51333c14ddfeac309995145 | [
"BSD-3-Clause"
] | null | null | null | Source/Falcor/Scene/Importers/PBRTImporter/Parser.cpp | gonsolo/Falcor | db27e6fa0efb1c04a51333c14ddfeac309995145 | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
# Copyright (c) 2015-22, 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.
**************************************************************************/
// This code is based on pbrt:
// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys.
// The pbrt source code is licensed under the Apache License, Version 2.0.
// SPDX: Apache-2.0
#include "stdafx.h"
#include "Parser.h"
#include "Helpers.h"
#include <charconv>
namespace Falcor
{
namespace pbrt
{
ParserTarget::~ParserTarget() {}
std::string toString(std::string_view sv)
{
return std::string(sv);
}
std::string Token::toString() const
{
return fmt::format("[ Token token: {} loc: {} ]", token, loc.toString());
}
static char decodeEscaped(int ch, const FileLoc& loc)
{
switch (ch)
{
case EOF:
throwError(loc, "Premature EOF after character escape '\\'");
case 'b':
return '\b';
case 'f':
return '\f';
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case '\\':
return '\\';
case '\'':
return '\'';
case '\"':
return '\"';
default:
throwError(loc, "Unexpected escaped character '%c'", ch);
}
return 0;
}
std::unique_ptr<Tokenizer> Tokenizer::createFromFile(const std::filesystem::path& path)
{
if (hasExtension(path, "gz"))
{
std::string str = decompressFile(path);
return std::make_unique<Tokenizer>(std::move(str), path);
}
else
{
std::string str = readFile(path);
return std::make_unique<Tokenizer>(std::move(str), path);
}
}
std::unique_ptr<Tokenizer> Tokenizer::createFromString(std::string str)
{
return std::make_unique<Tokenizer>(std::move(str), "<string>");
}
Tokenizer::Tokenizer(std::string str, const std::filesystem::path& path)
: mPath(path)
, mContents(std::move(str))
{
auto pFilename = std::make_unique<std::string>(path.string());
mLoc = FileLoc(*pFilename);
getFilenames().push_back(std::move(pFilename));
mPos = mContents.data();
mEnd = mPos + mContents.size();
if (isUTF16(mContents.data(), mContents.size())) throwError("File is encoded with UTF-16, which is not currently supported.");
}
bool Tokenizer::isUTF16(const void* ptr, size_t len) const
{
auto c = reinterpret_cast<const unsigned char*>(ptr);
// https://en.wikipedia.org/wiki/Byte_order_mark
return (len >= 2 && ((c[0] == 0xfe && c[1] == 0xff) || (c[0] == 0xff && c[1] == 0xfe)));
}
std::optional<Token> Tokenizer::next()
{
while (true)
{
const char* tokenStart = mPos;
FileLoc startLoc = mLoc;
int ch = getChar();
if (ch == EOF)
{
return {};
}
else if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\r')
{
// Skip.
}
else if (ch == '"')
{
// Scan to closing quote.
bool haveEscaped = false;
while ((ch = getChar()) != '"')
{
if (ch == EOF)
{
throwError(startLoc, "Premature EOF.");
}
else if (ch == '\n')
{
throwError(startLoc, "Unterminated string.");
}
else if (ch == '\\')
{
haveEscaped = true;
// Grab the next character.
if ((ch = getChar()) == EOF)
{
throwError(startLoc, "Premature EOF.");
}
}
}
if (!haveEscaped)
{
return Token({tokenStart, size_t(mPos - tokenStart)}, startLoc);
}
else
{
mEscaped.clear();
for (const char* p = tokenStart; p < mPos; ++p)
{
if (*p != '\\')
{
mEscaped.push_back(*p);
}
else
{
++p;
FALCOR_ASSERT(p < mPos);
mEscaped.push_back(decodeEscaped(*p, startLoc));
}
}
return Token({mEscaped.data(), mEscaped.size()}, startLoc);
}
}
else if (ch == '[' || ch == ']')
{
return Token({tokenStart, size_t(1)}, startLoc);
}
else if (ch == '#')
{
// Comment: scan to EOL (or EOF).
while ((ch = getChar()) != EOF)
{
if (ch == '\n' || ch == '\r')
{
ungetChar();
break;
}
}
return Token({tokenStart, size_t(mPos - tokenStart)}, startLoc);
}
else
{
// Regular statement or numeric token. Scan until we hit a space, opening quote, or bracket.
while ((ch = getChar()) != EOF)
{
if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\r' || ch == '"' || ch == '[' || ch == ']')
{
ungetChar();
break;
}
}
return Token({tokenStart, size_t(mPos - tokenStart)}, startLoc);
}
}
}
static int32_t parseInt(const Token& t)
{
auto begin = t.token.data();
auto end = t.token.data() + t.token.size();
// Skip '+' character, std::from_chars doesn't handle '+'.
if (*begin == '+') begin++;
int64_t value;
auto result = std::from_chars(begin, end, value);
if (result.ptr != end)
{
throwError(t.loc, "'{}': Expected a number.", t.token);
}
if (value < std::numeric_limits<int32_t>::lowest() || value > std::numeric_limits<int32_t>::max())
{
throwError(t.loc, "'{}': Numeric value cannot be represented as a 32-bit integer.", t.token);
}
return (int32_t)value;
}
static Float parseFloat(const Token& t)
{
// Fast path for a single digit.
if (t.token.size() == 1)
{
if (!(t.token[0] >= '0' && t.token[0] <= '9'))
{
throwError(t.loc, "'{}': Expected a number.", t.token);
}
return (Float)(t.token[0] - '0');
}
auto begin = t.token.data();
auto end = t.token.data() + t.token.size();
// Skip '+' character, std::from_chars doesn't handle '+'.
if (*begin == '+') begin++;
Float value;
auto result = std::from_chars(begin, end, value);
if (result.ptr != end)
{
throwError(t.loc, "'{}': Expected a number.", t.token);
}
return value;
}
inline bool isQuotedString(std::string_view str)
{
return str.size() >= 2 && str[0] == '"' && str.back() == '"';
}
static std::string_view dequoteString(const Token& t)
{
if (!isQuotedString(t.token)) throwError(t.loc, "'{}' is not a quoted string.");
std::string_view str = t.token;
str.remove_prefix(1);
str.remove_suffix(1);
return str;
}
constexpr uint32_t TokenOptional = 0;
constexpr uint32_t TokenRequired = 1;
template <typename Next, typename Unget>
static ParsedParameterVector parseParameters(Next nextToken, Unget ungetToken)
{
ParsedParameterVector parameterVector;
while (true)
{
auto t = nextToken(TokenOptional);
if (!t.has_value()) return parameterVector;
if (!isQuotedString(t->token))
{
ungetToken(*t);
return parameterVector;
}
ParsedParameter param(t->loc);
std::string_view decl = dequoteString(*t);
auto skipSpace = [&decl](std::string_view::const_iterator iter)
{
while (iter != decl.end() && (*iter == ' ' || *iter == '\t')) ++iter;
return iter;
};
// Skip to the next whitespace character (or the end of the string).
auto skipToSpace = [&decl](std::string_view::const_iterator iter)
{
while (iter != decl.end() && *iter != ' ' && *iter != '\t') ++iter;
return iter;
};
auto typeBegin = skipSpace(decl.begin());
if (typeBegin == decl.end()) throwError(t->loc, "Parameter '{}' doesn't have a type declaration.", decl);
// Find end of type declaration.
auto typeEnd = skipToSpace(typeBegin);
param.type.assign(typeBegin, typeEnd);
auto nameBegin = skipSpace(typeEnd);
if (nameBegin == decl.end()) throwError(t->loc, "Unable to find parameter name from '{}'.", decl);
auto nameEnd = skipToSpace(nameBegin);
param.name.assign(nameBegin, nameEnd);
enum ValType { Unknown, String, Bool, Float, Int } valType = Unknown;
if (param.type == "integer") valType = Int;
auto addVal = [&](const Token& t)
{
if (isQuotedString(t.token))
{
switch (valType) {
case Unknown:
valType = String;
break;
case String:
break;
case Float:
throwError(t.loc, "'{}': Expected floating-point value", t.token);
case Int:
throwError(t.loc, "'{}': Expected integer value", t.token);
case Bool:
throwError(t.loc, "'{}': Expected Boolean value", t.token);
}
param.addString(dequoteString(t));
}
else if (t.token[0] == 't' && t.token == "true")
{
switch (valType) {
case Unknown:
valType = Bool;
break;
case String:
throwError(t.loc, "'{}': Expected string value", t.token);
case Float:
throwError(t.loc, "'{}': Expected floating-point value", t.token);
case Int:
throwError(t.loc, "'{}': Expected integer value", t.token);
case Bool:
break;
}
param.addBool(true);
}
else if (t.token[0] == 'f' && t.token == "false")
{
switch (valType) {
case Unknown:
valType = Bool;
break;
case String:
throwError(t.loc, "'{}': Expected string value", t.token);
case Float:
throwError(t.loc, "'{}': Expected floating-point value", t.token);
case Int:
throwError(t.loc, "'{}': Expected integer value", t.token);
case Bool:
break;
}
param.addBool(false);
}
else
{
switch (valType) {
case Unknown:
valType = Float;
break;
case String:
throwError(t.loc, "'{}': Expected string value", t.token);
case Float:
break;
case Int:
break;
case Bool:
throwError(t.loc, "'{}': Expected Boolean value", t.token);
}
if (valType == Int) param.addInt(parseInt(t));
else param.addFloat(parseFloat(t));
}
};
Token val = *nextToken(TokenRequired);
if (val.token == "[")
{
while (true)
{
val = *nextToken(TokenRequired);
if (val.token == "]") break;
addVal(val);
}
}
else
{
addVal(val);
}
parameterVector.push_back(param);
}
return parameterVector;
}
void parse(ParserTarget& target, std::unique_ptr<Tokenizer> tokenizer)
{
static std::atomic<bool> warnedTransformBeginEndDeprecated{false};
logInfo("PBRTImporter: Started parsing '{}'.", tokenizer->getPath().string());
auto searchPath = tokenizer->getPath().parent_path();
std::vector<std::unique_ptr<Tokenizer>> fileStack;
fileStack.push_back(std::move(tokenizer));
std::optional<Token> ungetToken;
/** Helper function that handles the file stack, returning the next token from
the file until reaching EOF, at which point it switches to the next file (if any).
*/
std::function<std::optional<Token>(uint32_t flags)> nextToken;
nextToken = [&](uint32_t flags) -> std::optional<Token>
{
if (ungetToken.has_value()) return std::exchange(ungetToken, {});
if (fileStack.empty())
{
if ((flags & TokenRequired) != 0)
{
throwError("Premature end of file.");
}
return {};
}
std::optional<Token> tok = fileStack.back()->next();
if (!tok)
{
// We've reached EOF in the current file. Anything more to parse?
logInfo("PBRTImporter: Finished parsing '{}'.", fileStack.back()->getPath().string());
fileStack.pop_back();
return nextToken(flags);
}
else if (tok->token[0] == '#')
{
// Swallow comments.
return nextToken(flags);
}
else
{
// Regular token.
return tok;
}
};
auto unget = [&](Token t)
{
FALCOR_ASSERT(!ungetToken.has_value());
ungetToken = t;
};
/** Helper function for pbrt API entrypoints that take a single string
parameter and a ParameterVector (e.g. onShape()).
*/
auto basicParamListEntrypoint = [&](void (ParserTarget::*apiFunc)(const std::string&, ParsedParameterVector, FileLoc), FileLoc loc)
{
Token t = *nextToken(TokenRequired);
std::string_view dequoted = dequoteString(t);
std::string n = toString(dequoted);
ParsedParameterVector parameterVector = parseParameters(nextToken, unget);
(target.*apiFunc)(n, std::move(parameterVector), loc);
};
auto syntaxError = [&](const Token& t)
{
if (t.token == "WorldEnd")
{
throwError(t.loc, "Unknown directive: {}.\nThis looks like old (pre pbrt-v4) scene format which is not supported.", t.token);
}
else
{
throwError(t.loc, "Unknown directive: {}", t.token);
}
};
std::optional<Token> tok;
while (true)
{
tok = nextToken(TokenOptional);
if (!tok.has_value()) break;
switch (tok->token[0])
{
case 'A':
if (tok->token == "AttributeBegin")
{
target.onAttributeBegin(tok->loc);
}
else if (tok->token == "AttributeEnd")
{
target.onAttributeEnd(tok->loc);
}
else if (tok->token == "Attribute")
{
basicParamListEntrypoint(&ParserTarget::onAttribute, tok->loc);
}
else if (tok->token == "ActiveTransform")
{
Token a = *nextToken(TokenRequired);
if (a.token == "All") target.onActiveTransformAll(tok->loc);
else if (a.token == "EndTime") target.onActiveTransformEndTime(tok->loc);
else if (a.token == "StartTime") target.onActiveTransformStartTime(tok->loc);
else syntaxError(*tok);
}
else if (tok->token == "AreaLightSource")
{
basicParamListEntrypoint(&ParserTarget::onAreaLightSource, tok->loc);
}
else if (tok->token == "Accelerator")
{
basicParamListEntrypoint(&ParserTarget::onAccelerator, tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'C':
if (tok->token == "ConcatTransform")
{
if (nextToken(TokenRequired)->token != "[") syntaxError(*tok);
Float m[16];
for (int i = 0; i < 16; ++i) m[i] = parseFloat(*nextToken(TokenRequired));
if (nextToken(TokenRequired)->token != "]") syntaxError(*tok);
target.onConcatTransform(m, tok->loc);
}
else if (tok->token == "CoordinateSystem")
{
std::string_view n = dequoteString(*nextToken(TokenRequired));
target.onCoordinateSystem(toString(n), tok->loc);
}
else if (tok->token == "CoordSysTransform")
{
std::string_view n = dequoteString(*nextToken(TokenRequired));
target.onCoordSysTransform(toString(n), tok->loc);
}
else if (tok->token == "ColorSpace")
{
std::string_view n = dequoteString(*nextToken(TokenRequired));
target.onColorSpace(toString(n), tok->loc);
}
else if (tok->token == "Camera")
{
basicParamListEntrypoint(&ParserTarget::onCamera, tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'F':
if (tok->token == "Film")
{
basicParamListEntrypoint(&ParserTarget::onFilm, tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'I':
if (tok->token == "Integrator")
{
basicParamListEntrypoint(&ParserTarget::onIntegrator, tok->loc);
}
else if (tok->token == "Include")
{
Token filenameToken = *nextToken(TokenRequired);
std::string filename = toString(dequoteString(filenameToken));
auto path = searchPath / filename;
std::unique_ptr<Tokenizer> includeTokenizer = Tokenizer::createFromFile(path);
logInfo("PBRTImporter: Started parsing '{}'.", includeTokenizer->getPath().string());
fileStack.push_back(std::move(includeTokenizer));
}
else if (tok->token == "Import")
{
throwError(tok->loc, "'Import' directive not supported yet.");
}
else if (tok->token == "Identity")
{
target.onIdentity(tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'L':
if (tok->token == "LightSource")
{
basicParamListEntrypoint(&ParserTarget::onLightSource, tok->loc);
}
else if (tok->token == "LookAt")
{
Float v[9];
for (int i = 0; i < 9; ++i)
v[i] = parseFloat(*nextToken(TokenRequired));
target.onLookAt(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8],
tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'M':
if (tok->token == "MakeNamedMaterial")
{
basicParamListEntrypoint(&ParserTarget::onMakeNamedMaterial, tok->loc);
}
else if (tok->token == "MakeNamedMedium")
{
basicParamListEntrypoint(&ParserTarget::onMakeNamedMedium, tok->loc);
}
else if (tok->token == "Material")
{
basicParamListEntrypoint(&ParserTarget::onMaterial, tok->loc);
}
else if (tok->token == "MediumInterface")
{
std::string_view n = dequoteString(*nextToken(TokenRequired));
std::string names[2];
names[0] = toString(n);
// Check for optional second parameter.
std::optional<Token> second = nextToken(TokenOptional);
if (second.has_value()) {
if (isQuotedString(second->token))
names[1] = toString(dequoteString(*second));
else {
unget(*second);
names[1] = names[0];
}
} else
names[1] = names[0];
target.onMediumInterface(names[0], names[1], tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'N':
if (tok->token == "NamedMaterial")
{
std::string_view n = dequoteString(*nextToken(TokenRequired));
target.onNamedMaterial(toString(n), tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'O':
if (tok->token == "ObjectBegin")
{
std::string_view n = dequoteString(*nextToken(TokenRequired));
target.onObjectBegin(toString(n), tok->loc);
}
else if (tok->token == "ObjectEnd")
{
target.onObjectEnd(tok->loc);
}
else if (tok->token == "ObjectInstance")
{
std::string_view n = dequoteString(*nextToken(TokenRequired));
target.onObjectInstance(toString(n), tok->loc);
}
else if (tok->token == "Option")
{
std::string name = toString(dequoteString(*nextToken(TokenRequired)));
std::string value = toString(nextToken(TokenRequired)->token);
target.onOption(name, value, tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'P':
if (tok->token == "PixelFilter")
{
basicParamListEntrypoint(&ParserTarget::onPixelFilter, tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'R':
if (tok->token == "ReverseOrientation")
{
target.onReverseOrientation(tok->loc);
}
else if (tok->token == "Rotate")
{
Float v[4];
for (int i = 0; i < 4; ++i) v[i] = parseFloat(*nextToken(TokenRequired));
target.onRotate(v[0], v[1], v[2], v[3], tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'S':
if (tok->token == "Shape")
{
basicParamListEntrypoint(&ParserTarget::onShape, tok->loc);
}
else if (tok->token == "Sampler")
{
basicParamListEntrypoint(&ParserTarget::onSampler, tok->loc);
}
else if (tok->token == "Scale")
{
Float v[3];
for (int i = 0; i < 3; ++i) v[i] = parseFloat(*nextToken(TokenRequired));
target.onScale(v[0], v[1], v[2], tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'T':
if (tok->token == "TransformBegin")
{
if (!warnedTransformBeginEndDeprecated)
{
logWarning(tok->loc, "TransformBegin/End are deprecated and should be replaced with AttributeBegin/End.");
warnedTransformBeginEndDeprecated = true;
}
target.onAttributeBegin(tok->loc);
}
else if (tok->token == "TransformEnd")
{
target.onAttributeEnd(tok->loc);
}
else if (tok->token == "Transform")
{
if (nextToken(TokenRequired)->token != "[")
syntaxError(*tok);
Float m[16];
for (int i = 0; i < 16; ++i)
m[i] = parseFloat(*nextToken(TokenRequired));
if (nextToken(TokenRequired)->token != "]")
syntaxError(*tok);
target.onTransform(m, tok->loc);
}
else if (tok->token == "Translate")
{
Float v[3];
for (int i = 0; i < 3; ++i)
v[i] = parseFloat(*nextToken(TokenRequired));
target.onTranslate(v[0], v[1], v[2], tok->loc);
}
else if (tok->token == "TransformTimes")
{
Float v[2];
for (int i = 0; i < 2; ++i)
v[i] = parseFloat(*nextToken(TokenRequired));
target.onTransformTimes(v[0], v[1], tok->loc);
}
else if (tok->token == "Texture")
{
std::string_view n = dequoteString(*nextToken(TokenRequired));
std::string name = toString(n);
n = dequoteString(*nextToken(TokenRequired));
std::string type = toString(n);
Token t = *nextToken(TokenRequired);
std::string_view dequoted = dequoteString(t);
std::string texName = toString(dequoted);
ParsedParameterVector params = parseParameters(nextToken, unget);
target.onTexture(name, type, texName, std::move(params), tok->loc);
}
else
{
syntaxError(*tok);
}
break;
case 'W':
if (tok->token == "WorldBegin")
{
target.onWorldBegin(tok->loc);
}
else
{
syntaxError(*tok);
}
break;
default:
syntaxError(*tok);
}
}
}
void parseFile(ParserTarget& target, const std::filesystem::path& path)
{
auto tokenizer = Tokenizer::createFromFile(path);
parse(target, std::move(tokenizer));
target.onEndOfFiles();
}
void parseString(ParserTarget& target, std::string str)
{
auto tokenizer = Tokenizer::createFromString(std::move(str));
parse(target, std::move(tokenizer));
target.onEndOfFiles();
}
}
}
| 39.345665 | 145 | 0.398807 | [
"shape",
"vector",
"transform"
] |
9963df7ce4bcdef35a0c99a1862d0dadc770aeac | 2,375 | cpp | C++ | src/Visualization.cpp | arslansadiq/KinectShape | 5e5f0c544fd6fc57c05b305f90d5bcc5903bd1d0 | [
"MIT"
] | 71 | 2015-03-05T16:59:00.000Z | 2021-12-07T08:42:16.000Z | src/Visualization.cpp | coolvision/KinectShape | 5e5f0c544fd6fc57c05b305f90d5bcc5903bd1d0 | [
"MIT"
] | null | null | null | src/Visualization.cpp | coolvision/KinectShape | 5e5f0c544fd6fc57c05b305f90d5bcc5903bd1d0 | [
"MIT"
] | 30 | 2015-02-05T16:31:02.000Z | 2020-12-28T05:41:33.000Z | /*
* Visualization.cpp
*
* Created on: 2012
* Author: sk
*/
#include "ShapeApp.h"
void drawCameraPose(ofxKinect *kinect, ofColor color,
ofMatrix4x4 transform_matrix) {
ofPoint near[4];
ofPoint far[4];
ofPoint camera_near[4];
ofPoint camera_far[4];
ofPoint world_near[4];
ofPoint world_far[4];
//int width = kinect->getDepthPixelsRef().getWidth();
//int height = kinect->getDepthPixelsRef().getHeight();
int width;
int height;
// so, there are some points for display of the camera pose
near[0].set(0, 0, 0.0f);
near[1].set(0, height, 0.0f);
near[2].set(width, height, 0.0f);
near[3].set(width, 0, 0.0f);
far[0].set(0, 0, -1500);
far[1].set(0, height, -1500);
far[2].set(width, height, -1500);
far[3].set(width, 0, -1500);
// first, transform some points into camera coordinates
for (int i = 0; i < 4; i++) {
camera_near[i] = kinect->getWorldCoordinateAt(near[i].x, near[i].y,
near[i].z);
camera_far[i] = kinect->getWorldCoordinateAt(far[i].x, far[i].y,
far[i].z);
camera_near[i] /= 1000.0;
camera_far[i] /= 1000.0;
}
ofSetLineWidth(1.0);
// now transform this points
for (int i = 0; i < 4; i++) {
world_near[i] = camera_near[i] * transform_matrix;
world_far[i] = camera_far[i] * transform_matrix;
}
ofSetColor(color);
for (int i = 0; i < 4; i++) {
ofLine(world_near[i], world_far[i]);
}
ofLine(world_far[0], world_far[1]);
ofLine(world_far[1], world_far[2]);
ofLine(world_far[2], world_far[3]);
ofLine(world_far[3], world_far[0]);
}
void ShapeApp::drawVolume() {
float width = max.x - min.x;
float height = max.y - min.y;
ofPoint near_v[4];
ofPoint far_v[4];
near_v[0] = min;
near_v[1].set(min.x + width, min.y, min.z);
near_v[2].set(min.x + width, min.y + height, min.z);
near_v[3].set(min.x, min.y + height, min.z);
far_v[0].set(max.x - width, max.y - height, max.z);
far_v[1].set(max.x, max.y - height, max.z);
far_v[2] = max;
far_v[3].set(max.x - width, max.y, max.z);
ofSetColor(ofColor::green);
ofSetLineWidth(1.0);
ofLine(near_v[0], near_v[1]);
ofLine(near_v[1], near_v[2]);
ofLine(near_v[2], near_v[3]);
ofLine(near_v[3], near_v[0]);
ofLine(far_v[0], far_v[1]);
ofLine(far_v[1], far_v[2]);
ofLine(far_v[2], far_v[3]);
ofLine(far_v[3], far_v[0]);
for (int i = 0; i < 4; i++) {
ofLine(near_v[i], far_v[i]);
}
}
| 24.739583 | 75 | 0.622737 | [
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.