text
stringlengths 8
6.88M
|
|---|
#include "Utf8Ini.h"
#include <stdio.h>
static void testSerialisation(Utf8Ini & settings)
{
std::string data1 = settings.Serialize();
printf("serialized:\n%s\n\n", data1.c_str());
int errorLine = 0;
settings.Deserialize(data1, errorLine);
std::string data2 = settings.Serialize().c_str();
printf("re-serialized (%s):\n%s\n\n", data1 == data2 ? "okay" : "failed", data2.c_str());
}
static void printValue(const Utf8Ini & settings, const std::string & section, const std::string & key)
{
printf("[%s] \"%s\"=\"%s\"\n", section.c_str(), key.c_str(), settings.GetValue(section, key).c_str());
}
int main()
{
Utf8Ini settings;
settings.SetValue("Section 1", "Key 1", "Value 1");
settings.SetValue("Section 1", "Key 1", "Value 2");
settings.SetValue("Section 1", "Key 2", " this string starts and ends with a space ");
settings.SetValue("Section 2", "Key 1", "this string contains a\nnewline and escaped characters \\ \\n ");
testSerialisation(settings);
puts("====================================");
std::string iniData = "[Section 1]\n Key 1 = Value 1 \r\n Key 1 = \"Value 2\"\nKey 2 = \" this string starts and ends with a space \"\n\r ; comment line\n\n[Section 2] \nKey 1= \"this string contains a\\nnewline and escaped characters \\\\ \\\\n \"\nKey 2 = I like Utf8Ini!";
int errorLine;
if(!settings.Deserialize(iniData, errorLine))
printf("error deserializing (line %d)\n", errorLine);
else
testSerialisation(settings);
puts("====================================");
printValue(settings, "Section 1", "Key 1");
printValue(settings, "Section 1", "Key 2");
printValue(settings, "Section 2", "Key 1");
printValue(settings, "Section 2", "Key 2");
getchar();
return 0;
}
|
/***************************************************************************
Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD
FileName: RTCPSRPacket.cpp
Description: implement a compound RTCP packet including SR,SDES,BYE and Server info packets
which sent by the Server side.
Comment: copy from Darwin Streaming Server 5.5.5
Author: taoyunxing@dadimedia.com
Version: v1.0.0.1
CreateDate: 2010-08-16
LastUpdate: 2010-08-16
****************************************************************************/
#include <string.h>
#include "RTCPSRPacket.h"
#include "MyAssert.h"
#include "OS.h"
//构造函数,注意数据成员的赋值,十分重要
RTCPSRPacket::RTCPSRPacket()
{
// Write as much of the Sender Report as is possible
char theTempCName[kMaxCNameLen];
UInt32 cNameLen = RTCPSRPacket::GetACName(theTempCName);//得到一个cName
//write the SR & SDES headers
UInt32* theSRWriter = (UInt32*)&fSenderReportBuffer;
*theSRWriter = htonl(0x80c80006);//写SR的包头
theSRWriter += 7; //number of UInt32s in an SR.
//SDES length is the length of the CName, plus 2 32bit words (one for packet header, the other for the SSRC)
*theSRWriter = htonl(0x81ca0000 + (cNameLen >> 2) + 1);//写SDES包的包头,数据长度为变长,依CName长度定,再加1
::memcpy(&fSenderReportBuffer[kSenderReportSizeInBytes], theTempCName, cNameLen);
fSenderReportSize = kSenderReportSizeInBytes + cNameLen;
/*
SERVER INFO PACKET FORMAT
struct qtss_rtcp_struct
{
RTCPHeader header;
UInt32 ssrc; // ssrc of rtcp originator
OSType name;
UInt32 senderSSRC;
SInt16 reserved;
SInt16 length; // bytes of data (atoms) / 4
// qtsi_rtcp_atom structures follow
};
*/
// Write the SERVER INFO APP packet
UInt32* theAckInfoWriter = (UInt32*)&fSenderReportBuffer[fSenderReportSize];
*theAckInfoWriter = htonl(0x81cc0006);
theAckInfoWriter += 2;
*(theAckInfoWriter++) = htonl(FOUR_CHARS_TO_INT('q', 't', 's', 'i')); // Ack Info APP name
theAckInfoWriter++; // leave space for the ssrc (again)
*(theAckInfoWriter++) = htonl(2); // 2 UInt32s for the 'at' field
*(theAckInfoWriter++) = htonl(FOUR_CHARS_TO_INT( 'a', 't', 0, 4 ));
fSenderReportWithServerInfoSize = (char*)(theAckInfoWriter+1) - fSenderReportBuffer;
// Write BYE packet
UInt32* theByeWriter = (UInt32*)&fSenderReportBuffer[fSenderReportWithServerInfoSize];
*theByeWriter = htonl(0x81cb0001);
}
//对给定的入参,得到一个cName,并返回它的真实数据的长度(含padding bit)
UInt32 RTCPSRPacket::GetACName(char* ioCNameBuffer)
{
static char* sCNameBase = "QTSS";
//clear out the whole buffer 初始化入参
::memset(ioCNameBuffer, 0, kMaxCNameLen);
//cName identifier
ioCNameBuffer[0] = 1;
//Unique cname is constructed from the base name and the current time
qtss_sprintf(&ioCNameBuffer[2], " %s%"_64BITARG_"d", sCNameBase, OS::Milliseconds() / 1000); //1应为2?
UInt32 cNameLen = ::strlen(ioCNameBuffer);
//2nd byte of CName should be length
ioCNameBuffer[1] = (UInt8) (cNameLen - 2);//don't count indicator or length byte,不要计算前两个字节(indicator和length位)
// This function assumes that the cName is the only item in this SDES chunk (see RTP rfc 3550 for details).
// The RFC says that the item (the cName) should not be NULL terminated, but
// the chunk *must* be NULL terminated. And padded to a 32-bit boundary.
// qtss_sprintf already put a NULL terminator in the cName buffer. So all we have to
// do is pad out to the boundary.
cNameLen += 1; //add on the NULL character
UInt32 paddedLength = cNameLen + (4 - (cNameLen % 4));//再附加几bit凑成4字节的倍数,先统计附加的长度
// Pad, and zero out as we pad.附加几个值为0的比特
for (; cNameLen < paddedLength; cNameLen++)
ioCNameBuffer[cNameLen] = '\0';
Assert((cNameLen % 4) == 0);
return cNameLen;
}
/*
SDES: Source Description
------------------------
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|V=2|P| SC | PT=SDES=202 | length | header
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
| SSRC/CSRC_1 | chunk
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SDES items |
| ... |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
| SSRC/CSRC_2 | chunk 2
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SDES items |
| ... |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
Sender Report
---------------
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
header |V=2|P| RC | PT=SR=200 | length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SSRC of sender |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
sender | NTP timestamp, most significant word |
info +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| NTP timestamp, least significant word |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| RTP timestamp |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| sender's packet count |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| sender's octet count |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
report | SSRC_1 (SSRC of first source) |
block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1 | fraction lost | cumulative number of packets lost |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| extended highest sequence number received |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| interarrival jitter |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| last SR (LSR) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| delay since last SR (DLSR) |
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
report | SSRC_2 (SSRC of second source) |
block +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2 : ... :
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
| profile-specific extensions |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
APP: Application-defined RTCP packet
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|V=2|P| subtype | PT=APP=204 | length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SSRC/CSRC |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| name (ASCII) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| application-dependent data |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
|
#include "hardware.h"
namespace environment
{
hardware::hardware(boost::shared_ptr<controller> const & c) :
robo_(c)
{
}
hardware::~hardware()
{
}
//must exported to python
//sensors
double hardware::ray_distance(double x, double y, double z) const
{
return robo_->ray_traverse(vector3(x, y, z));
}
double hardware::ir_distance(double x, double y, double z) const
{
return robo_->cone_traverse(vector3(x, y, z), 5);
}
double hardware::wave_distance(double x, double y, double z) const
{
return robo_->cone_traverse(vector3(x, y, z), 5);
}
//controls
void hardware::set_speed(double left, double right)
{
robo_->set_speed(left, right);
}
py_v3 hardware::destination(double x, double y, double z)
{
return py_v3(robo_->destination(x, y, z));
}
}
|
#include <iostream>
using namespace std;
int main(void) {
int a, b;
cout << "Input two numbers:" << endl;
cin >> a >> b;
if (1./a == 1./b) cout << "Results are equal" << endl;
else cout << "Results are NOT equal" << endl;
system("pause");
return 0;
}
|
#include "pathTable.cxx"
|
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
using namespace std;
int T;
const int MAX_T = 20;
int n[MAX_T];
const int MAX_N = 1000;
char s[MAX_T][MAX_N][MAX_N];
void read_T();
void read();
void solve(int t);
int main(){
read_T();
for(int t=0; t < T; t++){
read();
solve(t);
}
return 0;
}
void read_T(){
cin >> T;
fprintf(stderr, "T=%d\n", T);
}
void read(){
scanf("%d", &n);
fprintf(stderr, "n; %d\n", n);
}
void solve(int t){
int ans;
printf("Case #%d: %s\n", t+1, (ans == 1) ? "YES" : "NO");
}
|
#ifndef _TNA_TASKING_TASK_H_
#define _TNA_TASKING_TASK_H_ value
namespace tna
{
typedef void(*task_function_t)(void *arg);
struct task_t
{
/**
* @brief Pointer to the function that executed the task
*/
task_function_t p_fp;
/**
* @brief Pointer to the argument data that will be passed to the task
* function
*/
void* p_args;
};
} /* tna */
#endif /* ifndef _TASKING_TASK_H_ */
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <algorithm>
#include <cmath>
#include <functional>
#include <ATen/ATen.h>
#include <ATen/TypeDefault.h>
#include <torch/library.h>
#include "ATen/Parallel.h"
#include "fbgemm_gpu/sparse_ops_utils.h"
namespace {
// To avoid multiple threads are touching the same cache line.
// Assume cache line size is 64B and element size is at least 4B like float or
// int32.
constexpr int FALSE_SHARING_PAD = 16;
// Converts sparse tensor to dense tensor with few optimizations to be used with
// histogram binning calibration by feature. (1) Assumes dense_last_dim == 1 (2)
// Does not update default value when length > 1. HBC by feature has a separate
// logic to handle this, but we fold it over here.
template <typename SegmentValueType, typename SegmentLengthType>
void _to_dense_representation(
const int64_t num_lengths,
const SegmentValueType* const segment_value_data,
const SegmentLengthType* const segment_lengths_data,
SegmentValueType* const dense_segment_value_data) {
int k = 0;
for (const auto i : c10::irange(num_lengths)) {
if (segment_lengths_data[i] == 1) {
// Add 1 to distinguish between 0 inserted by densification vs. original
// value.
dense_segment_value_data[i] = segment_value_data[k] + 1;
} else {
dense_segment_value_data[i] = 0;
}
k += segment_lengths_data[i];
}
}
} // namespace
using Tensor = at::Tensor;
namespace fbgemm_gpu {
Tensor native_empty_like(const Tensor& self) {
return at::native::empty_like(
self,
optTypeMetaToScalarType(self.options().dtype_opt()),
self.options().layout_opt(),
self.options().device_opt(),
self.options().pinned_memory_opt(),
c10::nullopt);
}
template <typename T>
void prefix_sum(const int length, const T* const array, T* const presum) {
presum[0] = 0;
for (const auto i : c10::irange(length)) {
presum[i + 1] = array[i] + presum[i];
}
}
// NOTE : _permute_indices_weights_kernel_cpu and _permute_lengths_cpu_kernel
// have to use the same grain size for consistent partitioning across threads.
template <
bool has_weight,
typename offsets_t,
typename indices_t,
typename weights_t>
void _permute_indices_weights_kernel_cpu(
const int32_t T,
const int32_t B,
const indices_t* const __restrict__ indices,
const weights_t* const __restrict__ weights,
const int32_t* const __restrict__ permute,
const offsets_t* const __restrict__ input_offsets,
const int64_t* const __restrict__ output_offsets_per_thread_cumsum,
indices_t* const __restrict__ permuted_indices,
weights_t* const __restrict__ permuted_weights,
const offsets_t* const __restrict__ permuted_lengths) {
at::parallel_for(
0, T * B, FALSE_SHARING_PAD, [&](int64_t tb_begin, int64_t tb_end) {
offsets_t output_start = output_offsets_per_thread_cumsum
[at::get_thread_num() * FALSE_SHARING_PAD];
int64_t t_begin = tb_begin / B;
int64_t t_end = (tb_end + B - 1) / B;
for (const auto t : c10::irange(t_begin, t_end)) {
int64_t b_begin = (t == t_begin) ? tb_begin % B : 0;
int64_t b_end = (t == t_end - 1 && tb_end % B != 0) ? tb_end % B : B;
for (const auto b : c10::irange(b_begin, b_end)) {
offsets_t permuted_length = permuted_lengths[t * B + b];
const offsets_t input_start = input_offsets[permute[t] * B + b];
for (const auto i : c10::irange(permuted_length)) {
permuted_indices[output_start + i] = indices[input_start + i];
if (has_weight) {
permuted_weights[output_start + i] = weights[input_start + i];
}
}
output_start += permuted_length;
} // for each b
} // for each t
}); // parallel_for T * B
}
template <typename index_t>
void _permute_lengths_cpu_kernel(
const int32_t T,
const int32_t B,
const index_t* const __restrict__ lengths,
int64_t lengths_size,
const int32_t* const __restrict__ permute,
index_t* const __restrict__ permuted_lengths,
index_t* const __restrict__ input_offsets,
int64_t* const __restrict__ output_offsets_per_thread_cumsum) {
int num_threads = at::get_num_threads();
std::vector<int> input_offsets_per_thread_cumsum(
(num_threads + 1) * FALSE_SHARING_PAD, 0);
// First parallel for: populate permuted_lengths, and compute per-thread
// summation of lengths (input_offsets_per_thread_cumsum) and permuted_lengths
// (output_offsets_per_thread_cumsum)
at::parallel_for(
0, T * B, FALSE_SHARING_PAD, [&](int64_t tb_begin, int64_t tb_end) {
index_t current_input_offset = 0;
// Have a separate loop for summing up lengths because lengths_size
// can be smaller than T * B.
for (int tb = tb_begin; tb < std::min(tb_end, lengths_size); ++tb) {
current_input_offset += lengths[tb];
}
index_t current_output_offset = 0;
int64_t t_begin = tb_begin / B;
int64_t t_end = (tb_end + B - 1) / B;
for (const auto t : c10::irange(t_begin, t_end)) {
int64_t b_begin = (t == t_begin) ? tb_begin % B : 0;
int64_t b_end = (t == t_end - 1 && tb_end % B != 0) ? tb_end % B : B;
for (const auto b : c10::irange(b_begin, b_end)) {
auto permuted_length = lengths[permute[t] * B + b];
permuted_lengths[t * B + b] = permuted_length;
current_output_offset += permuted_length;
}
}
input_offsets_per_thread_cumsum
[(at::get_thread_num() + 1) * FALSE_SHARING_PAD] =
current_input_offset;
output_offsets_per_thread_cumsum
[(at::get_thread_num() + 1) * FALSE_SHARING_PAD] =
current_output_offset;
});
// Inter-thread reduction
for (const auto t : c10::irange(1, num_threads)) {
input_offsets_per_thread_cumsum[(t + 1) * FALSE_SHARING_PAD] +=
input_offsets_per_thread_cumsum[t * FALSE_SHARING_PAD];
output_offsets_per_thread_cumsum[(t + 1) * FALSE_SHARING_PAD] +=
output_offsets_per_thread_cumsum[t * FALSE_SHARING_PAD];
}
// Second parallel for: populate input_offsets
// NOTE: this works assuming the partitioning will be the same as the
// first parallel_for.
at::parallel_for(
0, T * B, FALSE_SHARING_PAD, [&](int64_t tb_begin, int64_t tb_end) {
index_t current_input_offset = input_offsets_per_thread_cumsum
[at::get_thread_num() * FALSE_SHARING_PAD];
if (tb_begin < lengths_size) {
input_offsets[tb_begin] = current_input_offset;
}
for (const auto tb :
c10::irange(tb_begin, std::min(tb_end - 1, lengths_size))) {
current_input_offset += lengths[tb];
input_offsets[tb + 1] = current_input_offset;
}
});
if (lengths_size >= T * B) {
input_offsets[T * B] =
input_offsets_per_thread_cumsum[num_threads * FALSE_SHARING_PAD];
}
// Handle cases when lengths_size > T * B
for (const auto i : c10::irange(T * B, lengths_size)) {
input_offsets[i + 1] = lengths[i] + input_offsets[i];
}
}
template <
bool sequence,
bool has_weight,
typename offset_t,
typename index_t,
typename scalar_t>
void _block_bucketize_sparse_features_cpu(
Tensor lengths,
Tensor indices,
c10::optional<Tensor> weights,
bool bucketize_pos,
Tensor block_sizes,
int64_t my_size,
Tensor new_lengths,
Tensor new_indices,
c10::optional<Tensor> new_weights,
c10::optional<Tensor> new_pos,
c10::optional<Tensor> unbucketize_permute) {
// allocate tensors and buffers
const auto lengths_size = lengths.numel();
const auto new_lengths_size = lengths_size * my_size;
const int32_t T = block_sizes.numel();
const int32_t B = lengths_size / T;
auto offsets = at::empty({lengths_size + 1}, lengths.options());
auto new_offsets = at::empty({new_lengths_size + 1}, lengths.options());
const offset_t* lengths_data = lengths.data_ptr<offset_t>();
offset_t* offsets_data = offsets.data_ptr<offset_t>();
const index_t* indices_data = indices.data_ptr<index_t>();
scalar_t* weights_data;
scalar_t* new_weights_data;
index_t* new_pos_data;
index_t* unbucketize_permute_data;
offset_t* new_lengths_data = new_lengths.data_ptr<offset_t>();
offset_t* new_offsets_data = new_offsets.data_ptr<offset_t>();
index_t* new_indices_data = new_indices.data_ptr<index_t>();
index_t* block_sizes_data = block_sizes.data_ptr<index_t>();
using uindex_t = std::make_unsigned_t<index_t>;
using uoffset_t = std::make_unsigned_t<offset_t>;
if (sequence) {
unbucketize_permute_data = unbucketize_permute.value().data_ptr<index_t>();
}
if (has_weight) {
weights_data = weights.value().data_ptr<scalar_t>();
new_weights_data = new_weights.value().data_ptr<scalar_t>();
}
if (bucketize_pos) {
new_pos_data = new_pos.value().data_ptr<index_t>();
}
// count nonzeros
prefix_sum(lengths_size, lengths_data, offsets_data);
assert(offsets_data[lengths_size] == indices.numel());
for (const auto t : c10::irange(T)) {
auto blk_size = block_sizes_data[t];
for (const auto b : c10::irange(B)) {
const auto b_t = t * B + b;
const offset_t rowstart = offsets_data[b_t];
const offset_t rowend = offsets_data[b_t + 1];
for (const auto i : c10::irange(rowstart, rowend)) {
// We have use cases using none-hashed raw indices that can be either
// negative or larger than embedding table hash_size (blk_size *
// my_size). In cases of none-hashed indices we need to ensure
// bucketization can distribute them into different ranks and within
// range of blk_size, we expect the later embedding module to take care
// of hashing indices calculation.
const auto idx = static_cast<int64_t>(indices_data[i]);
const auto p =
idx < blk_size * my_size ? idx / blk_size : idx % my_size;
new_lengths_data[p * lengths_size + b_t]++;
}
}
}
// bucketize nonzeros
prefix_sum(new_lengths_size, new_lengths_data, new_offsets_data);
assert(new_offsets_data[new_lengths_size] == new_indices.numel());
for (const auto t : c10::irange(T)) {
auto blk_size = block_sizes_data[t];
for (const auto b : c10::irange(B)) {
const auto b_t = t * B + b;
const offset_t rowstart = offsets_data[b_t];
const offset_t rowend = offsets_data[b_t + 1];
for (const auto i : c10::irange(rowstart, rowend)) {
// We have use cases using none-hashed raw indices that can be either
// negative or larger than embedding table hash_size (blk_size *
// my_size). In cases of none-hashed indices we need to ensure
// bucketization can distribute them into different ranks and within
// range of blk_size, we expect the later embedding module to take care
// of hashing indices calculation.
const auto idx = static_cast<int64_t>(indices_data[i]);
const auto p =
idx < blk_size * my_size ? idx / blk_size : idx % my_size;
const uindex_t new_idx = idx % blk_size;
const uoffset_t pos = new_offsets_data[p * lengths_size + b_t];
new_indices_data[pos] = new_idx;
if (sequence) {
unbucketize_permute_data[i] = pos;
}
new_offsets_data[p * lengths_size + b_t]++;
if (has_weight) {
new_weights_data[pos] = weights_data[i];
}
if (bucketize_pos) {
new_pos_data[pos] = i - rowstart;
}
}
}
}
}
std::tuple<Tensor, Tensor, c10::optional<Tensor>> permute_sparse_data_cpu(
const Tensor& permute,
const Tensor& lengths,
const Tensor& indices,
const c10::optional<Tensor>& weights,
const c10::optional<int64_t>& permuted_lengths_sum) {
TENSOR_ON_CPU(permute);
TENSOR_ON_CPU(lengths);
TENSOR_ON_CPU(indices);
TENSOR_ON_CPU(weights);
const auto permute_contig = permute.expect_contiguous();
const auto lengths_contig = lengths.expect_contiguous();
const auto indices_contig = indices.expect_contiguous();
// the data to permute over can be less or more with or without
// repetitions
const auto T = permute.numel();
const auto B = lengths.view({lengths.sizes()[0], -1}).sizes()[1];
Tensor permuted_lengths;
Tensor permuted_indices;
Tensor permuted_weights;
permuted_lengths = at::empty({T, B}, lengths.options());
const auto lengths_size = lengths.numel();
auto input_offsets = at::empty({lengths_size + 1}, lengths.options());
int num_threads = at::get_num_threads();
std::vector<int64_t> output_offsets_per_thread_cumsum(
(num_threads + 1) * FALSE_SHARING_PAD, 0);
AT_DISPATCH_INDEX_TYPES(
lengths.scalar_type(), "permute_lengths_cpu_kernel", ([&] {
_permute_lengths_cpu_kernel(
T,
B,
lengths_contig->data_ptr<index_t>(),
lengths_size,
permute.data_ptr<int32_t>(),
permuted_lengths.data_ptr<index_t>(),
input_offsets.data_ptr<index_t>(),
output_offsets_per_thread_cumsum.data());
})); // for each scalar_t
int64_t permuted_indices_size = 0;
if (permuted_lengths_sum.has_value()) {
permuted_indices_size = permuted_lengths_sum.value();
} else {
permuted_indices_size =
output_offsets_per_thread_cumsum[num_threads * FALSE_SHARING_PAD];
}
permuted_indices = at::empty(permuted_indices_size, indices.options());
AT_DISPATCH_INDEX_TYPES(
input_offsets.scalar_type(), "permute_indices_weights_kernel_1", ([&] {
using offsets_t = index_t;
AT_DISPATCH_ALL_TYPES(
indices.scalar_type(), "permute_indices_weights_kernel_2", ([&] {
using indices_t = scalar_t;
AT_DISPATCH_FLOATING_TYPES(
weights.has_value() ? weights.value().scalar_type()
: at::ScalarType::Float,
"permute_indices_weights_kernel_3",
([&] {
using weights_t = scalar_t;
if (weights.has_value()) {
const auto weights_value_contig =
weights.value().expect_contiguous();
permuted_weights = at::empty(
permuted_indices_size, weights.value().options());
_permute_indices_weights_kernel_cpu<
true,
index_t,
indices_t,
weights_t>(
T,
B,
indices_contig->data_ptr<indices_t>(),
weights_value_contig->data_ptr<weights_t>(),
permute_contig->data_ptr<int32_t>(),
input_offsets.data_ptr<offsets_t>(),
output_offsets_per_thread_cumsum.data(),
permuted_indices.data_ptr<indices_t>(),
permuted_weights.data_ptr<weights_t>(),
permuted_lengths.data_ptr<offsets_t>());
} else {
_permute_indices_weights_kernel_cpu<
false,
index_t,
indices_t,
weights_t>(
T,
B,
indices_contig->data_ptr<indices_t>(),
nullptr,
permute_contig->data_ptr<int32_t>(),
input_offsets.data_ptr<offsets_t>(),
output_offsets_per_thread_cumsum.data(),
permuted_indices.data_ptr<indices_t>(),
nullptr,
permuted_lengths.data_ptr<offsets_t>());
}
})); // for each weights_t
})); // for each indices_t
})); // for each offsets_t
return {permuted_lengths, permuted_indices, permuted_weights};
}
std::tuple<
Tensor,
Tensor,
c10::optional<Tensor>,
c10::optional<Tensor>,
c10::optional<Tensor>>
block_bucketize_sparse_features_cpu(
Tensor lengths,
Tensor indices,
bool bucketize_pos,
bool sequence,
Tensor block_sizes,
int64_t my_size,
c10::optional<Tensor> weights) {
const auto lengths_size = lengths.numel();
const auto new_lengths_size = lengths_size * my_size;
auto new_lengths = at::zeros({new_lengths_size}, lengths.options());
auto new_indices = native_empty_like(indices);
Tensor new_weights;
Tensor new_pos;
Tensor unbucketize_permute;
if (bucketize_pos) {
new_pos = native_empty_like(indices);
}
if (weights.has_value()) {
const auto lengths_sum = indices.numel();
Tensor weights_value = weights.value();
new_weights = native_empty_like(weights_value);
if (sequence) {
unbucketize_permute = at::empty({lengths_sum}, indices.options());
AT_DISPATCH_INDEX_TYPES(
lengths.scalar_type(),
"block_bucketize_sparse_features_weights_cpu_1",
([&] {
using offset_t = index_t;
AT_DISPATCH_INDEX_TYPES(
indices.scalar_type(),
"block_bucketize_sparse_features_weights_cpu_2",
([&] {
AT_DISPATCH_FLOATING_TYPES(
weights_value.scalar_type(),
"bucketize_sparse_features_weights_cpu_3",
([&] {
_block_bucketize_sparse_features_cpu<
true,
true,
offset_t,
index_t,
scalar_t>(
lengths,
indices,
weights,
bucketize_pos,
block_sizes,
my_size,
new_lengths,
new_indices,
new_weights,
new_pos,
unbucketize_permute);
}));
}));
}));
} else {
AT_DISPATCH_INDEX_TYPES(
lengths.scalar_type(),
"block_bucketize_sparse_features_weights_cpu_1",
([&] {
using offset_t = index_t;
AT_DISPATCH_INDEX_TYPES(
indices.scalar_type(),
"block_bucketize_sparse_features_weights_cpu_2",
([&] {
AT_DISPATCH_FLOATING_TYPES(
weights_value.scalar_type(),
"bucketize_sparse_features_weights_cpu_3",
([&] {
_block_bucketize_sparse_features_cpu<
false,
true,
offset_t,
index_t,
scalar_t>(
lengths,
indices,
weights,
bucketize_pos,
block_sizes,
my_size,
new_lengths,
new_indices,
new_weights,
new_pos,
unbucketize_permute);
}));
}));
}));
}
} else {
if (sequence) {
const auto lengths_sum = indices.numel();
unbucketize_permute = at::empty({lengths_sum}, indices.options());
AT_DISPATCH_INDEX_TYPES(
lengths.scalar_type(), "block_bucketize_sparse_features_cpu_1", ([&] {
using offset_t = index_t;
AT_DISPATCH_INDEX_TYPES(
indices.scalar_type(),
"block_bucketize_sparse_features_cpu_2",
([&] {
_block_bucketize_sparse_features_cpu<
true,
false,
offset_t,
index_t,
std::nullptr_t>(
lengths,
indices,
weights,
bucketize_pos,
block_sizes,
my_size,
new_lengths,
new_indices,
new_weights,
new_pos,
unbucketize_permute);
}));
}));
} else {
AT_DISPATCH_INDEX_TYPES(
lengths.scalar_type(), "block_bucketize_sparse_features_cpu_1", ([&] {
using offset_t = index_t;
AT_DISPATCH_INDEX_TYPES(
indices.scalar_type(),
"block_bucketize_sparse_features_cpu_2",
([&] {
_block_bucketize_sparse_features_cpu<
false,
false,
offset_t,
index_t,
std::nullptr_t>(
lengths,
indices,
weights,
bucketize_pos,
block_sizes,
my_size,
new_lengths,
new_indices,
new_weights,
new_pos,
unbucketize_permute);
}));
}));
}
}
return {new_lengths, new_indices, new_weights, new_pos, unbucketize_permute};
}
// 1D exclusive scan: output[i] = input[i-1] + input[i-2] + input[i-3]
// Used as a helper to several functions below.
template <class T, class U>
U exclusive_scan_ptrs_cpu(
const int64_t N,
const T* const input,
U* const output) {
U cumsum = 0;
for (const auto i : c10::irange(N)) {
output[i] = cumsum;
cumsum += input[i];
}
return cumsum;
}
Tensor asynchronous_exclusive_cumsum_cpu(const Tensor& t_in) {
TENSOR_ON_CPU(t_in);
const auto t_in_contig = t_in.expect_contiguous();
auto output = native_empty_like(*t_in_contig);
AT_DISPATCH_ALL_TYPES(
t_in_contig->type(), "asynchronous_exclusive_cumsum_cpu_kernel", ([&] {
exclusive_scan_ptrs_cpu(
t_in_contig->numel(),
t_in_contig->data_ptr<scalar_t>(),
output.data_ptr<scalar_t>());
}));
return output;
}
Tensor asynchronous_inclusive_cumsum_cpu(const Tensor& t_in) {
TENSOR_ON_CPU(t_in);
const auto t_in_contig = t_in.expect_contiguous();
auto output = native_empty_like(*t_in_contig);
AT_DISPATCH_ALL_TYPES(
t_in_contig->type(), "asynchronous_inclusive_cumsum_cpu_kernel", ([&] {
scalar_t cumsum = 0;
const auto* input_ptr = t_in_contig->data_ptr<scalar_t>();
const auto N = t_in_contig->numel();
auto* output_ptr = output.data_ptr<scalar_t>();
for (const auto i : c10::irange(N)) {
cumsum += input_ptr[i];
output_ptr[i] = cumsum;
}
}));
return output;
}
Tensor asynchronous_complete_cumsum_cpu(const Tensor& t_in) {
TENSOR_ON_CPU(t_in);
TORCH_CHECK(t_in.dim() == 1);
const auto t_in_contig = t_in.expect_contiguous();
auto output = at::zeros({t_in.numel() + 1}, t_in.options());
AT_DISPATCH_ALL_TYPES(
t_in_contig->type(), "asynchronous_complete_cumsum_cpu_kernel", ([&] {
const auto N = t_in_contig->numel();
const auto last_sum = exclusive_scan_ptrs_cpu(
N, t_in_contig->data_ptr<scalar_t>(), output.data_ptr<scalar_t>());
output.data_ptr<scalar_t>()[N] = last_sum;
}));
return output;
}
template <class T>
void reorder_batched_ad_lengths_(
const Tensor& cat_ad_lengths,
const Tensor& batch_offsets,
const int64_t num_ads_in_batch,
Tensor& output) {
const int64_t nB = batch_offsets.numel() - 1;
const int64_t nT = cat_ad_lengths.numel() / num_ads_in_batch;
const auto* batch_offsets_data = batch_offsets.data_ptr<T>();
for (auto b = 0; b < nB; b++) {
const auto num_ads_b = batch_offsets_data[b + 1] - batch_offsets_data[b];
for (auto t = 0; t < nT; t++) {
const int32_t input_segment_start =
nT * batch_offsets_data[b] + t * num_ads_b;
const int32_t output_segment_start =
t * num_ads_in_batch + batch_offsets_data[b];
for (auto i = 0; i < num_ads_b; i++) {
output[output_segment_start + i] =
cat_ad_lengths[input_segment_start + i];
}
}
}
}
Tensor reorder_batched_ad_lengths_cpu(
const Tensor& cat_ad_lengths,
const Tensor& batch_offsets,
const int64_t num_ads_in_batch) {
TENSOR_ON_CPU(cat_ad_lengths);
TENSOR_ON_CPU(batch_offsets);
Tensor reordered_cat_ad_lengths = at::empty_like(cat_ad_lengths);
AT_DISPATCH_ALL_TYPES(
batch_offsets.type(), "reorder_batched_ad_lengths_cpu_kernel", ([&] {
reorder_batched_ad_lengths_<scalar_t>(
cat_ad_lengths,
batch_offsets,
num_ads_in_batch,
reordered_cat_ad_lengths);
}));
return reordered_cat_ad_lengths;
}
template <class T>
void reorder_batched_ad_indices_cpu_(
const Tensor& cat_ad_offsets,
const Tensor& cat_ad_indices,
const Tensor& reordered_cat_ad_offsets,
const Tensor& batch_offsets,
const int64_t num_ads_in_batch,
Tensor& output) {
const int64_t nB = batch_offsets.numel() - 1;
const int64_t nT = (cat_ad_offsets.numel() - 1) / num_ads_in_batch;
const auto* batch_offsets_data = batch_offsets.data_ptr<int32_t>();
const auto* cat_ad_offsets_data = cat_ad_offsets.data_ptr<int32_t>();
const auto* reordered_cat_ad_offsets_data =
reordered_cat_ad_offsets.data_ptr<int32_t>();
const auto* cat_ad_indices_data = cat_ad_indices.data_ptr<T>();
for (auto b = 0; b < nB; b++) {
const auto num_ads_b = batch_offsets_data[b + 1] - batch_offsets_data[b];
for (auto t = 0; t < nT; t++) {
const int32_t input_segment_offset_start =
nT * batch_offsets_data[b] + t * num_ads_b;
const int32_t input_segment_offset_end =
nT * batch_offsets_data[b] + t * num_ads_b + num_ads_b;
const auto input_segment_start =
cat_ad_offsets_data[input_segment_offset_start];
const auto input_segment_end =
cat_ad_offsets_data[input_segment_offset_end];
const auto output_segment_offset_start =
t * num_ads_in_batch + batch_offsets_data[b];
const auto output_segment_start =
reordered_cat_ad_offsets_data[output_segment_offset_start];
for (auto i = 0; i < input_segment_end - input_segment_start; i++) {
output[output_segment_start + i] =
cat_ad_indices_data[input_segment_start + i];
}
}
}
}
Tensor reorder_batched_ad_indices_cpu(
const Tensor& cat_ad_offsets,
const Tensor& cat_ad_indices,
const Tensor& reordered_cat_ad_offsets,
const Tensor& batch_offsets,
const int64_t num_ads_in_batch) {
TENSOR_ON_CPU(cat_ad_offsets);
TENSOR_ON_CPU(cat_ad_indices);
TENSOR_ON_CPU(reordered_cat_ad_offsets);
TENSOR_ON_CPU(batch_offsets);
Tensor reordered_cat_ad_indices = at::empty_like(cat_ad_indices);
AT_DISPATCH_ALL_TYPES(
cat_ad_indices.type(), "reorder_batched_ad_indices_cpu_kernel", ([&] {
reorder_batched_ad_indices_cpu_<scalar_t>(
cat_ad_offsets,
cat_ad_indices,
reordered_cat_ad_offsets,
batch_offsets,
num_ads_in_batch,
reordered_cat_ad_indices);
}));
return reordered_cat_ad_indices;
}
Tensor offsets_range_cpu(const Tensor& offsets, int64_t range_size) {
TENSOR_ON_CPU(offsets);
TENSOR_NDIM_EQUALS(offsets, 1);
const auto offsets_arg = at::TensorArg(offsets, "offsets", 1);
checkScalarTypes("_offsets_range_cpu", offsets_arg, {at::kLong, at::kInt});
auto range = at::empty(range_size, offsets.options());
if (range_size == 0) {
return range;
}
const auto offsets_contig = offsets.expect_contiguous();
const auto N = offsets_contig->numel();
AT_DISPATCH_INDEX_TYPES(
offsets_contig->scalar_type(), "offsets_range_kernel", [&]() {
const index_t* offsets_data = offsets_contig->data_ptr<index_t>();
index_t* range_data = range.data_ptr<index_t>();
index_t last = range_size;
for (int64_t i = N - 1; i >= 0; --i) {
index_t first = offsets_data[i];
std::iota(range_data + first, range_data + last, 0);
last = first;
}
});
return range;
}
/// CPU version of batched_unary_embeddings forward pass.
///
/// Sums up `weight` embeddings according to `offsets` and `indices`.
/// `table_offests` is a helper struct to quickly navigate through tables in
/// `weight` -- it is caller's responsibility to keep it in sync with `weight`.
/// Visualization of op semantics: https://fburl.com/9a4uktmb
///
/// This version is only for numerical verification so not optimized for
/// performance.
///
/// @param weight - Weight for the embeddings.
/// @param table_offsets - Index offsets for each table entry in `weight`.
/// @param offsets - Offsets for the starting point of each summation.
/// @param indices - Indices for the embeddings to fetch (from `weight`).
/// @return The sumed embeddings.
Tensor batched_unary_embeddings_forward_cpu(
const Tensor& weight,
const Tensor& table_offsets,
const Tensor& offsets,
const Tensor& indices) {
TENSOR_ON_CPU(weight);
TENSOR_ON_CPU(table_offsets);
TENSOR_ON_CPU(offsets);
TENSOR_ON_CPU(indices);
// N: number of tasks, T: number of tables, B: batch size
const int32_t N = weight.sizes()[0];
const int32_t T = table_offsets.numel() - 1;
const int32_t B = (offsets.numel() - 1) / T;
TORCH_CHECK(N > 0);
TORCH_CHECK(T > 0);
TORCH_CHECK(B > 0);
// Only supporting limited data types for now.
TORCH_CHECK(weight.scalar_type() == at::ScalarType::Float);
// Make sure the index_t are consistent among table_offsets, offsets and
// indices
TORCH_CHECK(table_offsets.scalar_type() == offsets.scalar_type());
TORCH_CHECK(table_offsets.scalar_type() == indices.scalar_type());
auto output = at::empty({N, B, T}, weight.options());
auto* output_data = output.data_ptr<float>();
const auto* weight_data = weight.data_ptr<float>();
AT_DISPATCH_INDEX_TYPES(
table_offsets.scalar_type(), "unary_indices", ([&] {
const index_t* table_offsets_data = table_offsets.data_ptr<index_t>();
const index_t* offsets_data = offsets.data_ptr<index_t>();
const index_t* indices_data = indices.data_ptr<index_t>();
const index_t sum_E = table_offsets_data[T];
for (const auto n : c10::irange(N)) {
for (const auto b : c10::irange(B)) {
for (const auto t : c10::irange(T)) {
const index_t indices_start = offsets_data[t * B + b];
const index_t indices_end = offsets_data[t * B + b + 1];
float sum = 0;
for (const auto l : c10::irange(indices_start, indices_end)) {
const index_t idx =
n * sum_E + table_offsets_data[t] + indices_data[l];
// Since we don't care about the performance of CPU impl, adding
// the boundary check here. OOB will result in undefined
// behavior for GPU impl.
TORCH_CHECK(idx < weight.numel());
sum += weight_data[idx];
}
output_data[(n * B + b) * T + t] = sum;
}
}
}
}));
return output;
}
template <typename index_t, typename scalar_t>
void jagged_2d_to_dense_forward_kernel(
int32_t B,
int32_t max_L,
int32_t D,
const index_t* offsets,
const scalar_t* values_data,
scalar_t* padded_values_data) {
const auto block_size = max_L * D;
const auto embedding_byte_size = D * sizeof(scalar_t);
for (auto b = 0; b < B; ++b) {
auto start_idx = offsets[b];
auto end_idx = offsets[b + 1];
auto length = end_idx - start_idx;
if (length > max_L) {
length = max_L;
}
auto padding_length = max_L - length;
memcpy(
&padded_values_data[b * block_size],
&values_data[start_idx * D],
length * embedding_byte_size);
memset(
&padded_values_data[b * block_size + length * D],
0,
padding_length * embedding_byte_size);
}
}
Tensor
jagged_2d_to_dense_forward_cpu(Tensor values, Tensor offsets, int64_t max_L) {
TORCH_CHECK(values.dim() == 2);
TORCH_CHECK(offsets.dim() == 1);
TORCH_CHECK(max_L > 0);
const auto B = offsets.numel() - 1;
const auto D = values.size(1);
const auto values_contig = values.expect_contiguous();
const auto offsets_contig = offsets.expect_contiguous();
if (values.size(0) == 0) {
return at::zeros({B, max_L, D}, values.options());
}
auto padded_values = at::empty({B, max_L, D}, values.options());
AT_DISPATCH_INDEX_TYPES(
offsets_contig->scalar_type(),
"jagged_2d_to_dense_forward_by_offsets",
([&]() {
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
values_contig->scalar_type(),
"jagged_2d_to_dense_forward_by_values",
([&]() {
jagged_2d_to_dense_forward_kernel(
B,
max_L,
D,
offsets_contig->data_ptr<index_t>(),
values_contig->data_ptr<scalar_t>(),
padded_values.data_ptr<scalar_t>());
}));
}));
return padded_values;
}
template <typename index_t, typename scalar_t>
void jagged_1d_to_dense_kernel(
int64_t B,
int64_t max_L,
scalar_t padding_value,
const index_t* offsets,
const scalar_t* values_data,
scalar_t* padded_values_data) {
const auto block_size = max_L;
const auto value_byte_size = sizeof(scalar_t);
for (auto b = 0; b < B; ++b) {
auto start_idx = offsets[b];
auto end_idx = offsets[b + 1];
auto length = end_idx - start_idx;
if (length > max_L) {
// Guard against the case that lengths[b] > max_L. This is
// a valid use case.
length = max_L;
}
auto padding_length = max_L - length;
memcpy(
&padded_values_data[b * block_size],
&values_data[start_idx],
length * value_byte_size);
for (int l = 0, offset = b * block_size + length; l < padding_length;
++l, ++offset) {
padded_values_data[offset] = padding_value;
}
}
}
Tensor jagged_1d_to_dense_cpu(
Tensor values,
Tensor offsets,
int64_t max_L,
int64_t padding_value) {
TORCH_CHECK(values.dim() == 1);
TORCH_CHECK(offsets.dim() == 1);
TORCH_CHECK(max_L > 0);
const auto B = offsets.numel() - 1;
const auto values_contig = values.expect_contiguous();
const auto offsets_contig = offsets.expect_contiguous();
if (values.size(0) == 0 && padding_value == 0) {
return at::zeros({B, max_L}, values.options());
}
auto padded_values = at::empty({B, max_L}, values.options());
AT_DISPATCH_INDEX_TYPES(
offsets_contig->scalar_type(), "jagged_1d_to_dense_1", ([&]() {
AT_DISPATCH_ALL_TYPES(
values_contig->scalar_type(), "jagged_1d_to_dense_2", ([&]() {
jagged_1d_to_dense_kernel<index_t, scalar_t>(
B,
max_L,
padding_value,
offsets_contig->data_ptr<index_t>(),
values_contig->data_ptr<scalar_t>(),
padded_values.data_ptr<scalar_t>());
}));
}));
return padded_values;
}
template <typename T>
void _histogram_binning_calibration_cpu_kernel(
const int64_t num_logits,
const double recalibrate_value,
const double step,
const int64_t bin_ctr_in_use_after,
const double bin_ctr_weight_value,
const T* const logit_data,
const double* const bin_num_examples_data,
const double* const bin_num_positives_data,
T* const calibrated_prediction_data,
int64_t* const bin_ids_data) {
for (const auto i : c10::irange(num_logits)) {
const T pre_sigmoid = logit_data[i] + recalibrate_value;
const double uncalibrated = 1.0 / (1.0 + std::exp(-pre_sigmoid));
bin_ids_data[i] = std::ceil(uncalibrated / step) - 1;
const auto curr_bin_num_examples = bin_num_examples_data[bin_ids_data[i]];
if (curr_bin_num_examples > bin_ctr_in_use_after) {
const auto curr_bin_ctr =
bin_num_positives_data[bin_ids_data[i]] / curr_bin_num_examples;
calibrated_prediction_data[i] = curr_bin_ctr * bin_ctr_weight_value +
uncalibrated * (1.0 - bin_ctr_weight_value);
} else {
calibrated_prediction_data[i] = uncalibrated;
}
}
}
std::tuple<Tensor, Tensor> histogram_binning_calibration_cpu(
const Tensor& logit,
const Tensor& bin_num_examples,
const Tensor& bin_num_positives,
double positive_weight,
double lower_bound,
double upper_bound,
int64_t bin_ctr_in_use_after,
double bin_ctr_weight_value) {
TENSOR_ON_CPU(logit);
TENSOR_ON_CPU(bin_num_examples);
TENSOR_ON_CPU(bin_num_positives);
TORCH_CHECK(bin_num_examples.numel() == bin_num_positives.numel());
Tensor calibrated_prediction = at::empty_like(logit);
Tensor bin_ids = at::empty({logit.numel()}, logit.options().dtype(at::kLong));
const double recalibrate_value = std::log(positive_weight);
const double step = (upper_bound - lower_bound) /
static_cast<double>(bin_num_examples.numel());
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
logit.type(), "histogram_binning_calibration_cpu", [&]() {
_histogram_binning_calibration_cpu_kernel<scalar_t>(
logit.numel(),
recalibrate_value,
step,
bin_ctr_in_use_after,
bin_ctr_weight_value,
logit.data_ptr<scalar_t>(),
bin_num_examples.data_ptr<double>(),
bin_num_positives.data_ptr<double>(),
calibrated_prediction.data_ptr<scalar_t>(),
bin_ids.data_ptr<int64_t>());
});
return std::make_tuple(calibrated_prediction, bin_ids);
}
template <typename LogitType, typename SegmentValueType>
void _histogram_binning_calibration_by_feature_cpu_kernel(
const int64_t num_logits,
const int64_t num_bins,
const int64_t num_segments,
const double recalibrate_value,
const double step,
const int64_t bin_ctr_in_use_after,
const double bin_ctr_weight_value,
const LogitType* const logit_data,
const SegmentValueType* const dense_segment_value_data,
const double* const bin_num_examples_data,
const double* const bin_num_positives_data,
LogitType* const calibrated_prediction_data,
int64_t* const bin_ids_data) {
for (const auto i : c10::irange(num_logits)) {
const LogitType pre_sigmoid = logit_data[i] + recalibrate_value;
const double uncalibrated = 1.0 / (1.0 + std::exp(-pre_sigmoid));
const int64_t curr_segment_value =
dense_segment_value_data[i] > num_segments
? 0
: std::max(0L, dense_segment_value_data[i] * num_bins);
bin_ids_data[i] = (std::ceil(uncalibrated / step) - 1) + curr_segment_value;
const auto curr_bin_num_examples = bin_num_examples_data[bin_ids_data[i]];
if (curr_bin_num_examples > bin_ctr_in_use_after) {
const auto curr_bin_ctr =
bin_num_positives_data[bin_ids_data[i]] / curr_bin_num_examples;
calibrated_prediction_data[i] = curr_bin_ctr * bin_ctr_weight_value +
uncalibrated * (1.0 - bin_ctr_weight_value);
} else {
calibrated_prediction_data[i] = uncalibrated;
}
}
}
std::tuple<Tensor, Tensor> histogram_binning_calibration_by_feature_cpu(
const Tensor& logit,
const Tensor& segment_value,
const Tensor& segment_lengths,
int64_t num_segments,
const Tensor& bin_num_examples,
const Tensor& bin_num_positives,
int64_t num_bins,
double positive_weight,
double lower_bound,
double upper_bound,
int64_t bin_ctr_in_use_after,
double bin_ctr_weight_value) {
TENSOR_ON_CPU(logit);
TENSOR_ON_CPU(segment_value);
TENSOR_ON_CPU(segment_lengths);
TENSOR_ON_CPU(bin_num_examples);
TENSOR_ON_CPU(bin_num_positives);
TORCH_CHECK(bin_num_examples.numel() == bin_num_positives.numel());
// dense_segment_value is used as a temporary storage.
Tensor dense_segment_value =
at::empty({logit.numel()}, segment_value.options());
AT_DISPATCH_INDEX_TYPES(
segment_value.scalar_type(),
"to_dense_representation_cpu_wrapper",
[&]() {
using segment_value_t = index_t;
AT_DISPATCH_INDEX_TYPES(
segment_lengths.scalar_type(),
"to_dense_representation_cpu",
[&]() {
using segment_length_t = index_t;
_to_dense_representation<segment_value_t, segment_length_t>(
segment_lengths.numel(),
segment_value.data_ptr<segment_value_t>(),
segment_lengths.data_ptr<segment_length_t>(),
dense_segment_value.data_ptr<segment_value_t>());
});
});
Tensor calibrated_prediction = at::empty_like(logit);
Tensor bin_ids = at::empty({logit.numel()}, logit.options().dtype(at::kLong));
const double recalibrate_value = std::log(positive_weight);
const double step =
(upper_bound - lower_bound) / static_cast<double>(num_bins);
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
logit.type(),
"histogram_binning_calibration_by_feature_cpu_wrapper",
[&]() {
using logit_t = scalar_t;
AT_DISPATCH_INDEX_TYPES(
segment_value.scalar_type(),
"histogram_binning_calibration_by_feature_cpu",
[&]() {
using segment_value_t = index_t;
_histogram_binning_calibration_by_feature_cpu_kernel<
logit_t,
segment_value_t>(
logit.numel(),
num_bins,
num_segments,
recalibrate_value,
step,
bin_ctr_in_use_after,
bin_ctr_weight_value,
logit.data_ptr<logit_t>(),
dense_segment_value.data_ptr<segment_value_t>(),
bin_num_examples.data_ptr<double>(),
bin_num_positives.data_ptr<double>(),
calibrated_prediction.data_ptr<logit_t>(),
bin_ids.data_ptr<int64_t>());
});
});
return std::make_tuple(calibrated_prediction, bin_ids);
}
template <typename LogitType, typename SegmentValueType>
void _generic_histogram_binning_calibration_by_feature_cpu_kernel(
const int64_t num_logits,
const int64_t num_bins,
const int64_t num_segments,
const double recalibrate_value,
const int64_t bin_ctr_in_use_after,
const double bin_ctr_weight_value,
const LogitType* const logit_data,
const SegmentValueType* const dense_segment_value_data,
const double* const bin_num_examples_data,
const double* const bin_num_positives_data,
const double* const bin_boundaries,
LogitType* const calibrated_prediction_data,
int64_t* const bin_ids_data) {
for (const auto i : c10::irange(num_logits)) {
const LogitType pre_sigmoid = logit_data[i] + recalibrate_value;
const double uncalibrated = 1.0 / (1.0 + std::exp(-pre_sigmoid));
const int curr_bin_id =
std::lower_bound(
bin_boundaries, bin_boundaries + num_bins - 1, uncalibrated) -
bin_boundaries;
const int64_t curr_segment_value =
dense_segment_value_data[i] > num_segments
? 0
: std::max(0L, dense_segment_value_data[i] * num_bins);
bin_ids_data[i] = curr_bin_id + curr_segment_value;
const auto curr_bin_num_examples = bin_num_examples_data[bin_ids_data[i]];
if (curr_bin_num_examples > bin_ctr_in_use_after) {
const auto curr_bin_ctr =
bin_num_positives_data[bin_ids_data[i]] / curr_bin_num_examples;
calibrated_prediction_data[i] = curr_bin_ctr * bin_ctr_weight_value +
uncalibrated * (1.0 - bin_ctr_weight_value);
} else {
calibrated_prediction_data[i] = uncalibrated;
}
}
}
std::tuple<Tensor, Tensor> generic_histogram_binning_calibration_by_feature_cpu(
const Tensor& logit,
const Tensor& segment_value,
const Tensor& segment_lengths,
int64_t num_segments,
const Tensor& bin_num_examples,
const Tensor& bin_num_positives,
const Tensor& bin_boundaries,
double positive_weight,
int64_t bin_ctr_in_use_after,
double bin_ctr_weight_value) {
TENSOR_ON_CPU(logit);
TENSOR_ON_CPU(segment_value);
TENSOR_ON_CPU(segment_lengths);
TENSOR_ON_CPU(bin_num_examples);
TENSOR_ON_CPU(bin_num_positives);
TENSOR_ON_CPU(bin_boundaries);
TORCH_CHECK(bin_num_examples.numel() == bin_num_positives.numel());
TORCH_CHECK(
bin_num_examples.numel() ==
(num_segments + 1) * (bin_boundaries.numel() + 1));
// dense_segment_value is used as a temporary storage.
Tensor dense_segment_value =
at::empty({logit.numel()}, segment_value.options());
AT_DISPATCH_INDEX_TYPES(
segment_value.scalar_type(),
"to_dense_representation_cpu_wrapper",
[&]() {
using segment_value_t = index_t;
AT_DISPATCH_INDEX_TYPES(
segment_lengths.scalar_type(),
"to_dense_representation_cpu",
[&]() {
using segment_length_t = index_t;
_to_dense_representation<segment_value_t, segment_length_t>(
segment_lengths.numel(),
segment_value.data_ptr<segment_value_t>(),
segment_lengths.data_ptr<segment_length_t>(),
dense_segment_value.data_ptr<segment_value_t>());
});
});
Tensor calibrated_prediction = at::empty_like(logit);
Tensor bin_ids = at::empty({logit.numel()}, logit.options().dtype(at::kLong));
const double recalibrate_value = std::log(positive_weight);
AT_DISPATCH_FLOATING_TYPES_AND_HALF(
logit.type(),
"generic_histogram_binning_calibration_by_feature_cpu_wrapper",
[&]() {
using logit_t = scalar_t;
AT_DISPATCH_INDEX_TYPES(
segment_value.scalar_type(),
"generic_histogram_binning_calibration_by_feature_cpu",
[&]() {
using segment_value_t = index_t;
_generic_histogram_binning_calibration_by_feature_cpu_kernel<
logit_t,
segment_value_t>(
logit.numel(),
bin_boundaries.numel() + 1,
num_segments,
recalibrate_value,
bin_ctr_in_use_after,
bin_ctr_weight_value,
logit.data_ptr<logit_t>(),
dense_segment_value.data_ptr<segment_value_t>(),
bin_num_examples.data_ptr<double>(),
bin_num_positives.data_ptr<double>(),
bin_boundaries.data_ptr<double>(),
calibrated_prediction.data_ptr<logit_t>(),
bin_ids.data_ptr<int64_t>());
});
});
return std::make_tuple(calibrated_prediction, bin_ids);
}
template <typename scalar_t>
void _segment_sum_csr_cpu_kernel(
const int num_segments,
const int batch_size,
const int* const csr_seg_data,
const scalar_t* const values_data,
scalar_t* const output_data) {
for (const auto i : c10::irange(num_segments)) {
const int seg_start = csr_seg_data[i] * batch_size;
const int seg_end = csr_seg_data[i + 1] * batch_size;
scalar_t v = 0;
for (const auto j : c10::irange(seg_start, seg_end)) {
v += values_data[j];
}
output_data[i] = v;
}
}
Tensor segment_sum_csr_cpu(
const int64_t batch_size,
const Tensor& csr_seg,
const Tensor& values) {
TENSOR_ON_CPU(csr_seg);
TENSOR_ON_CPU(values);
auto output = at::empty(csr_seg.numel() - 1, values.options());
AT_DISPATCH_ALL_TYPES(values.type(), "_segment_sum_csr_cpu", ([&] {
_segment_sum_csr_cpu_kernel<scalar_t>(
csr_seg.numel() - 1,
batch_size,
csr_seg.data_ptr<int>(),
values.data_ptr<scalar_t>(),
output.data_ptr<scalar_t>());
}));
return output;
}
bool should_prune(
const Tensor& weights,
const int64_t num_rows_kept,
double min_save_ratio) {
TENSOR_ON_CPU(weights);
const auto weight_sizes = weights.sizes();
const int64_t data_byte_size = sizeof(float);
const int64_t num_cols = weight_sizes[1];
// Size of the pruned weights tensor.
const int64_t lut_after_prune_size =
num_rows_kept * num_cols * data_byte_size;
constexpr auto index_byte_size = sizeof(int);
const auto lut_num_row = weight_sizes[0];
const int64_t compressed_idx_overhead_size = lut_num_row * index_byte_size;
const int64_t original_size = data_byte_size * weights.numel();
return (compressed_idx_overhead_size + lut_after_prune_size) <
min_save_ratio * original_size;
}
// This operator introduces sparsity to a weight matrix by applying
// magnitude based pruning at a row level. The importance level of a row is
// specified using an 'indicator' vector which contains a single value per
// row of the weight matrix.
//
// A row is considered important and not pruned if the indicator value for that
// particular row is greater than the pruning 'threshold' value.
//
// This operator doesn't zero out the pruned rows in-place. Instead, it returns
// a tuple that contains a pruned weights tensor as well as a map that can be
// used to refer the original row in the pruned weights tensor. We refer this
// map as 'compressed indices map' going forward.
// The compressed indices map is an 1D tensor that contains one entry per
// original row in 'weights'. The array index is the index for the original
// non-pruned weight tensor and the value would be the re-mapped index in the
// pruned weights tensor. If the value for a index is -1, it means the
// corresponding row has been pruned from the original weight tensor.
// Arguments:
// 'weights' - the weight tensor that needs to be pruned rowwise.
// 'indicator' - the magnitude for every row of the 'weights' matrix.
// 'threshold' - the pruning threshold that will be used for comparison
// against the indicator row value.
// 'compressed_indices_dtype' - dtype for the compressed map indices.
// This should be either int32 or int64.
// 'abs' - whether we should perform abs() on the indicator value or not.
// 'min_non_pruned_rows' - a minimum threshold on the number of rows
// that should be present after pruning.
// 'min_save_ratio' - a parameter to tradeoff between lookup table CPU overhead
// with the reduction in memory bandwidth due to pruned rows.
// Pruning will be skipped for the entire matrix if the physical size of
// pruned weights and indices mapping is greater than
// min_save_ratio * weights size.
// 'compressed indices map' will contain a single element [0] in this case.
//
// Returns: a tuple,
// - The first value is the pruned weight tensor whose dtype is float.
// - The second value is a 1D tensor whose dtype is 'compressed_indices_dtype'.
std::tuple<Tensor, Tensor> embedding_bag_rowwise_prune(
const Tensor& weights,
const Tensor& indicator,
const double threshold,
at::ScalarType compressed_indices_dtype,
const bool abs,
const int64_t min_non_pruned_rows,
const c10::optional<double>& min_save_ratio) {
TENSOR_ON_CPU(weights);
TENSOR_ON_CPU(indicator);
TENSOR_NDIM_EQUALS(weights, 2);
TORCH_CHECK(
indicator.numel() == weights.sizes()[0],
"Number of elements in 'indicator' should be equivalent to "
"number of rows in 'weights'.")
TORCH_CHECK(
threshold >= 0.0, "Threshold should be greater than or equal to zero.");
TORCH_CHECK(
compressed_indices_dtype == at::ScalarType::Int ||
compressed_indices_dtype == at::ScalarType::Long,
"'compressed_indices_dtype' should be Int/Long.");
const auto indicator_contig = indicator.expect_contiguous();
const auto indicator_data = indicator_contig->data_ptr<float>();
auto rowwise_prune_mask = at::empty({indicator.numel()}, at::kBool);
int num_kept = 0;
for (const auto i : c10::irange(indicator.numel())) {
const float val = abs ? std::abs(indicator_data[i]) : indicator_data[i];
bool should_keep_row = val > threshold;
// The total number of rows post-pruning should be greater than or equal
// to 'min_non_pruned_rows'.
// Skip pruning the current row to satisfy the above criteria.
if (num_kept < min_non_pruned_rows &&
num_kept + (indicator.numel() - i) <= min_non_pruned_rows) {
should_keep_row = true;
}
if (!should_keep_row) {
rowwise_prune_mask[i] = false;
continue;
}
rowwise_prune_mask[i] = true;
num_kept++;
}
if (min_save_ratio.has_value() &&
!should_prune(weights, min_non_pruned_rows, min_save_ratio.value())) {
auto compressed_indices_mapping = at::empty({1}, compressed_indices_dtype);
compressed_indices_mapping[0] = 0;
return std::tuple<Tensor, Tensor>(weights, compressed_indices_mapping);
}
return at::native::_rowwise_prune(
weights, rowwise_prune_mask, compressed_indices_dtype);
}
} // namespace fbgemm_gpu
TORCH_LIBRARY_FRAGMENT(fbgemm, m) {
m.def(
"permute_sparse_data(Tensor permute, Tensor lengths, Tensor values, Tensor? weights=None, int? permuted_lengths_sum=None) -> (Tensor, Tensor, Tensor?)");
m.def(
"block_bucketize_sparse_features(Tensor lengths, Tensor indices, bool bucketize_pos, bool sequence, Tensor block_sizes, int my_size, Tensor? weights=None) -> (Tensor, Tensor, Tensor?, Tensor?, Tensor?)");
m.def("asynchronous_exclusive_cumsum(Tensor t_in) -> Tensor");
m.def("asynchronous_inclusive_cumsum(Tensor t_in) -> Tensor");
m.def("asynchronous_complete_cumsum(Tensor t_in) -> Tensor");
m.def(
"reorder_batched_ad_lengths(Tensor cat_ad_lengths, Tensor batch_offsets, int num_ads_in_batch) -> Tensor");
m.def(
"reorder_batched_ad_indices(Tensor cat_ad_offsets, Tensor cat_ad_indices, Tensor reordered_cat_ad_offsets, Tensor batch_offsets, int num_ads_in_batch) -> Tensor");
m.def("offsets_range(Tensor offsets, int range_size) -> Tensor");
m.def(
"batched_unary_embeddings(Tensor weight, Tensor table_offsets, Tensor offsets, Tensor indices) -> Tensor");
m.def(
"jagged_2d_to_dense(Tensor values, Tensor offsets, int max_sequence_length) -> Tensor");
m.def(
"jagged_1d_to_dense(Tensor values, Tensor offsets, int max_sequence_length, int padding_value) -> Tensor");
m.def(
"stacked_jagged_2d_to_dense_forward(Tensor values, Tensor lengths, int[] offset_per_key, int[] max_lengths_per_key) -> (Tensor[], Tensor[])");
m.def(
"stacked_jagged_2d_to_dense_backward(int B, int D, int total_L, Tensor[] grad_padded_values_per_key, Tensor[] offsets_tensor_per_key, int[] offset_per_key) -> Tensor");
m.def(
"stacked_jagged_1d_to_dense(Tensor values, Tensor lengths, int[] offset_per_key, int[] max_lengths_per_key, int padding_value) -> Tensor[]");
m.def(
"stacked_jagged_2d_to_dense(Tensor values, Tensor lengths, int[] offset_per_key, int[] max_lengths_per_key) -> Tensor[]");
m.def(
"histogram_binning_calibration(Tensor logit, Tensor bin_num_examples, Tensor bin_num_positives, float positive_weight, float lower_bound, float upper_bound, int bin_ctr_in_use_after, float bin_ctr_weight_value) -> (Tensor, Tensor)");
m.def(
"histogram_binning_calibration_by_feature(Tensor logit, Tensor segment_value, Tensor segment_lengths, int num_segments, Tensor bin_num_examples, Tensor bin_num_positives, int num_bins, float positive_weight, float lower_bound, float upper_bound, int bin_ctr_in_use_after, float bin_ctr_weight_value) -> (Tensor, Tensor)");
m.def(
"generic_histogram_binning_calibration_by_feature(Tensor logit, Tensor segment_value, Tensor segment_lengths, int num_segments, Tensor bin_num_examples, Tensor bin_num_positives, Tensor bin_boundaries, float positive_weight, int bin_ctr_in_use_after, float bin_ctr_weight_value) -> (Tensor, Tensor)");
m.def(
"segment_sum_csr(int batch_size, Tensor csr_seg, Tensor values) -> Tensor");
m.def(
"embedding_bag_rowwise_prune(Tensor weight, Tensor indicator, float threshold, ScalarType compressed_indices_dtype, bool abs=True, int min_num_rows=0, float? min_save_ratio=1.0) -> (Tensor, Tensor)");
}
TORCH_LIBRARY_IMPL(fbgemm, CPU, m) {
m.impl("permute_sparse_data", fbgemm_gpu::permute_sparse_data_cpu);
m.impl(
"block_bucketize_sparse_features",
fbgemm_gpu::block_bucketize_sparse_features_cpu);
m.impl(
"asynchronous_exclusive_cumsum",
fbgemm_gpu::asynchronous_exclusive_cumsum_cpu);
m.impl(
"asynchronous_inclusive_cumsum",
fbgemm_gpu::asynchronous_inclusive_cumsum_cpu);
m.impl(
"asynchronous_complete_cumsum",
fbgemm_gpu::asynchronous_complete_cumsum_cpu);
m.impl(
"reorder_batched_ad_lengths", fbgemm_gpu::reorder_batched_ad_lengths_cpu);
m.impl(
"reorder_batched_ad_indices", fbgemm_gpu::reorder_batched_ad_indices_cpu);
m.impl("offsets_range", fbgemm_gpu::offsets_range_cpu);
m.impl(
"batched_unary_embeddings",
fbgemm_gpu::batched_unary_embeddings_forward_cpu);
m.impl("jagged_2d_to_dense", fbgemm_gpu::jagged_2d_to_dense_forward_cpu);
m.impl("jagged_1d_to_dense", fbgemm_gpu::jagged_1d_to_dense_cpu);
m.impl(
"histogram_binning_calibration",
fbgemm_gpu::histogram_binning_calibration_cpu);
m.impl(
"histogram_binning_calibration_by_feature",
fbgemm_gpu::histogram_binning_calibration_by_feature_cpu);
m.impl(
"generic_histogram_binning_calibration_by_feature",
fbgemm_gpu::generic_histogram_binning_calibration_by_feature_cpu);
m.impl("segment_sum_csr", fbgemm_gpu::segment_sum_csr_cpu);
m.impl(
"embedding_bag_rowwise_prune", fbgemm_gpu::embedding_bag_rowwise_prune);
}
|
#include <stdio.h>
#include <iostream>
#include <string>
#include "board.h"
#include "point.h"
bool checkGameState(Board brd1,Board brd2, Board brd3)
{
bool ret = false;
int tab1[9];
int tab2[9];
int tab3[9];
memcpy(tab1,brd1.getTableContent(),sizeof(tab1));
memcpy(tab2,brd2.getTableContent(),sizeof(tab2));
memcpy(tab3,brd3.getTableContent(),sizeof(tab3));
if(tab1[0] == tab2[0] && tab2[0] == tab3[0] && tab3[0]!= 0)
return true;
if(tab1[1] == tab2[1] && tab2[1] == tab3[1] && tab3[1] != 0)
return true;
if(tab1[2] == tab2[2] && tab2[2] == tab3[2] && tab3[2] != 0)
return true;
if(tab1[3] == tab2[3] && tab2[3] == tab3[3] && tab3[3] != 0)
return true;
if(tab1[4] == tab2[4] && tab2[4] == tab3[4] && tab3[4] != 0)
return true;
if(tab1[5] == tab2[5] && tab2[5] == tab3[5] && tab3[5] != 0)
return true;
if(tab1[6] == tab2[6] && tab2[6] == tab3[6] && tab3[6] != 0)
return true;
if(tab1[7] == tab2[7] && tab2[7] == tab3[7] && tab3[7] != 0)
return true;
if(tab1[8] == tab2[8] && tab2[8] == tab3[8] && tab3[8] != 0)
return true;
if(tab1[0] == tab2[4] && tab2[4] == tab3[8] && tab3[8] != 0)
return true;
if(tab1[6] == tab2[4] && tab2[4] == tab3[2] && tab3[2] != 0)
return true;
if(tab1[2] == tab2[4] && tab2[4] == tab3[6] && tab3[6] != 0)
return true;
if(tab1[8] == tab2[4] && tab2[4] == tab3[0] && tab3[0] != 0)
return true;
if(tab1[2] == tab2[5] && tab2[5] == tab3[8] && tab3[8] != 0)
return true;
if(tab1[1] == tab2[4] && tab2[4] == tab3[7] && tab3[7] != 0)
return true;
if(tab1[0] == tab2[3] && tab2[3] == tab3[6] && tab3[6] != 0)
return true;
if(tab1[8] == tab2[5] && tab2[5] == tab3[2] && tab3[2] != 0)
return true;
if(tab1[7] == tab2[4] && tab2[4] == tab3[1] && tab3[1] != 0)
return true;
if(tab1[6] == tab2[3] && tab2[3] == tab3[0] && tab3[0] != 0)
return true;
if(tab1[0] == tab1[1] && tab1[1] == tab1[2] && tab1[2] != 0)
return true;
if(tab1[3] == tab1[4] && tab1[4] == tab1[5] && tab1[5] != 0)
return true;
if(tab1[6] == tab1[7] && tab1[7] == tab1[8] && tab1[8] != 0)
return true;
if(tab1[0] == tab1[3] && tab1[3] == tab1[6] && tab1[6] != 0)
return true;
if(tab1[1] == tab1[4] && tab1[4] == tab1[7] && tab1[7] != 0)
return true;
if(tab1[2] == tab1[5] && tab1[5] == tab1[8] && tab1[8] != 0)
return true;
if(tab1[0] == tab1[4] && tab1[4] == tab1[8] && tab1[8] != 0)
return true;
if(tab1[6] == tab1[4] && tab1[4] == tab1[2] && tab1[2] != 0)
return true;
if(tab2[0] == tab2[1] && tab2[1] == tab2[2] && tab2[2] != 0)
return true;
if(tab2[3] == tab2[4] && tab2[4] == tab2[5] && tab2[5] != 0)
return true;
if(tab2[6] == tab2[7] && tab2[7] == tab2[8] && tab2[8] != 0)
return true;
if(tab2[0] == tab2[3] && tab2[3] == tab2[6] && tab2[6] != 0)
return true;
if(tab2[1] == tab2[4] && tab2[4] == tab2[7] && tab2[7] != 0)
return true;
if(tab2[2] == tab2[5] && tab2[5] == tab2[8] && tab2[8] != 0)
return true;
if(tab2[0] == tab2[4] && tab2[4] == tab2[8] && tab2[8] != 0)
return true;
if(tab2[6] == tab2[4] && tab2[4] == tab2[2] && tab2[2] != 0)
return true;
if(tab3[0] == tab3[1] && tab3[1] == tab3[2] && tab3[2] != 0)
return true;
if(tab3[3] == tab3[4] && tab3[4] == tab3[5] && tab3[5] != 0)
return true;
if(tab3[6] == tab3[7] && tab3[7] == tab3[8] && tab3[8] != 0)
return true;
if(tab3[0] == tab3[3] && tab3[3] == tab3[6] && tab3[6] != 0)
return true;
if(tab3[1] == tab3[4] && tab3[4] == tab3[7] && tab3[7] != 0)
return true;
if(tab3[2] == tab3[5] && tab3[5] == tab3[8] && tab3[8] != 0)
return true;
if(tab3[0] == tab3[4] && tab3[4] == tab3[8] && tab3[8] != 0)
return true;
if(tab3[6] == tab3[4] && tab3[4] == tab3[2] && tab3[2] != 0)
return true;
return ret;
}
void showDesk(Board brd1, Board brd2, Board brd3)
{
int tab1[9];
int tab2[9];
int tab3[9];
memcpy(tab1,brd1.getTableContent(),sizeof(tab1));
memcpy(tab2,brd2.getTableContent(),sizeof(tab2));
memcpy(tab3,brd3.getTableContent(),sizeof(tab3));
string desk1[9],desk2[9],desk3[9];
string arr1[9],arr2[9],arr3[9];
for(int i = 0; i<9; i++)
{
if(tab1[i] == 1)
arr1[i] = "X";
else if(tab1[i] == 2)
arr1[i] = "Y";
else
arr1[i] = " ";
if(tab2[i] == 1)
arr2[i] = "X";
else if(tab2[i] == 2)
arr2[i] = "Y";
else
arr2[i] = " ";
if(tab3[i] == 1)
arr3[i] = "X";
else if(tab3[i] == 2)
arr3[i] = "Y";
else
arr3[i] = " ";
}
desk1[0] = "\t\t\t\t\t";
desk1[1] = "\t\t ";
desk1[2] = " ___________ ";
desk1[3] = " / " + arr1[0] + " / " + arr1[1] + " / " + arr1[2] + " / ";
desk1[4] = " /-----------/ ";
desk1[5] = " / " + arr1[3] + " / " + arr1[4] + " / " + arr1[5] + " / ";
desk1[6] = " /-----------/ ";
desk1[7] = "/ " + arr1[6] + " / " + arr1[7] + " / " + arr1[8] + " / ";
desk1[8] = "------------ ";
desk2[0] = "";
desk2[1] = " ____________ ";
desk2[2] = "/ " + arr2[0] + " / " + arr2[1] + " / " + arr2[2] + " / ";
desk2[3] = "/-----------/ ";
desk2[4] = "/ " + arr2[3] + " / " + arr2[4] + " / " + arr2[5] + " / ";
desk2[5] = "/-----------/ ";
desk2[6] = "/ " + arr2[6] + " / " + arr2[7] + " / " + arr2[8] + " / ";
desk2[7] = " ------------ ";
desk2[8] = "";
desk3[0] = " ____________";
desk3[1] = "/ " + arr3[0] + " / " + arr3[1] + " / " + arr3[2] + " /";
desk3[2] = "/-----------/";
desk3[3] = "/ " + arr3[3] + " / " + arr3[4] + " / " + arr3[5] + " /";
desk3[4] = "/-----------/";
desk3[5] = "/ " + arr3[6] + " / " + arr3[7] + " / " + arr3[8] + " /";
desk3[6] = " ------------";
desk3[7] = "";
desk3[8] = "";
for(int i = 0;i < 9; i++)
{
cout << desk1[i];
cout << desk2[i];
cout << desk3[i];
cout << endl;
}
}
int countOccurrence(string input, char item)
{
int ret = 0;
for(int i = 0; i < input.size(); i++)
{
if(input[i] == item)
ret+= 1;
}
return ret;
}
int* splitStringIntoIntArr(string input, char del)
{
int delCt = countOccurrence(input,del);
int ret[delCt];
int ix = 0;
for(int i = 0; i < input.size(); i++)
{
if(input[i] != ' ' && input[i] != ',')
{
ret[ix] = stoi(string(1,input[i]));
ix += 1;
}
}
return ret;
}
void doMove(Board brd1, Board brd2, Board brd3, Point pt)
{
string line;
cout << "Ruch gracza nr : " << pt.getSign() << endl;
cout << "Podaj punkt w formacie : x,y,z ." << endl;
getline(cin, line);
int* sPoint ={};
sPoint = splitStringIntoIntArr(line, ',');
pt.setX(sPoint[0]);
pt.setY(sPoint[1]);
pt.setZ(sPoint[2]);
int pz = pt.getZ();
if(pz == 1)
brd1.addPointToTable(pt);
else if(pz == 2)
brd2.addPointToTable(pt);
else if(pz == 3)
brd3.addPointToTable(pt);
showDesk(brd1,brd2,brd3);
//return brd1,brd2,brd3;
}
void startGame()
{
int round = 0;
Board brd1(0);
Board brd2(1);
Board brd3(2);
Point p1(1);
Point p2(2);
while(checkGameState(brd1,brd2,brd3) == false)
{
string line;
if(round%2 == 0)
{
cout << "Ruch gracza nr : " << p1.getSign() << endl;
cout << "Podaj punkt w formacie : x,y,z ." << endl;
getline(cin, line);
int* sPoint ={};
sPoint = splitStringIntoIntArr(line, ',');
p1.setX(sPoint[0]);
p1.setY(sPoint[1]);
p1.setZ(sPoint[2]);
int pz = p1.getZ();
if(pz == 1)
brd1.addPointToTable(p1);
else if(pz == 2)
brd2.addPointToTable(p1);
else if(pz == 3)
brd3.addPointToTable(p1);
}
else if(round%2 == 1)
{
cout << "Ruch gracza nr : " << p2.getSign() << endl;
cout << "Podaj punkt w formacie : x,y,z ." << endl;
getline(cin, line);
int* sPoint ={};
sPoint = splitStringIntoIntArr(line, ',');
p2.setX(sPoint[0]);
p2.setY(sPoint[1]);
p2.setZ(sPoint[2]);
int pz = p2.getZ();
if(pz == 1)
brd1.addPointToTable(p2);
else if(pz == 2)
brd2.addPointToTable(p2);
else if(pz == 3)
brd3.addPointToTable(p2);
}
showDesk(brd1,brd2,brd3);
round += 1;
}
cout << "Gracz nr ";
if(round%2 -1 == 0)
cout << "1";
else
cout << "2";
cout << " wygrał."<<endl;
exit(0);
}
void showMenu()
{
cout << "1. Start gry" << endl << "2. Wyjście" << endl;
string ret = "0";
getline(cin,ret);
if(ret == "1")
{
startGame();
}
else if(ret == "2")
{
exit(0);
}
}
int main()
{
showMenu();
}
|
#ifndef TEXT_HPP
#define TEXT_HPP
#include <SFML\Graphics.hpp>
#include <vector>
#include <iostream>
#include "ResourceManager.hpp"
#include "SceneNode.hpp"
#include "Constants.hpp"
class Text : public SceneNode
{
public:
Text( const sf::Font& font );
virtual void updateCurrent( sf::Time dt, sf::View& view );
virtual void drawCurrent( sf::RenderTarget& target, sf::RenderStates states ) const;
sf::Text& getText() { return m_text; }
void setString( const std::string& text ) { m_text.setString( text ); }
void setSize( int size ) { m_text.setCharacterSize( size ); }
void setColor( sf::Color color ) { m_text.setColor( sf::Color( color ) ); }
void setOffset( float x, float y ) { m_offset = sf::Vector2f( x, y ); } // Provides the same functionality as 'setPosition()'
void setOffset( sf::Vector2f pos ) { m_offset = pos; } // Overloaded function, does the same thing ^^^
private:
sf::Font m_font;
sf::Text m_text;
sf::Vector2f m_offset;
};
#endif //TEXT_HPP
|
#include "demo.hpp"
int step = 0;
int step_direction = 1;
QueueHandle_t demo_task_queue;
void fire_demo_step() {
double roll_k = 0.05;
double rads = step * 2.0 * PI / 360.0;
storage.pitch = 20.0 * cos(rads + PI / 4.0);
storage.roll = 30 * sin(rads);
storage.heading = storage.heading - storage.roll * roll_k ;
if (storage.heading > 360.0) { storage.heading = storage.heading - 360.0; }
if (storage.heading < 0.0) { storage.heading = storage.heading + 360.0 ; }
storage.altitude = storage.altitude + storage.vsi / 20.0;
storage.airspeed = 150 + 30 * sin(rads);
storage.ground_speed = abs(storage.airspeed * cos(storage.pitch * 2.0 * PI / 360.0));
storage.desired_heading = 230;
storage.desired_altitude = 1000;
storage.vsi = storage.airspeed * sin(storage.pitch * 2.0 * PI / 360.0);
storage.qnh = 1013.1;
if (step >= 1000 || step < 0) {
storage.altitude = 1000;
step_direction = (-1) * step_direction;
}
step += step_direction;
}
void demo_task(void* pvParameters) {
int demo_period = 50;
int enabled = 0;
for(;;) {
xQueueReceive(demo_task_queue, &enabled, demo_period / 10);
if (enabled > 0) {
fire_demo_step();
}
vTaskDelay(demo_period / portTICK_PERIOD_MS);
}
}
void demo_init() {
storage.altitude = 1000;
demo_task_queue = xQueueCreate(1, sizeof(int));
xTaskCreate(&demo_task, "demo_task", 3000, NULL, 6, NULL);
}
|
/*
Title: Interpreter
Description: To interperet buffer input and perform
appropriate actions given specific parameters.
Usage: soon...
*/
#include <cstdlib>
#include <iostream>
#include <cstring>
/*
bool interpreter(char* input) {
char* token = strtok(input, " ");
if (strcmp(token, "exit") {
}
}
*/
class Interpreter {
public:
Interpreter();
~Interpreter();
private:
};
Interpreter::Interpreter() {
}
Interpreter::~Interpreter() {
}
|
/* implement a singleton which can die and can be re_created. */
#include <iostream>
class singleton
{
singleton() = default;
static singleton const * instance;
public:
singleton(singleton const &) = delete;
singleton & operator=(singleton const &) = delete;
static singleton const * get_instance()
{
std::cout << "singleton::get_instance()\n";
if (instance == nullptr)
{
instance = new singleton;
std::cout << "new singleton: " << instance << '\n';
}
return instance;
}
static void destroy()
{
std::cout << "singleton::destroy()\n";
if (instance != nullptr)
{
std::cout << "delete instance\n";
delete instance;
instance = nullptr;
}
}
};
singleton const * singleton::instance = nullptr;
int main()
{
singleton::destroy();
singleton::get_instance();
singleton::get_instance();
singleton::destroy();
singleton::destroy();
return 0;
}
|
//cpp
#include "tic_tac_toe.h"
TicTacToe::TicTacToe()
{
}
bool TicTacToe::game_over()
{
if (check_column_win() || check_row_win() || check_diagonal_win())
{
set_winner();
return true;
}
else if (check_board_full())
{
winner = "C";
return true;
}
return false;
}
void TicTacToe::start_game(string player)
{
next_player = player;
clear_board();
}
// position is what user sees when you save posiiton to vector subtract 1 from position
void TicTacToe::mark_board(int position)
{
pegs[position - 1] = next_player;
set_next_player();
}
string TicTacToe::get_player() const
{
return next_player;
}
string TicTacToe::get_winner() const
{
return winner;
}
const std::vector<std::string>& TicTacToe::get_pegs()
{
return pegs;
}
void TicTacToe::set_next_player()
{
if (next_player == "X")
{
next_player = "O";
}
else
{
next_player = "X";
}
}
bool TicTacToe::check_column_win()
{
return false;
}
bool TicTacToe::check_row_win()
{
return false;
}
bool TicTacToe::check_diagonal_win()
{
return false;
}
void TicTacToe::clear_board()
{
for (auto& i : pegs)
{
i = " ";
}
}
bool TicTacToe::check_board_full()
{
for (auto i : pegs)
{
if (i == " ")
{
return false;
}
}
return true;
}
void TicTacToe::set_winner()
{
if (next_player == "X")
{
winner = "O";
}
else
{
winner = "X";
}
}
std::ostream& operator<<(std::ostream& out, const TicTacToe& board)
{
if (board.pegs.size() == 9) {
for (std::size_t i = 0; i <= 6; i += 3)
{
out << board.pegs[i] << "|" << board.pegs[i + 1] << "|" << board.pegs[i + 2] << "\n";
}
return out;
}
else if (board.pegs.size() == 16){
for (std::size_t i = 0; i <= 12; i += 4)
{
out << board.pegs[i] << "|" << board.pegs[i + 1] << "|" << board.pegs[i + 2] << "|" << board.pegs[i + 3] << "\n";
}
return out;
}
}
std::istream& operator>>(std::istream& in, TicTacToe& board)
{
// TODO: insert return statement here
int p_position;
cout << "\nEnter position for " << board.get_player() << " ";
in >> p_position;
board.mark_board(p_position);
return in;
}
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 10
int factorial(int);
int multiply(int, int [], int);
int main() {
int n,m,c,unq1,unq2,FinalLocation;
scanf("%d %d %d",&n,&m,&c);
if((n<11 && m<11) && (c<n && c<m) ){
unq1= n-c;
unq2= m-c;
FinalLocation= unq1+unq2+c-1;
factorial(FinalLocation);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
int factorial(int n){
int res[MAX];
int res_size=1;
res[0]=1;
for(int x=2;x<=n;x++)
res_size=multiply(x,res,res_size);
for(int i=res_size-1;i>=0;i--)
printf("%d",res[i]);
}
int multiply(int x, int res[], int res_size){
int carry=0;
for(int i=0;i<res_size;i++){
int prod=(res[i]*x)+carry;
res[i]=prod%10;
carry=prod/10;
}
while(carry){
res[res_size]=carry%10;
carry=carry/10;
res_size++;
}
return res_size;
}
|
/*=========================================================================
Program: Visualization Toolkit
Module: QVTKRenderWindowAdapter.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef QVTKRenderWindowAdapter_h
#define QVTKRenderWindowAdapter_h
/**
* @class QVTKRenderWindowAdapter
* @brief Helper to manage Qt context and other OpenGL components
*
* QVTKRenderWindowAdapter is an internal class that is used by
* QVTKOpenGLNativeWidget and QVTKOpenGLWindow to manage the rendering using
* vtkGenericOpenGLRenderWindow within a OpenGL context created via Qt.
*
* QVTKRenderWindowAdapter is expected to be recreated anytime the context
* changes. In the constructor, QVTKRenderWindowAdapter will mark the
* vtkGenericOpenGLRenderWindow ready for rendering and call OpenGL context
* initialization API (vtkOpenGLRenderWindow::OpenGLInitContext).
*
* By observing events on vtkGenericOpenGLRenderWindow, QVTKRenderWindowAdapter
* can then support rendering to an internally created FBO via VTK's rendering
* calls. Making sure that the rendering results are shown on the screen is
* handled by QVTKOpenGLWindow or QVTKOpenGLNativeWidget.
*/
#include "vtkGUISupportQtModule.h" // For export macro
#include <QObject>
#include <QCursor> // for ivar
#include <QScopedPointer> // for ivar
class QOpenGLContext;
class QSurfaceFormat;
class QWidget;
class QWindow;
class vtkGenericOpenGLRenderWindow;
class vtkObject;
class VTKGUISUPPORTQT_EXPORT QVTKRenderWindowAdapter : public QObject
{
Q_OBJECT;
using Superclass = QObject;
public:
//@{
/**
* Constructor that makes vtkGenericOpenGLRenderWindow ready for subsequent
* render requests i.e. calls
* `vtkGenericOpenGLRenderWindow::SetReadyForRendering(true)`. This also calls
* `vtkOpenGLRenderWindow::OpenGLInitContext` to ensure that the OpenGL
* context is ready for VTK rendering.
*/
QVTKRenderWindowAdapter(
QOpenGLContext* cntxt, vtkGenericOpenGLRenderWindow* window, QWindow* parent);
QVTKRenderWindowAdapter(
QOpenGLContext* cntxt, vtkGenericOpenGLRenderWindow* window, QWidget* parent);
//@}
~QVTKRenderWindowAdapter() override;
/**
* Returns a QSurfaceFormat suitable for surfaces that intend to be used for
* VTK rendering.
*
* If your applications plans on using `QVTKOpenGLNativeWidget`, then this
* format (or similar) must be set as the default format on QSurfaceFormat
* before any widgets are created.
*
* Note this returns a QSurfaceFormat required to support the OpenGL rendering
* capabilities in a vtkRenderWindow. Whether those features, e.g. multi
* sampling, is actually used for rendering is determined by values
* specified on the vtkRenderWindow instance itself through appropriate API.
*
* Passing `stereo_capable=true` is same as calling `QSurfaceFormat::setStereo(true)`.
* This is necessary if you want to use quad-buffer based stereo in your
* application.
*
* Refer to Qt docs for QOpenGLWidget and QOpenGLWindow for appropriate
* locations in your application where to the format may be provided e.g.
* either on the instance of QOpenGLWindow or QOpenGLWidget subclasses or as
* default format for the application using `QSurfaceFormat::setDefaultFormat()`.
*/
static QSurfaceFormat defaultFormat(bool stereo_capable = false);
/**
* Get the context to use for rendering.
*/
QOpenGLContext* context() const;
/**
* Call this method in `paintGL` to request a render. This may trigger a
* `vtkRenderWindow::Render` if this class determines the buffers may be
* obsolete.
*/
void paint();
/**
* Call this method to resize the render window. This simply calls
* `vtkRenderWindow::SetSize` taking device pixel ratio into consideration.
* This doesn't cause a render or resize of the FBO. That happens on a
* subsequent render request.
*
* Besides widget resize, this method should also be called in cases when the
* devicePixelRatio for the parent window (or widget) changes. This is
* necessary since the internal FBO's pixel size is computed by scaling the
* `widget` and `height` provided by the window's (or widget's) `devicePixelRatio`.
*/
void resize(int width, int height);
//@{
/**
* Convenience methods to blit the results rendered in the internal FBO to a
* target
*/
bool blit(
unsigned int targetId, int targetAttachement, const QRect& targetRect, bool left = true);
bool blitLeftEye(unsigned int targetId, int targetAttachement, const QRect& targetRect)
{
return this->blit(targetId, targetAttachement, targetRect, true);
}
bool blitRightEye(unsigned int targetId, int targetAttachement, const QRect& targetRect)
{
return this->blit(targetId, targetAttachement, targetRect, false);
}
//@}
/**
* Process the event and return true if the event have been processed
* successfully.
*/
bool handleEvent(QEvent* evt);
//@{
/**
* Get/set the default cursor.
*/
void setDefaultCursor(const QCursor& cursor) { this->DefaultCursor = cursor; }
const QCursor& defaultCursor() const { return this->DefaultCursor; }
//@}
//@{
/**
* Enable/disable DPI scaling. When enabled call to `resize` (which must
* happen any time the `devicePixelRatio`, in addition to the size may
* change), will result in updating the DPI on the
* vtkGenericOpenGLRenderWindow as well. The DPI change only happens in
* `resize` to enable applications to temporarily change DPI on the
* vtkGenericOpenGLRenderWindow and request an explicit render seamlessly. In
* such a case, it's the applications responsibility to restore DPI value or
* the changed value will linger until the next `resize` happens.
*/
void setEnableHiDPI(bool value);
//@}
//@{
/**
* Set the unscaled DPI to use when scaling DPI. It defaults to 72, which is
* same as the hard-coded default in `vtkWindow`.
*/
void setUnscaledDPI(int value);
//@}
private slots:
void contextAboutToBeDestroyed();
private:
QVTKRenderWindowAdapter(
QOpenGLContext* cntxt, vtkGenericOpenGLRenderWindow* window, QObject* widgetOrWindow);
Q_DISABLE_COPY(QVTKRenderWindowAdapter);
class QVTKInternals;
QScopedPointer<QVTKInternals> Internals;
QCursor DefaultCursor;
};
#endif
|
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool judgeCircle(string moves) {
unordered_map<char, int> umap;
for (auto c : moves) ++umap[c];
return (umap['U'] == umap['D']) && (umap['L'] == umap['R']);
}
};
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Devices::Usb {
struct IUsbBulkInEndpointDescriptor;
struct IUsbBulkInPipe;
struct IUsbBulkOutEndpointDescriptor;
struct IUsbBulkOutPipe;
struct IUsbConfiguration;
struct IUsbConfigurationDescriptor;
struct IUsbConfigurationDescriptorStatics;
struct IUsbControlRequestType;
struct IUsbDescriptor;
struct IUsbDevice;
struct IUsbDeviceClass;
struct IUsbDeviceClasses;
struct IUsbDeviceClassesStatics;
struct IUsbDeviceDescriptor;
struct IUsbDeviceStatics;
struct IUsbEndpointDescriptor;
struct IUsbEndpointDescriptorStatics;
struct IUsbInterface;
struct IUsbInterfaceDescriptor;
struct IUsbInterfaceDescriptorStatics;
struct IUsbInterfaceSetting;
struct IUsbInterruptInEndpointDescriptor;
struct IUsbInterruptInEventArgs;
struct IUsbInterruptInPipe;
struct IUsbInterruptOutEndpointDescriptor;
struct IUsbInterruptOutPipe;
struct IUsbSetupPacket;
struct IUsbSetupPacketFactory;
struct UsbBulkInEndpointDescriptor;
struct UsbBulkInPipe;
struct UsbBulkOutEndpointDescriptor;
struct UsbBulkOutPipe;
struct UsbConfiguration;
struct UsbConfigurationDescriptor;
struct UsbControlRequestType;
struct UsbDescriptor;
struct UsbDevice;
struct UsbDeviceClass;
struct UsbDeviceClasses;
struct UsbDeviceDescriptor;
struct UsbEndpointDescriptor;
struct UsbInterface;
struct UsbInterfaceDescriptor;
struct UsbInterfaceSetting;
struct UsbInterruptInEndpointDescriptor;
struct UsbInterruptInEventArgs;
struct UsbInterruptInPipe;
struct UsbInterruptOutEndpointDescriptor;
struct UsbInterruptOutPipe;
struct UsbSetupPacket;
}
namespace Windows::Devices::Usb {
struct IUsbBulkInEndpointDescriptor;
struct IUsbBulkInPipe;
struct IUsbBulkOutEndpointDescriptor;
struct IUsbBulkOutPipe;
struct IUsbConfiguration;
struct IUsbConfigurationDescriptor;
struct IUsbConfigurationDescriptorStatics;
struct IUsbControlRequestType;
struct IUsbDescriptor;
struct IUsbDevice;
struct IUsbDeviceClass;
struct IUsbDeviceClasses;
struct IUsbDeviceClassesStatics;
struct IUsbDeviceDescriptor;
struct IUsbDeviceStatics;
struct IUsbEndpointDescriptor;
struct IUsbEndpointDescriptorStatics;
struct IUsbInterface;
struct IUsbInterfaceDescriptor;
struct IUsbInterfaceDescriptorStatics;
struct IUsbInterfaceSetting;
struct IUsbInterruptInEndpointDescriptor;
struct IUsbInterruptInEventArgs;
struct IUsbInterruptInPipe;
struct IUsbInterruptOutEndpointDescriptor;
struct IUsbInterruptOutPipe;
struct IUsbSetupPacket;
struct IUsbSetupPacketFactory;
struct UsbBulkInEndpointDescriptor;
struct UsbBulkInPipe;
struct UsbBulkOutEndpointDescriptor;
struct UsbBulkOutPipe;
struct UsbConfiguration;
struct UsbConfigurationDescriptor;
struct UsbControlRequestType;
struct UsbDescriptor;
struct UsbDevice;
struct UsbDeviceClass;
struct UsbDeviceClasses;
struct UsbDeviceDescriptor;
struct UsbEndpointDescriptor;
struct UsbInterface;
struct UsbInterfaceDescriptor;
struct UsbInterfaceSetting;
struct UsbInterruptInEndpointDescriptor;
struct UsbInterruptInEventArgs;
struct UsbInterruptInPipe;
struct UsbInterruptOutEndpointDescriptor;
struct UsbInterruptOutPipe;
struct UsbSetupPacket;
}
namespace Windows::Devices::Usb {
template <typename T> struct impl_IUsbBulkInEndpointDescriptor;
template <typename T> struct impl_IUsbBulkInPipe;
template <typename T> struct impl_IUsbBulkOutEndpointDescriptor;
template <typename T> struct impl_IUsbBulkOutPipe;
template <typename T> struct impl_IUsbConfiguration;
template <typename T> struct impl_IUsbConfigurationDescriptor;
template <typename T> struct impl_IUsbConfigurationDescriptorStatics;
template <typename T> struct impl_IUsbControlRequestType;
template <typename T> struct impl_IUsbDescriptor;
template <typename T> struct impl_IUsbDevice;
template <typename T> struct impl_IUsbDeviceClass;
template <typename T> struct impl_IUsbDeviceClasses;
template <typename T> struct impl_IUsbDeviceClassesStatics;
template <typename T> struct impl_IUsbDeviceDescriptor;
template <typename T> struct impl_IUsbDeviceStatics;
template <typename T> struct impl_IUsbEndpointDescriptor;
template <typename T> struct impl_IUsbEndpointDescriptorStatics;
template <typename T> struct impl_IUsbInterface;
template <typename T> struct impl_IUsbInterfaceDescriptor;
template <typename T> struct impl_IUsbInterfaceDescriptorStatics;
template <typename T> struct impl_IUsbInterfaceSetting;
template <typename T> struct impl_IUsbInterruptInEndpointDescriptor;
template <typename T> struct impl_IUsbInterruptInEventArgs;
template <typename T> struct impl_IUsbInterruptInPipe;
template <typename T> struct impl_IUsbInterruptOutEndpointDescriptor;
template <typename T> struct impl_IUsbInterruptOutPipe;
template <typename T> struct impl_IUsbSetupPacket;
template <typename T> struct impl_IUsbSetupPacketFactory;
}
namespace Windows::Devices::Usb {
enum class UsbControlRecipient
{
Device = 0,
SpecifiedInterface = 1,
Endpoint = 2,
Other = 3,
DefaultInterface = 4,
};
enum class UsbControlTransferType
{
Standard = 0,
Class = 1,
Vendor = 2,
};
enum class UsbEndpointType
{
Control = 0,
Isochronous = 1,
Bulk = 2,
Interrupt = 3,
};
enum class UsbReadOptions : unsigned
{
None = 0x0,
AutoClearStall = 0x1,
OverrideAutomaticBufferManagement = 0x2,
IgnoreShortPacket = 0x4,
AllowPartialReads = 0x8,
};
DEFINE_ENUM_FLAG_OPERATORS(UsbReadOptions)
enum class UsbTransferDirection
{
Out = 0,
In = 1,
};
enum class UsbWriteOptions : unsigned
{
None = 0x0,
AutoClearStall = 0x1,
ShortPacketTerminate = 0x2,
};
DEFINE_ENUM_FLAG_OPERATORS(UsbWriteOptions)
}
}
|
/*******************************************
*** Dateiname: Kameraschien.ino
********************************************
*** Zweck: Steuerung eines Positioniersystem
*** mittels einer Bluetooth-Applikation
*** Erstellt: 19.10.2016
******************************************
*** Geändert: 07.11.2016
******************************************
*** Änderung: Implementierung der Endschalter-Interrupts
*****************************************/
/*
* Dieses Programm wurde für einen Genuino101 entwickelt.
*
* Aufgabe des Programms:
* Das Programm hat den Zweck eine Verbindung über Bluetooth
* zu einem Perephärie-Gerät herzustellen. Dieses verfügt über eine Applikation,
* mit welcher die Schiene gesteuert werden kann.
* Momentan steuerbar, ist der Links- und Rechtslauf in zwei Geschwindigkeitsstufen,
* sowie die Stopp-Funktionalität.
*
* Ablauf des Programms:
* - Initialisierung aller Variablen und Konstanten
* - Initialiserung der Bluetooth-Verbindung und parametrieren dieser
* - Konfigurieren der Ein- und Ausgänge, zuweisen der Interrupt-Service-Routinen
* - Zyklisch wird danach abgearbeitet, ob etwas per Bluetooth geschickt wurde,
* dass die momentan aktiven Befehle an die Motorsteuerung weitergeleitet werden,
* falls eine Fahrtrichtung durch eine Endlagen ISR gesperrt wurde, ob der Abstand
* zu dieser Endlage bereits wieder groß genung ist um diese Fahrtrichtung wieder freizugeben.
*
*
* Anmerkungen zum Programm-Code:
* Die noch im Code befindlichen Funktionen der Seriellen Schnittstelle wurden zu Diagnosezwecken,
* dort belassen. Jedoch wurde alle zum Zweck eines schneller Ansprechverhaltens, auf Signale
* , sowie eine schneller Verarbeitungsgeschwindigkeit, auskommentiert.
*/
#include "Bluetooth.h" // Einbinden der Header-Datei für die Bluetooth-Funktionalität
#include "Encoder.h" // Einbinden der Header-Datei für die Encoder-Funktionalität
#include "Motorcontrol.h" // Einbinden der Header-Datei für die Motorsteuerung
BLEPeripheral Genuino101;
BLEService Positioniersystem("180A"); // BLE Posistioniersystem Service
BLEUnsignedCharCharacteristic Positionierbefehl("180B", BLERead | BLEWrite);
BLEUnsignedIntCharacteristic Sollposition("180C", BLERead | BLEWrite);
BLEUnsignedIntCharacteristic Istposition("180D", BLERead | BLENotify);
BLEUnsignedCharCharacteristic Zustand_BLE("180E", BLERead | BLENotify);
/******Encodervariablen********/
const uint8_t encoder0PinA = 2; //Definieren der Pins für die Encodereingänge
const uint8_t encoder0PinB = 4;
volatile unsigned int encoder0Pos = 2000; //Deklarieren der Zählvariable des Encoders
/******Motorvariablen**********/
const uint8_t PinRichtung = 12; //Definieren des Pins für die Drehrichtungssteuerung
const uint8_t PinGeschwindigkeit = 3; //Definieren des Pins für die Verfahrgeschwindigkeit
const uint8_t RefGeschw = 255; //Definieren der Verfahrgeschwindigkeit für die Referenzfahrt
/***** Endschalterparameter *******/
const uint8_t EndschL = 6;
const uint8_t EndschR = 7; //Definieren des Pins für das Endschalter/Referenzsignal
bool EndlageL = true; // Variable zum Speichern einer Erreichten Endlage
bool EndlageR = true;
unsigned int LastISR = 0;
bool Endl_ISR1 = false; //Hilfsvariable zur Erfassung ob EndlagenISR bereits ausgelöst wurde
const uint8_t Hyst=10; // Definieren der Strecke die vom Encoder erfasst werden muss,. bis eine Fahrtrichtung wieder
// freigegeben wird.
const uint8_t Wartezeit = 50;
void ISR_EndschL();
void ISR_EndschR();
/*****Positionierparameter*****/
char Befehl; //Deklarieren der Variablen für die Kommunikation und Motorsteuerung
int Sollpos;
int Istpos;
char Zustand;
bool ref = true; //Deklarieren und Initialisieren der Variable zur Überprüfung ob bereits refeneziert wurde
/*************** Initiaisierung ***********/
void setup() {
intitialiseBLE();
/**** Konfiguration Encoder Pins und Interrupts *****/
pinMode(encoder0PinA, INPUT);
digitalWrite(encoder0PinA, HIGH); // Aktivieren des pull-up Widerstandes
pinMode(encoder0PinB, INPUT);
digitalWrite(encoder0PinB, HIGH); // Aktivieren des pull-up Widerstandes
attachInterrupt(digitalPinToInterrupt(encoder0PinA), doEncoder, CHANGE); // Zuweisen des Interrupts der auf einen Pegelwechsel am EncoderPin A wartet
/**** Konfiguration Motor Pins *****/
pinMode(PinRichtung, OUTPUT); // Den Richtungspin als Ausgang definieren
digitalWrite(PinRichtung, LOW); // Den Richtungspin in einen definierten Zustand versetzen
pinMode(PinGeschwindigkeit, OUTPUT); // Den Geschwindigkeitspin als Ausgang definieren
analogWrite(PinGeschwindigkeit, 0); // Das Initial-PWM-Signal auf Geschwindigkeit = "0" setzen
/*** Konfiguration Endschalter Pins ****/
pinMode(EndschR, INPUT);
digitalWrite(EndschR, HIGH); // Aktivieren des pull-up Widerstandes
attachInterrupt(digitalPinToInterrupt(EndschR), ISR_EndschR, CHANGE); // Zuweisen der ISR auf den Interrupt-Pin
pinMode(EndschL, INPUT);
digitalWrite(EndschL, HIGH); // Aktivieren des pull-up Widerstandes
attachInterrupt(digitalPinToInterrupt(EndschL), ISR_EndschL, CHANGE); // Zuweisen der ISR auf den Interrupt-Pin
/***** Initialisierung Positionierparameter *****/
Befehl = 0; // Initialisierung der Parameter welche für die
Sollpos = 0; // Positionierung und Motorsteuerung notwendig sind
Istpos = Sollpos;
Zustand = 0;
//Serial.begin (9600);
}
/************* Schleife ***************/
void loop() {
communicate(Befehl, Sollpos, Istpos, Zustand); // Zyklisches Abrufen der via Bluetooth übermittelten Werte
motormain(Befehl, Sollpos, Istpos, Zustand); // Schreiben der ermittelten Werte in die Motorsteuerung
if ((EndlageL == false) || (EndlageR == false)) // Überprüfen ob Endlagen Flag gesetzt wurde
{
if (((LastISR + Hyst) < encoder0Pos) || ((LastISR - Hyst) > encoder0Pos)) // Wenn Endlagenflag gesetzt wurde und die Ist-Position ausreichend von
// der Endlage entfernt ist, freigeben des Positionierbetriebs in Richtung
{ EndlageL = true; // dieser Endlage
EndlageR = true;
// Serial.println("Reset Endlage:");
}
}
}
/**********Interrupt Service Routinen der Endschalter*************/
void ISR_EndschL(){ // ISR des linken Endschalters
if (EndlageL)
{
EndlageL = false; // Setzten des linken Endlagen-Flags
Befehl = 50; // Verfahrbefehl auf Stopp ändern
LastISR = encoder0Pos; // Speichern der aktuellen Position in LastISR
// Serial.println("Last ISR:");
// Serial.println(LastISR, DEC);
}
};
void ISR_EndschR(){ // ISR des rechten Endschalters
if (EndlageR)
{
EndlageR = false; // Setzten des rechten Endlagen-Flags
Befehl = 50; // Verfahrbefehl auf Stopp ändern
LastISR = encoder0Pos; // Speichern der aktuellen Position in LastISR
// Serial.println(LastISR, DEC);
}
};
|
#include "Macro.h"
#include <string>
#include "cocoa/CCObject.h"
#include <cocoa/CCGeometry.h>
#include <sprite_nodes/CCSprite.h>
#include "GameSkill.h"
#include "TypeDefine.h"
#include <vector>
#ifndef __GAMESPRITE_H__
#define __GAMESPRITE_H__
using std::vector;
namespace cocos2d
{
class CCSpriteBatchNode;
class CCNode;
class CCCallFuncND;
}
class GameAnimtion;
class GameBattleLayer;
enum ESpriteStatus //精灵的状态
{
ESS_Standing = 0, //站立
ESS_Attacking, //攻击
ESS_Runnig, //跑步
ESS_Dying, //死亡
ESS_Attacked, //被攻击
ESS_Cnt
};
enum ESpriteDir //精灵朝向
{
ESD_Left = 0,
ESD_Right,
ESD_Cnt
};
enum ESpriteCamp
{
ESC_Player = 0,
ESC_AI,
ESC_Cnt
};
class GameSprite : public cocos2d::CCNode
{
public:
GameSprite();
~GameSprite();
static GameSprite* create(int32t nSN);
bool initWithGame(int32t nSN);
int32t getSN() const {return m_nSN;}
bool setStatus(ESpriteStatus eStatus, cocos2d::CCCallFuncND* onStatusEnd = NULL);
ESpriteStatus getStatus() const {return m_eStatus;}
void setCamp(ESpriteCamp eCamp) { m_eCamp = eCamp;};
ESpriteCamp getCamp() {return m_eCamp;}
bool moveto(const cocos2d::CCPoint& postion, float fSpeed, cocos2d::CCCallFuncND* onMoveDone);
bool fightWith(GameSprite* pAim, cocos2d::CCCallFuncND* onFightDone);
bool setDir(ESpriteDir eDir);
ESpriteDir getDir() const {return m_eDir;}
const cocos2d::CCPoint& getSpritePosition() {return getPosition();}
float getSpritePositionX() {return getPositionX();}
GameSkill* selectASkill();//选择一个技能
void onHurt(int nPoint);
bool isDead();
void draw();
void drawHealthBar();
void doActivate(float dt);
void doDead(cocos2d::CCNode* pNode, void*);
void update(float delta);
void updateSkill(float dt);
//call back
void callback_skillEffectCastPlayOver(cocos2d::CCNode* pNode, void*p); //施展技能播放完成
void callback_skillEffectHitPlayOver(cocos2d::CCNode* pNode, void*p); //施展效果播放完成
void callback_skillEffectTrajectoryPlayOver(cocos2d::CCNode* pNode, void*p); //施展弹道效果播放完成
void callback_AttackEnd(cocos2d::CCNode* pNode, void*p);
void callback_palySkillEffect(cocos2d::CCNode* pNode, void*p);
void setSpriteScale(float f) {setScale(f);}
virtual bool isCanRun() {return true;}
virtual bool isHero() {return false;}
TAimMoveType getMoveType() const {return m_eMoveType;}
void onExit();
private:
GameSprite* selectAim(GameSkill* pSkill); //根据技能选中目标
GameSkill* getSkill(int32t nSkill);
protected:
std::string m_strSpriteFilePath;
ESpriteStatus m_eStatus; //精灵状态
GameAnimtion* m_pGameAnimation; //动画
ESpriteDir m_eDir; //精灵朝向
int m_nHP; //
int m_nCD; //
float m_fSpeed; //
int m_nCostNum; //消耗资源的数量
ESpriteCamp m_eCamp; //所属阵营
int m_nMaxHP;
vector<GameSkill*> m_pSkillList; //技能
bool m_bIsActive;
int32t m_nSN; //精灵归属SN
TAimMoveType m_eMoveType;
bool m_bIsInCastSkillStatus; //是否在施展技能的状态里
float m_fBirthTime;
#if _DEBUG
GameSkill* m_pCurrentSkill;
#endif
};
#endif // !__GAMESPRITE_H__
|
/*
* Perro.h
*
* Created on: Feb 19, 2013
* Author: j2deme
*/
#include <iostream>
using namespace std;
#ifndef PERRO_H_
#define PERRO_H_
class Perro {
public:
Perro();
Perro(string, string);
virtual ~Perro();
void ladrar();
const string& getColor() const;
void setColor(const string& color);
double getEstatura() const;
void setEstatura(double estatura);
const string& getNombre() const;
void setNombre(const string& nombre);
double getPeso() const;
void setPeso(double peso);
const string& getRaza() const;
void setRaza(const string& raza);
private:
string raza;
string nombre;
double peso;
double estatura;
string color;
};
#endif /* PERRO_H_ */
|
//
// Created by k on 12.04.18.
//
#ifndef EXERCISE03_EDGE_H
#define EXERCISE03_EDGE_H
class Node;
class Edge {
public:
Edge(Node *v, Node *w, int wt = 0, bool d = false);
Edge(bool isDirected, int weight, Node **endpoint);
bool isDirected;
int weight;
Node *endpoint[2];
};
#endif //EXERCISE03_EDGE_H
|
#include<omp.h>
#include <iostream>
#include "map.h"
using namespace std;
int main()
{
long long a[20];
for (int i = 1;i < 20;i++)
{
a[i] = i;
}
long long*B = map(a, 20, f);
for (int i = 1;i < 20;i++)
cout << B[i] << endl;
system("pause");
return 0;
}
|
#include "common\Singularity.Common.h"
namespace Singularity
{
IMPLEMENT_OBJECT_TYPE(Singularity, IDelegate, Singularity::Object);
}
|
#include <windows.h>
#include <GL/glut.h>
GLsizei ancho, alto;
float r = 0.0;
float g = 0.0;
float b = 0.0;
void init()
{
glClearColor (1.0, 1.0, 1.0, 1.0);
glColor3f(1.0, 0.0, 0.0);
}
void myReshape(GLsizei w, GLsizei h){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if(w<=h)
gluOrtho2D(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w);
else
gluOrtho2D(-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0);
glMatrixMode(GL_MODELVIEW);
glViewport(0,0,w,h);
ancho=w;
alto=h;
}
void menuColores(int entryID)
{
if (entryID == 1){
r=1.0;
g=0.0;
b=0.0;
}
if (entryID == 2){
r=0.0;
g=1.0;
b=0.0;
}
if (entryID == 3){
r=0.0;
g=0.0;
b=1.0;
}
glutPostRedisplay();
}
void crearMenus(){
glutCreateMenu(menuColores);
glutAddMenuEntry("Rojo", 1 );
glutAddMenuEntry("Verde",2 );
glutAddMenuEntry("Azul", 3 );
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
void myDisplay(){
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(r,g,b);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}
int main(){
glutCreateWindow("Menu Boton Derecho");
glutDisplayFunc(myDisplay);
glutReshapeFunc(myReshape);
init();
crearMenus();
glutMainLoop();
}
|
//rotate one by one clockwise
#include<iostream>
void rotate(int a[],int len,int d){
int temp=0;
for(int i=0;i<d;i++){
temp=a[0];
for (int j=1;j<len;j++){
a[j-1]=a[j];
}
a[len-1]=temp;
}
}
int main(){
int n=5;
int a[]={2,3,4,5,6};
int d=4;
rotate(a,n,d);
for(int i=0;i<5;i++){
std::cout<<a[i]<<"\n";
}
return 0;
}
|
// Convert this program to C++
// change to C++ io
// change to one line comments
// change defines of constants to const
// change array to vector<>
// inline any short function
//
#include<iostream>
#include<vector>
using namespace std;
const int N = 40;
inline void sum(int &s,vector<int> d){
for(int i=0;i<d.size();i++){
s = s+i;
}
}
int main(){
vector<int> data;
int s=0;
for(int i=0;i<N;i++){
data.push_back(i);
}
sum(s,data);
cout<<"The result of sum is : "<<s;
return 0;
}
|
//
// Recorder - a GPS logger app for Windows Mobile
// Copyright (C) 2006-2019 Michael Fink
//
/// \file BacklightManager.cpp Backlight manager
//
#include "StdAfx.h"
#include "BacklightManager.hpp"
#ifdef _WIN32_WCE
#include <pm.h>
#endif
CBacklightManager::CBacklightManager(EBacklightLevel enBacklightLevel) throw()
:m_hPower(NULL)
{
#ifdef _WIN32_WCE
m_hPower = SetPowerRequirement(_T("BKL1:"),
static_cast<CEDEVICE_POWER_STATE>(enBacklightLevel),
POWER_NAME, NULL, 0);
#endif
}
CBacklightManager::~CBacklightManager() throw()
{
#ifdef _WIN32_WCE
ReleasePowerRequirement(m_hPower);
#endif
}
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
/** @file
* @ingroup Mesh
* @brief
* A rectilinear mesh without uniform spacing between vertices.
*/
#ifndef POOMA_FIELD_MESH_RECTILINEARMESH_H
#define POOMA_FIELD_MESH_RECTILINEARMESH_H
//-----------------------------------------------------------------------------
// Includes:
//-----------------------------------------------------------------------------
#include "Engine/ConstantFunctionEngine.h" // Used in functors
#include "Engine/IndexFunctionEngine.h" // Used in functors
#include "Layout/INode.h" // Used in ctors
#include "Field/FieldEngine/FieldEnginePatch.h" // Used in ctors
#include "Field/Mesh/NoMesh.h" // Base class
#include "Field/FieldCentering.h" // Centering<Dim> inline
#include "Tiny/Vector.h" // Class member
//-----------------------------------------------------------------------------
/// Holds the data for a rectilinear mesh. That class has a ref-counted
/// instance of this class.
//-----------------------------------------------------------------------------
template <int Dim, class T>
class RectilinearMeshData : public NoMeshData<Dim>
{
public:
typedef Array<1, T> SpacingsType_t[Dim];
//---------------------------------------------------------------------------
// Constructors.
/// We provide a default constructor that creates the object with empty
/// domains. To be useful, this object must be replaced by another
/// version via assignment.
RectilinearMeshData()
{
// This space intentionally left blank.
}
/// This constructor fully constructs the object. It uses the layout to
/// compute domains and also initializes the origin and the spacings in each
/// coordinate direction. The indices in the layout refer to VERTEX
/// positions.
template<class Layout, class EngineTag>
RectilinearMeshData(
const Layout &layout,
const Vector<Dim, T> &origin,
const SpacingsType_t &spacings)
: NoMeshData<Dim>(layout),
origin_m(origin)
//spacings_m(spacings)
{
for (int i=0; i<Dim; i++) {
spacings_m[i].engine() = spacings[i].engine(); // init
spacings_m[i].engine().makeOwnCopy(); // FIXME? Do we want this?
Interval<1> I(layout.domain()[i]);
positions_m[i].engine() = Engine<1, T, Brick>(I);
positions_m[i](0) = origin_m(i);
// initialize from origin downward the ghost cells
for (int j=-1; j>=I.min(); j--)
positions_m[i](j) = positions_m[i].read(j+1) - spacings_m[i].read(j);
// initialize from origin upward
for (int j=1; j<=I.max(); j++)
positions_m[i](j) = positions_m[i].read(j-1) + spacings_m[i].read(j-1);
}
}
/// Constructor for constructing evenly spaced rectilinear meshes just
/// like UniformRectilinearMesh does.
template<class Layout>
RectilinearMeshData(
const Layout &layout,
const Vector<Dim, T> &origin,
const Vector<Dim, T> &spacings)
: NoMeshData<Dim>(layout),
origin_m(origin)
{
// for each dimension we allocate engines for spacings & positions
// and initialize them according to origin/spacings
for (int i=0; i<Dim; i++) {
Interval<1> I(layout.domain()[i]);
// allocate and assign spacings
spacings_m[i].engine() = Engine<1, T, Brick>(I);
spacings_m[i](I) = spacings(i); // no Array.all()
Pooma::blockAndEvaluate();
// allocate positions, assign origin
positions_m[i].engine() = Engine<1, T, Brick>(I);
positions_m[i](0) = origin_m(i);
// initialize from origin downward the ghost cells
for (int j=-1; j>=I.min(); j--)
positions_m[i](j) = positions_m[i].read(j+1) - spacings_m[i].read(j);
// initialize from origin upward
for (int j=1; j<=I.max(); j++)
positions_m[i](j) = positions_m[i].read(j-1) + spacings_m[i].read(j-1);
}
}
/// Copy constructor.
RectilinearMeshData(const RectilinearMeshData<Dim, T> &model)
: NoMeshData<Dim>(model),
origin_m(model.origin_m)
//spacings_m(model.spacings_m),
//positions_m(model.positions_m)
{
for (int i=0; i<Dim; i++) {
spacings_m[i].engine() = model.spacings_m[i].engine();
positions_m[i].engine() = model.positions_m[i].engine();
}
// This space intentionally left blank.
}
/// @name View constructors.
//@{
/// Interval view. This means that we simply need to adjust the
/// origin by the amount the view is offset from the model's physical
/// cell domain. We rely on the base class to do the heavy lifting
/// with respect to figuring out the domains correctly.
///
/// The Interval supplied must refer to VERTEX positions.
RectilinearMeshData(const RectilinearMeshData<Dim, T> &model,
const Interval<Dim> &d)
: NoMeshData<Dim>(d)
{
for (int i = 0; i < Dim; i++) {
// FIXME: Wheeee ;) (we cant store a BrickView...
// and still dont want to copy)
spacings_m[i].engine() = Engine<1, T, Brick>(&model.spacings_m[i](d[i])(0), d[i]);
positions_m[i].engine() = Engine<1, T, Brick>(&model.positions_m[i](d[i])(0), d[i]);
origin_m(i) = positions_m[i](d[i].min());
}
}
/// FieldEnginePatch view. We don't fiddle with the origin because we are not
/// making the domain zero-based.
///
/// The domain supplied by the FieldEnginePatch must refer to VERTEX
/// positions.
RectilinearMeshData(const RectilinearMeshData<Dim, T> &model,
const FieldEnginePatch<Dim> &p)
: NoMeshData<Dim>(model, p),
origin_m(model.origin_m),
spacings_m(model.spacings_m),
positions_m(model.spacings_m)
{
// FIXME: what does FieldEnginePatch do???
for (int i=0; i<Dim; i++) {
spacings_m[i].engine() = model.spacings_m[i].engine();
positions_m[i].engine() = model.positions_m[i].engine();
}
}
//@}
//---------------------------------------------------------------------------
/// Copy assignment operator.
RectilinearMeshData<Dim, T> &
operator=(const RectilinearMeshData<Dim, T> &rhs)
{
if (this != &rhs)
{
NoMeshData<Dim>::operator=(rhs);
origin_m = rhs.origin_m;
for (int i=0; i<Dim; i++) {
spacings_m[i].engine() = rhs.spacings_m[i].engine();
positions_m[i].engine() = rhs.positions_m[i].engine();
}
}
return *this;
}
//---------------------------------------------------------------------------
/// Empty destructor is fine. Note, however, that NoMeshData does not have
/// a virtual destructor. We must be careful to delete these puppies as
/// RectilinearMeshData.
~RectilinearMeshData() { }
//---------------------------------------------------------------------------
/// @name General accessors.
//@{
/// The mesh spacing.
inline const SpacingsType_t& spacings() const
{
return spacings_m;
}
/// The mesh vertex positions.
inline const SpacingsType_t& positions() const
{
return positions_m;
}
/// The mesh origin.
inline const Vector<Dim, T> &origin() const
{
return origin_m;
}
//@}
private:
/// Origin of mesh (coordinate vector of first vertex).
Vector<Dim, T> origin_m;
/// Spacings between vertices.
SpacingsType_t spacings_m;
/// Vertex positions.
SpacingsType_t positions_m;
};
///
/// RectilinearMesh is a rectilinear mesh sometimes called a
/// "cartesian product" or "tensor product" mesh. Each dimension has a
/// spacing value between every pair of vertices along that dimension;
/// these spacings can all be different.
///
template<int Dim, class T = POOMA_DEFAULT_POSITION_TYPE>
class RectilinearMesh
{
public:
//---------------------------------------------------------------------------
// Exported typedefs and enumerations.
/// The type of mesh points.
typedef Vector<Dim, T> PointType_t;
/// The type of vectors used to represent, for example, normals.
typedef Vector<Dim, T> VectorType_t;
/// The type used to store spacings.
typedef Array<1, T> SpacingsType_t[Dim];
/// The type T, used to represent, for example, volumes & areas, etc.
typedef T T_t;
/// The number of indices required to select a point in this mesh.
enum { dimensions = Dim };
//---------------------------------------------------------------------------
// Constructors.
/// We supply a default constructor, but it doesn't generate a useful mesh.
/// This is accomplished through assignment.
RectilinearMesh()
: data_m(new RectilinearMeshData<Dim, T>)
{
// This space intentionally left blank.
}
/// This constructor fully constructs the object. It uses the layout to
/// compute domains and also initializes the origin and the spacings in each
/// coordinate direction.
///
/// The Layout supplied must refer to VERTEX positions.
template<class Layout, class EngineTag>
inline RectilinearMesh(const Layout &layout,
const PointType_t &origin,
const SpacingsType_t &spacings)
: data_m(new RectilinearMeshData<Dim, T>(layout, origin, spacings))
{
}
/// Constructor compatible to UniformRectilinearMesh.
template<class Layout>
inline RectilinearMesh(const Layout &layout,
const PointType_t &origin,
const PointType_t &spacings)
: data_m(new RectilinearMeshData<Dim, T>(layout, origin, spacings))
{
}
template<class Layout>
inline RectilinearMesh(const Layout &layout)
: data_m(new RectilinearMeshData<Dim, T>(layout,
PointType_t(0),
PointType_t(1)))
{
}
/// Copy constructor.
inline RectilinearMesh(const RectilinearMesh<Dim, T> &model)
: data_m(model.data_m)
{
}
/// @name View constructors
/// These are the only possible views of this
/// mesh. Other views will make a NoMesh.
//@{
/// Interval view.
///
/// The Interval supplied must refer to VERTEX positions.
inline RectilinearMesh(const RectilinearMesh<Dim, T> &model,
const Interval<Dim> &d)
: data_m(new RectilinearMeshData<Dim, T>(*model.data_m, d))
{
}
/// INode view.
///
/// The INode supplied must refer to VERTEX positions.
inline RectilinearMesh(const RectilinearMesh<Dim, T> &model,
const INode<Dim> &i)
: data_m(new RectilinearMeshData<Dim, T>(*model.data_m, i.domain()))
{
}
/// FieldEnginePatch view.
///
/// The FieldEnginePatch supplied must refer to VERTEX positions.
inline RectilinearMesh(const RectilinearMesh<Dim, T> &model,
const FieldEnginePatch<Dim> &p)
: data_m(new RectilinearMeshData<Dim, T>(*model.data_m, p))
{
}
//@}
//---------------------------------------------------------------------------
/// Copy assignment operator.
inline RectilinearMesh<Dim, T> &
operator=(const RectilinearMesh<Dim, T> &rhs)
{
if (&rhs != this)
{
data_m = rhs.data_m;
}
return *this;
}
//---------------------------------------------------------------------------
/// Empty destructor is fine. The pointer to the data is ref-counted so its
/// lifetime is correctly managed.
~RectilinearMesh()
{
}
//---------------------------------------------------------------------------
/// @name Domain functions.
//@{
/// The vertex domain, as the mesh was constructed with.
inline const Interval<Dim> &physicalVertexDomain() const
{
return data_m->physicalVertexDomain();
}
/// Function that returns a domain adjusted to give the indices of the cells.
inline const Interval<Dim> &physicalCellDomain() const
{
return data_m->physicalCellDomain();
}
/// The total vertex domain, including mesh guard vertices.
inline const Interval<Dim> &totalVertexDomain() const
{
return data_m->totalVertexDomain();
}
/// The total cell domain, including mesh guard cells.
inline const Interval<Dim> &totalCellDomain() const
{
return data_m->totalCellDomain();
}
//@}
//---------------------------------------------------------------------------
/// @name General accessors.
//@{
/// The mesh spacing.
inline const SpacingsType_t &spacings() const
{
return data_m->spacings();
}
/// The mesh positions.
inline const SpacingsType_t &positions() const
{
return data_m->positions();
}
/// The mesh origin.
inline const Vector<Dim, T> &origin() const
{
return data_m->origin();
}
/// The cell containing a particular point.
inline Loc<Dim> cellContaining(const Vector<Dim, T> &point) const
{
/// FIXME
Loc<Dim> loc((0, Pooma::NoInit())); // Avoid a g++ parse error.
for (int i = 0; i < Dim; i++)
{
const T *start = &positions()[i](0);
const T *finish = start + positions()[i].physicalDomain()[i].length();
const T *p = std::lower_bound(start, finish, point(i));
#if POOMA_BOUNDS_CHECK
PInsist(p != finish,
"Rectilinear::cellContaining(): point is outside mesh.");
#endif
// The lower_bound function returns the first element that is not
// less than the point we're searching for.
int j = static_cast<int>(std::distance(start, p));
if (*p == point(i))
loc[i] = j;
else
loc[i] = j-1;
}
return loc;
}
/// The lower-left vertex associated with a given cell location.
inline Vector<Dim, T> vertexPosition(const Loc<Dim> &loc) const
{
Vector<Dim, T> point;
for (int i = 0; i < Dim; i++)
point(i) = positions()[i](loc[i]);
return point;
}
//@}
//---------------------------------------------------------------------------
/// Support for the positions() function. We need to provide a functor for
/// use with IndexFunction-engine. We also need to export the
/// PositionsEngineTag_t typedef and the positionsFunctor() member function,
/// which computes the positions using the centering point positions.
/// The indices passed in refer to cells.
class PositionsFunctor {
public:
/// Need to be able to default construct since we fill in the details
/// after the fact.
// WARNING! For Arrays to be initialized (copy constructed, assigned,
// etc.) correctly, even in the case of uninitialized targets
// we need to copy the engines explicitly rather than rely
// on the compiler generating correct copy constructors and
// assignment operators.
// FIXME! Technically we either can dump the copy constructor or the
// assignment operator.
PositionsFunctor() { }
PositionsFunctor(const RectilinearMesh<Dim, T> &m,
const Centering<Dim> &c)
: centering_m(c.position(0))
{
for (int i=0; i<Dim; i++) {
positions_m[i].engine() = m.positions()[i].engine();
spacings_m[i].engine() = m.spacings()[i].engine();
}
}
PositionsFunctor(const PositionsFunctor &m)
: centering_m(m.centering_m)
{
for (int i=0; i<Dim; i++) {
positions_m[i].engine() = m.positions_m[i].engine();
spacings_m[i].engine() = m.spacings_m[i].engine();
}
}
PositionsFunctor& operator=(const PositionsFunctor &m)
{
centering_m = m.centering_m;
for (int i=0; i<Dim; i++) {
positions_m[i].engine() = m.positions_m[i].engine();
spacings_m[i].engine() = m.spacings_m[i].engine();
}
return *this;
}
inline PointType_t operator()(int i0) const
{
return PointType_t(positions_m[0].read(i0) + spacings_m[0].read(i0)*centering_m(0));
}
inline PointType_t operator()(int i0, int i1) const
{
return PointType_t(positions_m[0].read(i0) + spacings_m[0].read(i0)*centering_m(0),
positions_m[1].read(i1) + spacings_m[1].read(i1)*centering_m(1));
}
inline PointType_t operator()(int i0, int i1, int i2) const
{
return PointType_t(positions_m[0].read(i0) + spacings_m[0].read(i0)*centering_m(0),
positions_m[1].read(i1) + spacings_m[1].read(i1)*centering_m(1),
positions_m[2].read(i2) + spacings_m[2].read(i2)*centering_m(2));
}
private:
SpacingsType_t positions_m;
SpacingsType_t spacings_m;
typename Centering<Dim>::Position centering_m;
};
typedef IndexFunction<PositionsFunctor> PositionsEngineTag_t;
void initializePositions(
Engine<Dim, PointType_t, PositionsEngineTag_t> &e,
const Centering<Dim> &c) const
{
e.setFunctor(PositionsFunctor(*this, c));
}
//---------------------------------------------------------------------------
/// Support for the outwardNormals() and coordinateNormals() functions.
/// We also need to export the NormalsEngineTag_t typedef and the
/// initializeNormals() member function, which sets the appropriate constant
/// value (since the normals exactly align with the coordinate axes).
/// The boolean value passed is true if we are asking for outward normals,
/// as opposed to coordinate normals. The indices passed in refer to cells.
typedef ConstantFunction NormalsEngineTag_t;
void initializeNormals(
Engine<Dim, VectorType_t, NormalsEngineTag_t> &e,
const Centering<Dim> &c,
bool outward = true) const
{
// Check some pre-conditions. We need there to be a single centering
// point and it must be face-centered.
PAssert(c.size() == 1);
PAssert(c.centeringType() == FaceType);
// Generate the normals. The coordinate normals are computed from
// 1 - orientation. Then, if we are on the near face, indicated by
// position == 0.0, we need to multiply by -1.0 if we are doing
// outward normals.
VectorType_t normal;
for (int i = 0; i < Dim; i++)
{
normal(i) = static_cast<T_t>(1 - c.orientation(0)[i].first());
if (outward && c.position(0)(i) == 0.0)
normal(i) *= static_cast<T_t>(-1);
}
e.setConstant(normal);
}
/// General "volume" functor: works for edges, faces and cells.
class GeneralVolumesFunctor {
public:
/// Need to be able to default construct since we fill in the details
/// after the fact.
GeneralVolumesFunctor() { }
GeneralVolumesFunctor(const RectilinearMesh<Dim, T> &m,
const Centering<Dim> &c)
: orientation_m(c.orientation(0))
{
for (int i=0; i<Dim; i++)
spacings_m[i].engine() = m.spacings()[i].engine();
}
GeneralVolumesFunctor(const GeneralVolumesFunctor &m)
: orientation_m(m.orientation_m)
{
for (int i=0; i<Dim; i++)
spacings_m[i].engine() = m.spacings_m[i].engine();
}
GeneralVolumesFunctor& operator=(const GeneralVolumesFunctor &m)
{
orientation_m = m.orientation_m;
for (int i=0; i<Dim; i++)
spacings_m[i].engine() = m.spacings_m[i].engine();
return *this;
}
inline T operator()(int i0) const
{
// It does not make sense to have a zero orientation for 1D
return spacings_m[0].read(i0);
}
inline T operator()(int i0, int i1) const
{
// It does not make sense to have all zero orientations for 2D
if (orientation_m[0].first() == 0)
return spacings_m[1].read(i1);
else if (orientation_m[1].first() == 0)
return spacings_m[0].read(i0);
else
return spacings_m[0].read(i0) * spacings_m[1].read(i1);
}
inline T operator()(int i0, int i1, int i2) const
{
// Could optimize as above
T volume = static_cast<T>(1);
if (orientation_m[0].first() != 0)
volume *= spacings_m[0].read(i0);
if (orientation_m[1].first() != 0)
volume *= spacings_m[1].read(i1);
if (orientation_m[2].first() != 0)
volume *= spacings_m[2].read(i2);
return volume;
}
private:
SpacingsType_t spacings_m;
typename Centering<Dim>::Orientation orientation_m;
};
//---------------------------------------------------------------------------
/// Support for the cellVolumes() function. We also need to export the
/// CellVolumesEngineTag_t typedef and the initializeCellVolumes() member
/// function, which sets the appropriate constant value for the volume.
/// The indices passed in refer to cells.
typedef IndexFunction<GeneralVolumesFunctor> CellVolumesEngineTag_t;
void initializeCellVolumes(
Engine<Dim, T, CellVolumesEngineTag_t> &e,
const Centering<Dim> &c) const
{
// Check some pre-conditions. We need there to be a single centering
// point and it must be cell-centered.
PAssert(c.size() == 1);
PAssert(c.centeringType() == CellType);
// Use the general functor to do the job.
e.setFunctor(GeneralVolumesFunctor(*this, c));
}
//---------------------------------------------------------------------------
/// Support for the faceAreas() function. We also need to export the
/// FaceAreasEngineTag_t typedef and the initializeFaceAreas() member
/// function, which sets the appropriate constant face area value.
/// The indices passed in refer to cells.
typedef IndexFunction<GeneralVolumesFunctor> FaceAreasEngineTag_t;
void initializeFaceAreas(
Engine<Dim, T, FaceAreasEngineTag_t> &e,
const Centering<Dim> &c) const
{
// Check some pre-conditions. We need there to be a single centering
// point and it must be face-centered.
PAssert(c.size() == 1);
PAssert(c.centeringType() == FaceType);
// Use the general functor to do the job.
e.setFunctor(GeneralVolumesFunctor(*this, c));
}
//---------------------------------------------------------------------------
/// Support for the edgeLengths() function. We also need to export the
/// EdgeLengthsEngineTag_t typedef and the initializeEdgeLengths() member
/// function, which sets the appropriate constant edge length value.
/// The indices passed in refer to cells.
typedef IndexFunction<GeneralVolumesFunctor> EdgeLengthsEngineTag_t;
void initializeEdgeLengths(
Engine<Dim, T, EdgeLengthsEngineTag_t> &e,
const Centering<Dim> &c) const
{
// Check some pre-conditions. We need there to be a single centering
// point and it must be edge-centered.
PAssert(c.size() == 1);
PAssert(c.centeringType() == EdgeType);
// Use the general functor to do the job.
e.setFunctor(GeneralVolumesFunctor(*this, c));
}
private:
/// Our data, stored as a ref-counted pointer to simplify memory management.
RefCountedPtr<RectilinearMeshData<Dim, T> > data_m;
};
#endif // POOMA_FIELD_MESH_RECTILINEARMESH_H
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: RectilinearMesh.h,v $ $Author: richi $
// $Revision: 1.4 $ $Date: 2004/11/23 16:20:31 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Inform non-template definitions.
//-----------------------------------------------------------------------------
// POOMA include files
#include "Utilities/Inform.h"
#include "Utilities/PAssert.h"
// string-based ostream subclass include files
#include <iomanip>
#include <fstream>
#if POOMA_NO_STRINGSTREAM
#include <strstream>
#else
#include <sstream>
#endif
// the size of the Inform internal character buffer,
// for those implementations which do not have ostringstream
const unsigned int Inform::bufSize = 32000;
// A mutex used to protect printing to the output stream, since that can
// be shared among many Inform's
Pooma::Mutex_t Inform::outputMutex_s;
// the current context ID and number of contexts for all Inform
// objects. By default it looks like we're running on context 0
// of 1 total contexts. But this can be changed by the underlying
// run-time system.
Inform::Context_t Inform::context_s = 0;
Inform::Context_t Inform::nContexts_s = 1;
//-----------------------------------------------------------------------------
// The InformStream class, defined here because it is only used internally
// by Inform. InformStream stores information about a single stream
// connection. The information is: ostream pointer, whether it needs to
// be closed by us, the destination context, and output level threshhold.
//-----------------------------------------------------------------------------
class InformStream
{
public:
// Constructor which takes the ostream to use and the destination context
InformStream(std::ostream *s, Inform::Context_t oc)
: stream_m(s), close_m(false), outputContext_m(oc), level_m(0)
{
PAssert(s != 0);
}
// Constructor which takes a filename, and opens a file.
InformStream(const char *fname, int mode, Inform::Context_t oc)
: stream_m(0), close_m(true), outputContext_m(oc), level_m(0)
{
PAssert(fname != 0);
PAssert(mode == Inform::out || mode == Inform::app);
if (oc < 0 || oc == Inform::context()) {
if (mode == Inform::out)
stream_m = new std::ofstream(fname, std::ios::out);
else
stream_m = new std::ofstream(fname, std::ios::app);
}
}
// Destructor: close the stream, if necessary.
~InformStream()
{
if (close_m && stream_m != 0)
delete stream_m;
}
// get or set the output context
Inform::Context_t outputContext() const
{
return outputContext_m;
}
void setOutputContext(Inform::Context_t val)
{
outputContext_m = val;
}
// get or set the output threshold
Inform::Level_t outputLevel() const
{
return level_m;
}
void setOutputLevel(Inform::Level_t val)
{
level_m = val;
}
// print out the given message to the output stream
void print(Inform::Level_t l, const std::string &prefix, const char *msg)
{
if (shouldPrint(l))
{
// Print the prefix, if necessary.
if (prefix.length() > 0)
{
// First print the base part of the prefix
*stream_m << prefix;
// If there are more than 1 contexts, insert the context ID
// into the prefix:
if (Inform::numContexts() > 1)
{
if ((outputContext_m == Inform::allContexts) ||
(outputContext_m == Inform::context()))
{
*stream_m << "{" << Inform::context() << "}";
}
}
// Add on the "> ":
*stream_m << "> ";
}
// Then print the rest of the message and flush the stream
*stream_m << msg << "\n";
stream_m->flush();
}
}
private:
// The stream to manage.
std::ostream *stream_m;
// Do we need to close (delete) this stream when done?
bool close_m;
// Which context should we write to.
Inform::Context_t outputContext_m;
// The output message threshold level
Inform::Level_t level_m;
// A boolean function that determines if we should print out the
// current message based on:
// 1. The output level
// 2. The current context settings
// 3. Do we have somewhere to print to
bool shouldPrint(Inform::Level_t level)
{
PAssert(level >= 0);
// Definitely do not print if there is no stream
if (stream_m == 0)
return false;
// Do not print if the specified message level does not match
// our output level requirements, or we're on the wrong context.
return (level <= level_m &&
(outputContext_m == Inform::context() ||
outputContext_m == Inform::allContexts));
}
};
//-----------------------------------------------------------------------------
// Inform endl manipulator. When 'endl' is inserted into an Inform stream,
// it causes the current message to be printed, along with a newline.
//
// Inform flush manipulator. Just calls 'flush' on the Inform.
//
// Inform lock and unlock manipulator. Just calls the corresponding
// routines to lock access to the stream.
//-----------------------------------------------------------------------------
namespace std {
Inform &endl(Inform &inf)
{
inf.flush();
return inf;
}
Inform &flush(Inform &inf)
{
inf.flush();
return inf;
}
Inform &lock(Inform &inf)
{
inf.lock();
return inf;
}
Inform &unlock(Inform &inf)
{
inf.unlock();
return inf;
}
} // namespace std
//-----------------------------------------------------------------------------
// Create an Inform object which will print to just standard out with
// the given prefix and destination context (initially these are
// defaulted to 'no prefix' and 'just print on context 0').
// The initial output stream has an ID value of '0'.
//-----------------------------------------------------------------------------
Inform::Inform(const char *prefix, Context_t outputContext)
: prefix_m(""), outputContext_m(outputContext), level_m(0),
message_m(0), buffer_m(0), nextID_m(0)
{
// Create a connection to cout
open(outputContext);
// Initialize our internal formatting buffer
setup(prefix);
}
//-----------------------------------------------------------------------------
// Create an Inform object which will print to a file with the given
// name, opened either for overwrite or append operations. The first
// and last arguments give the prefix and destination context as usual.
// If the destination context is 'allContexts', then a file will be
// created by all contexts. If the destination context is just a single
// context, then only that context will have a file opened.
// The destination context for a file cannot be changed once it is set
// in the constructor or 'open' call.
// The initial output stream has an ID value of '0'.
//-----------------------------------------------------------------------------
Inform::Inform(const char *prefix, const char *fname, int writemode,
Context_t outputContext)
: prefix_m(""), outputContext_m(outputContext), level_m(0),
message_m(0), buffer_m(0), nextID_m(0)
{
// Create a connection to the given file
open(fname, writemode, outputContext);
// Initialize our internal formatting buffer
setup(prefix);
}
//-----------------------------------------------------------------------------
// Create an Inform object which will print to the given ostream,
// with a prefix and destination context. The destination context
// for this case CAN be changed later.
// The initial output stream has an ID value of '0'.
//-----------------------------------------------------------------------------
Inform::Inform(const char *prefix, std::ostream &outstream,
Context_t outputContext)
: prefix_m(""), outputContext_m(outputContext), level_m(0),
message_m(0), buffer_m(0), nextID_m(0)
{
// Create a connection to the given file
open(outstream, outputContext);
// Initialize our internal formatting buffer
setup(prefix);
}
//-----------------------------------------------------------------------------
// The Inform destructor will flush all existing buffers, and
// close all files that it opened.
//-----------------------------------------------------------------------------
Inform::~Inform()
{
// delete all the existing connections
close();
// delete the existing output buffer stream
delete message_m;
// delete the storage buffer, if necessary
if (buffer_m != 0)
delete [] buffer_m;
}
//-----------------------------------------------------------------------------
// Open a connection to a new stream, and return the ID for that
// stream. The ID should be used in other manipulator calls, such
// as 'outputLevel(ID_t)'. There are three forms for open, which
// correspond to the three types of constructors without prefixes:
// 1. output context: open new standard-out connection.
// 2. filename + output mode + output context: open new file.
// 3. ostream + output context: open new ostream connection.
// Upon successful completion, open returns the ID for the new connection.
// If an error occurs, open returns (-1).
//-----------------------------------------------------------------------------
Inform::ID_t Inform::open(Context_t oc)
{
streams_m.insert(Value_t(nextID_m, new InformStream(&std::cout, oc)));
return nextID_m++;
}
Inform::ID_t Inform::open(const char *fname, int mode, Context_t oc)
{
streams_m.insert(Value_t(nextID_m, new InformStream(fname, mode, oc)));
return nextID_m++;
}
Inform::ID_t Inform::open(std::ostream &outstream, Context_t oc)
{
streams_m.insert(Value_t(nextID_m, new InformStream(&outstream, oc)));
return nextID_m++;
}
//-----------------------------------------------------------------------------
// Close the specifed connection.
//-----------------------------------------------------------------------------
void Inform::close(ID_t id)
{
// find the proper connection to close
iterator s = streams_m.find(id);
PAssert(s != streams_m.end());
// delete the connection, and remove it from the map
delete ((*s).second);
streams_m.erase(s);
}
//-----------------------------------------------------------------------------
// Close all connections.
//-----------------------------------------------------------------------------
void Inform::close()
{
// delete all the existing connections
for (iterator a = streams_m.begin(); a != streams_m.end(); ++a)
delete ((*a).second);
// remove all the elements
streams_m.erase(streams_m.begin(), streams_m.end());
}
//-----------------------------------------------------------------------------
// Return the current value for the output threshhold level, which is
// the highest level of message that will be printed. If this is < 0,
// no messages will be printed. You must specify which stream to return
// the settings for, which has a default value of '0'.
//-----------------------------------------------------------------------------
Inform::Level_t Inform::outputLevel(ID_t id) const
{
// Find the proper connection
InformStream *s = findStream(id);
PAssert(s != 0);
// Return the output level
return s->outputLevel();
}
//-----------------------------------------------------------------------------
// Change the output threshhold level for the output stream specified
// in the second argument. If the first argument is < 0, then this
// effectively turns off that stream, since a message level cannot be
// < 0. The 'off' enumeration can be used for the first argument to
// indicate this. If no ID is given, change the setting for all.
//-----------------------------------------------------------------------------
void Inform::setOutputLevel(Level_t newval, ID_t id)
{
// Find the proper connection
InformStream *s = findStream(id);
PAssert(s != 0);
// Change the output level
s->setOutputLevel(newval);
}
void Inform::setOutputLevel(Level_t newval)
{
for (iterator a = streams_m.begin(); a != streams_m.end(); ++a)
(*a).second->setOutputLevel(newval);
}
//-----------------------------------------------------------------------------
// Return the current value for the destination context, for the specified
// ostream connection. The value is either >= 0, indicating a single
// destination context, or it is < 0, indicating 'all contexts'.
//-----------------------------------------------------------------------------
Inform::Context_t Inform::outputContext(ID_t id) const
{
// Find the proper connection
InformStream *s = findStream(id);
PAssert(s != 0);
// Return the output context
return s->outputContext();
}
//-----------------------------------------------------------------------------
// Change the destination context for the specified ostream connection.
// Note that for some destinations, the context cannot be changed.
// If ID is not given, change the context for all.
//-----------------------------------------------------------------------------
void Inform::setOutputContext(Context_t outputContext, ID_t id)
{
// Find the proper connection
InformStream *s = findStream(id);
PAssert(s != 0);
// Change the output context
s->setOutputContext(outputContext);
}
void Inform::setOutputContext(Context_t outputContext)
{
for (iterator a = streams_m.begin(); a != streams_m.end(); ++a)
(*a).second->setOutputContext(outputContext);
}
//-----------------------------------------------------------------------------
// Print out the current message to the active streams.
//-----------------------------------------------------------------------------
void Inform::flush()
{
// terminate the existing string
*message_m << std::ends;
outputMutex_s.lock();
// get a pointer to the formatted string buffer
#if POOMA_NO_STRINGSTREAM
std::string formatstr = buffer_m;
#else
std::string formatstr = message_m->str();
#endif
// create a buffer that we can modify
char *outputbuf = new char[formatstr.length() + 2];
// scan through the lines of the buffer, as separated by newlines,
// and print out each line
char *endbuf = outputbuf;
char *begbuf = outputbuf;
const char *formatbuf = formatstr.c_str();
do {
// advance endbuf to next set of endlines
while (*formatbuf != '\n' && *formatbuf != '\0')
*endbuf++ = *formatbuf++;
// make sure there is a string terminator
*endbuf = '\0';
// if there was a newline, skip it in the formatbuf
if (*formatbuf == '\n')
++formatbuf;
// go through each connection, and print the prefix and message.
for (iterator a = streams_m.begin(); a != streams_m.end(); ++a)
(*a).second->print(level_m, prefix_m, begbuf);
// skip begbuf to the beginning of the next line
begbuf = endbuf;
} while (*formatbuf != '\0');
// reset the string buffer
#if POOMA_NO_STRINGSTREAM
message_m->seekp(0, std::ios::beg);
#else
message_m->str( std::string() );
#endif
// delete the buffer copy and we're done
delete [] outputbuf;
outputMutex_s.unlock();
}
//-----------------------------------------------------------------------------
// Return a pointer to the InformStream with the given ID. If it is
// not found, 0 is returned.
//-----------------------------------------------------------------------------
InformStream *Inform::findStream(ID_t id) const
{
// try to find the ID in the map
const_iterator s = streams_m.find(id);
// return either the pointer, or 0 if not found
if (s != streams_m.end())
return (*s).second;
else
return 0;
}
//-----------------------------------------------------------------------------
// Perform setup information needed by each constructor
//-----------------------------------------------------------------------------
void Inform::setup(const char *prefix)
{
// Initialize the prefix string
setPrefix(prefix);
#if POOMA_NO_STRINGSTREAM
// create an ostrstream, using a fixed-size character buffer for storage
buffer_m = new char[Inform::bufSize];
*buffer_m = '\0';
message_m = new std::ostrstream(buffer_m, Inform::bufSize, std::ios::out);
#else
// create an ostringstream, which uses its own string for storage
buffer_m = 0;
message_m = new std::ostringstream(std::ios::out);
#endif
}
//-----------------------------------------------------------------------------
// Change the prefix string to the given value
//-----------------------------------------------------------------------------
void Inform::setPrefix(const char *prefix)
{
// Initialize the prefix string. If prefix is empty or null, do not use a
// prefix at all. Otherwise, make it of the form "prefix{context}> "
if (prefix == 0 || *prefix == '\0')
prefix_m = "";
else
prefix_m = prefix;
}
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: Inform.cmpl.cpp,v $ $Author: richard $
// $Revision: 1.21 $ $Date: 2004/11/01 18:17:17 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.Devices.I2c.0.h"
#include "Windows.Devices.I2c.Provider.0.h"
#include "Windows.Foundation.0.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Devices::I2c {
struct I2cTransferResult
{
winrt::Windows::Devices::I2c::I2cTransferStatus Status;
uint32_t BytesTransferred;
};
}
namespace Windows::Devices::I2c {
using I2cTransferResult = ABI::Windows::Devices::I2c::I2cTransferResult;
}
namespace ABI::Windows::Devices::I2c {
struct __declspec(uuid("f2db1307-ab6f-4639-a767-54536dc3460f")) __declspec(novtable) II2cConnectionSettings : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_SlaveAddress(int32_t * value) = 0;
virtual HRESULT __stdcall put_SlaveAddress(int32_t value) = 0;
virtual HRESULT __stdcall get_BusSpeed(winrt::Windows::Devices::I2c::I2cBusSpeed * value) = 0;
virtual HRESULT __stdcall put_BusSpeed(winrt::Windows::Devices::I2c::I2cBusSpeed value) = 0;
virtual HRESULT __stdcall get_SharingMode(winrt::Windows::Devices::I2c::I2cSharingMode * value) = 0;
virtual HRESULT __stdcall put_SharingMode(winrt::Windows::Devices::I2c::I2cSharingMode value) = 0;
};
struct __declspec(uuid("81b586b3-9693-41b1-a243-ded4f6e66926")) __declspec(novtable) II2cConnectionSettingsFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_Create(int32_t slaveAddress, Windows::Devices::I2c::II2cConnectionSettings ** value) = 0;
};
struct __declspec(uuid("c48ab1b2-87a0-4166-8e3e-b4b8f97cd729")) __declspec(novtable) II2cController : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_GetDevice(Windows::Devices::I2c::II2cConnectionSettings * settings, Windows::Devices::I2c::II2cDevice ** device) = 0;
};
struct __declspec(uuid("40fc0365-5f05-4e7e-84bd-100db8e0aec5")) __declspec(novtable) II2cControllerStatics : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_GetControllersAsync(Windows::Devices::I2c::Provider::II2cProvider * provider, Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::I2c::I2cController>> ** operation) = 0;
virtual HRESULT __stdcall abi_GetDefaultAsync(Windows::Foundation::IAsyncOperation<Windows::Devices::I2c::I2cController> ** operation) = 0;
};
struct __declspec(uuid("8636c136-b9c5-4f70-9449-cc46dc6f57eb")) __declspec(novtable) II2cDevice : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_DeviceId(hstring * value) = 0;
virtual HRESULT __stdcall get_ConnectionSettings(Windows::Devices::I2c::II2cConnectionSettings ** value) = 0;
virtual HRESULT __stdcall abi_Write(uint32_t __bufferSize, uint8_t * buffer) = 0;
virtual HRESULT __stdcall abi_WritePartial(uint32_t __bufferSize, uint8_t * buffer, Windows::Devices::I2c::I2cTransferResult * result) = 0;
virtual HRESULT __stdcall abi_Read(uint32_t __bufferSize, uint8_t * buffer) = 0;
virtual HRESULT __stdcall abi_ReadPartial(uint32_t __bufferSize, uint8_t * buffer, Windows::Devices::I2c::I2cTransferResult * result) = 0;
virtual HRESULT __stdcall abi_WriteRead(uint32_t __writeBufferSize, uint8_t * writeBuffer, uint32_t __readBufferSize, uint8_t * readBuffer) = 0;
virtual HRESULT __stdcall abi_WriteReadPartial(uint32_t __writeBufferSize, uint8_t * writeBuffer, uint32_t __readBufferSize, uint8_t * readBuffer, Windows::Devices::I2c::I2cTransferResult * result) = 0;
};
struct __declspec(uuid("91a33be3-7334-4512-96bc-fbae9459f5f6")) __declspec(novtable) II2cDeviceStatics : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_GetDeviceSelector(hstring * value) = 0;
virtual HRESULT __stdcall abi_GetDeviceSelectorFromFriendlyName(hstring friendlyName, hstring * value) = 0;
virtual HRESULT __stdcall abi_FromIdAsync(hstring deviceId, Windows::Devices::I2c::II2cConnectionSettings * settings, Windows::Foundation::IAsyncOperation<Windows::Devices::I2c::I2cDevice> ** operation) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::Devices::I2c::I2cConnectionSettings> { using default_interface = Windows::Devices::I2c::II2cConnectionSettings; };
template <> struct traits<Windows::Devices::I2c::I2cController> { using default_interface = Windows::Devices::I2c::II2cController; };
template <> struct traits<Windows::Devices::I2c::I2cDevice> { using default_interface = Windows::Devices::I2c::II2cDevice; };
}
namespace Windows::Devices::I2c {
template <typename D>
struct WINRT_EBO impl_II2cConnectionSettings
{
int32_t SlaveAddress() const;
void SlaveAddress(int32_t value) const;
Windows::Devices::I2c::I2cBusSpeed BusSpeed() const;
void BusSpeed(Windows::Devices::I2c::I2cBusSpeed value) const;
Windows::Devices::I2c::I2cSharingMode SharingMode() const;
void SharingMode(Windows::Devices::I2c::I2cSharingMode value) const;
};
template <typename D>
struct WINRT_EBO impl_II2cConnectionSettingsFactory
{
Windows::Devices::I2c::I2cConnectionSettings Create(int32_t slaveAddress) const;
};
template <typename D>
struct WINRT_EBO impl_II2cController
{
Windows::Devices::I2c::I2cDevice GetDevice(const Windows::Devices::I2c::I2cConnectionSettings & settings) const;
};
template <typename D>
struct WINRT_EBO impl_II2cControllerStatics
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::I2c::I2cController>> GetControllersAsync(const Windows::Devices::I2c::Provider::II2cProvider & provider) const;
Windows::Foundation::IAsyncOperation<Windows::Devices::I2c::I2cController> GetDefaultAsync() const;
};
template <typename D>
struct WINRT_EBO impl_II2cDevice
{
hstring DeviceId() const;
Windows::Devices::I2c::I2cConnectionSettings ConnectionSettings() const;
void Write(array_view<const uint8_t> buffer) const;
Windows::Devices::I2c::I2cTransferResult WritePartial(array_view<const uint8_t> buffer) const;
void Read(array_view<uint8_t> buffer) const;
Windows::Devices::I2c::I2cTransferResult ReadPartial(array_view<uint8_t> buffer) const;
void WriteRead(array_view<const uint8_t> writeBuffer, array_view<uint8_t> readBuffer) const;
Windows::Devices::I2c::I2cTransferResult WriteReadPartial(array_view<const uint8_t> writeBuffer, array_view<uint8_t> readBuffer) const;
};
template <typename D>
struct WINRT_EBO impl_II2cDeviceStatics
{
hstring GetDeviceSelector() const;
hstring GetDeviceSelector(hstring_view friendlyName) const;
Windows::Foundation::IAsyncOperation<Windows::Devices::I2c::I2cDevice> FromIdAsync(hstring_view deviceId, const Windows::Devices::I2c::I2cConnectionSettings & settings) const;
};
}
namespace impl {
template <> struct traits<Windows::Devices::I2c::II2cConnectionSettings>
{
using abi = ABI::Windows::Devices::I2c::II2cConnectionSettings;
template <typename D> using consume = Windows::Devices::I2c::impl_II2cConnectionSettings<D>;
};
template <> struct traits<Windows::Devices::I2c::II2cConnectionSettingsFactory>
{
using abi = ABI::Windows::Devices::I2c::II2cConnectionSettingsFactory;
template <typename D> using consume = Windows::Devices::I2c::impl_II2cConnectionSettingsFactory<D>;
};
template <> struct traits<Windows::Devices::I2c::II2cController>
{
using abi = ABI::Windows::Devices::I2c::II2cController;
template <typename D> using consume = Windows::Devices::I2c::impl_II2cController<D>;
};
template <> struct traits<Windows::Devices::I2c::II2cControllerStatics>
{
using abi = ABI::Windows::Devices::I2c::II2cControllerStatics;
template <typename D> using consume = Windows::Devices::I2c::impl_II2cControllerStatics<D>;
};
template <> struct traits<Windows::Devices::I2c::II2cDevice>
{
using abi = ABI::Windows::Devices::I2c::II2cDevice;
template <typename D> using consume = Windows::Devices::I2c::impl_II2cDevice<D>;
};
template <> struct traits<Windows::Devices::I2c::II2cDeviceStatics>
{
using abi = ABI::Windows::Devices::I2c::II2cDeviceStatics;
template <typename D> using consume = Windows::Devices::I2c::impl_II2cDeviceStatics<D>;
};
template <> struct traits<Windows::Devices::I2c::I2cConnectionSettings>
{
using abi = ABI::Windows::Devices::I2c::I2cConnectionSettings;
static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.I2c.I2cConnectionSettings"; }
};
template <> struct traits<Windows::Devices::I2c::I2cController>
{
using abi = ABI::Windows::Devices::I2c::I2cController;
static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.I2c.I2cController"; }
};
template <> struct traits<Windows::Devices::I2c::I2cDevice>
{
using abi = ABI::Windows::Devices::I2c::I2cDevice;
static constexpr const wchar_t * name() noexcept { return L"Windows.Devices.I2c.I2cDevice"; }
};
}
}
|
#include "mpi_centralized_barrier.h"
//#include "mpi.h"
// this line is for local implementation
#include "/usr/lib/openmpi/include/mpi.h"
#include <stdio.h>
Mpi_Centralized_Barrier::Mpi_Centralized_Barrier(bool* sense, int *pnum){
local_sense = true;
*sense = true;
num_processors = *pnum;
}
void Mpi_Centralized_Barrier::sync(int* pid, bool* sense){
local_sense = !local_sense;
if (*pid != 0){
MPI_Send(&local_sense, 1, MPI_C_BOOL, 0, 0, MPI_COMM_WORLD);
}
else{
bool local_sense_buf[num_processors];
local_sense_buf[0] = local_sense;
for (int i=1; i<num_processors; i++){
MPI_Recv(local_sense_buf+i, 1, MPI_C_BOOL, i, 0, MPI_COMM_WORLD, NULL);
//printf("root 0 recevied from %i\n", i);
}
/*
for (int i=0; i<num_processors; i++){
printf("%d ", local_sense_buf[i]);
}
printf("\n");
*/
*sense = local_sense;
}
MPI_Bcast(sense, 1, MPI_C_BOOL, 0, MPI_COMM_WORLD);
while(*sense != local_sense);
}
|
/***********************************************************************
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Ogre/Renderer.h"
#ifndef CEGUI_USE_OGRE_TEXTURE_GPU
#include "CEGUI/RendererModules/Ogre/RenderTarget.h"
#include "CEGUI/RendererModules/Ogre/GeometryBuffer.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/RenderQueue.h"
#include <OgreRenderSystem.h>
#include <OgreRenderTarget.h>
#include <OgreCamera.h>
#include <OgreViewport.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
// Start of CEGUI namespace section
namespace CEGUI
{
OgreRenderTarget::OgreRenderTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
d_owner(owner),
d_renderSystem(rs),
d_renderTarget(0),
d_viewport(0),
d_ogreViewportDimensions(0, 0, 0, 0),
d_viewportValid(false)
{
}
OgreRenderTarget::~OgreRenderTarget()
{
delete d_viewport;
}
void OgreRenderTarget::setOgreViewportDimensions(const Rectf& area)
{
d_ogreViewportDimensions = area;
if (d_viewport)
updateOgreViewportDimensions(d_viewport->getTarget());
d_viewportValid = false;
}
void OgreRenderTarget::updateOgreViewportDimensions(
const Ogre::RenderTarget* const rt)
{
if (rt)
{
if(d_viewport)
d_viewport->setDimensions(
d_ogreViewportDimensions.left() / rt->getWidth(),
d_ogreViewportDimensions.top() / rt->getHeight(),
d_ogreViewportDimensions.getWidth() / rt->getWidth(),
d_ogreViewportDimensions.getHeight() / rt->getHeight());
}
}
void OgreRenderTarget::activate()
{
if (!RenderTarget::d_matrixValid)
updateMatrix();
if (!d_viewportValid)
updateViewport();
d_renderSystem._setViewport(d_viewport);
d_owner.setViewProjectionMatrix(RenderTarget::d_matrix);
#ifdef CEGUI_USE_OGRE_HLMS
d_owner.initialiseRenderStateSettings(d_renderTarget);
#else
d_owner.initialiseRenderStateSettings();
#endif
RenderTarget::activate();
}
void OgreRenderTarget::draw(const GeometryBuffer& buffer, std::uint32_t drawModeMask)
{
buffer.draw(drawModeMask);
}
void OgreRenderTarget::draw(const RenderQueue& queue, std::uint32_t drawModeMask)
{
queue.draw(drawModeMask);
}
void OgreRenderTarget::updateMatrix() const
{
if (d_owner.usesOpenGL())
RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() );
else if (d_owner.usesDirect3D())
RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForDirect3D() );
else
throw RendererException("An unsupported RenderSystem is being used by Ogre. Please contact the CEGUI team.");
}
void OgreRenderTarget::updateViewport()
{
if (!d_viewport)
{
#ifdef CEGUI_USE_OGRE_COMPOSITOR2
d_viewport = OGRE_NEW Ogre::Viewport(d_renderTarget, 0, 0, 1, 1);
#else
d_viewport = OGRE_NEW Ogre::Viewport(0, d_renderTarget, 0, 0, 1, 1, 0);
#endif // CEGUI_USE_OGRE_COMPOSITOR2
updateOgreViewportDimensions(d_renderTarget);
}
d_viewport->_updateDimensions();
d_viewportValid = true;
}
OgreRenderer& OgreRenderTarget::getOwner()
{
return d_owner;
}
void OgreRenderTarget::setArea(const Rectf& area)
{
setOgreViewportDimensions(area);
RenderTarget::setArea(area);
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
#endif // CEGUI_USE_OGRE_TEXTURE_GPU
|
/***************************************************************************
matrix.cpp - description
-------------------
begin : Tue Jul 24 2002
copyright : (C) 2002 by Marco Bubke
email : marco@bubke.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation; 2.1 of the License. *
* * *
***************************************************************************/
#include "matrix.h"
#include "math.h"
namespace Ah {
Matrix::Matrix()
: ReferenceCounter(), pivotx(0), pivoty(0)
{
setIdentity();
}
void Matrix::setIdentity()
{
matrix[0] = 1.0;
matrix[1] = 0.0;
matrix[2] = 0.0;
matrix[3] = 0.0;
matrix[4] = 0.0;
matrix[5] = 1.0;
matrix[6] = 0.0;
matrix[7] = 0.0;
matrix[8] = 0.0;
matrix[9] = 0.0;
matrix[10] = 1.0;
matrix[11] = 0.0;
matrix[12] = 0.0;
matrix[13] = 0.0;
matrix[14] = 0.0;
matrix[15] = 1.0;
}
void Matrix::scale(float x, float y)
{
matrix[0] *= x;
matrix[1] *= x;
matrix[4] *= y;
matrix[5] *= y;
}
void Matrix::scale(float factor)
{
matrix[0] *= factor;
matrix[1] *= factor;
matrix[4] *= factor;
matrix[5] *= factor;
}
void Matrix::move(float x, float y)
{
matrix[12] += -x * matrix[0] + -y * matrix[4];
matrix[13] += -x * matrix[1] + -y * matrix[5];
}
void Matrix::zoom(float factor)
{
matrix[0] *= 1/factor;
matrix[1] *= 1/factor;
matrix[4] *= 1/factor;
matrix[5] *= 1/factor;
}
void Matrix::rotate(float angle)
{
matrix[12] += pivotx * matrix[0] + pivoty * matrix[4];
matrix[13] += pivotx * matrix[1] + pivoty * matrix[5];
float cosinus = cosf(angle);
float sinus = sinf(angle);
float tmp0 = matrix[0] * cosinus + matrix[4] * sinus;
float tmp1 = matrix[1] * cosinus + matrix[5] * sinus;
matrix[4] = matrix[0] * -sinus + matrix[4] * cosinus;
matrix[5] = matrix[1] * -sinus + matrix[5] * cosinus;
matrix[0] = tmp0;
matrix[1] = tmp1;
matrix[12] += -pivotx * matrix[0] + -pivoty * matrix[4];
matrix[13] += -pivotx * matrix[1] + -pivoty * matrix[5];
}
void Matrix::movePivot(float x, float y)
{
pivotx += x;
pivoty += y;
}
void Matrix::movePivotTo(float x, float y)
{
pivotx = x;
pivoty = y;
}
/*
void Matrix::rotate(float angle)
{
float cosinus = cosf(angle);
float sinus = sinf(angle);
float tmp1 = cosinus * matrix[0] + -sinus * matrix[1];
matrix[1] = sinus * matrix[0] + cosinus * matrix[1];
matrix[0] = tmp1;
float tmp4 = cosinus * matrix[4] + -sinus * matrix[5];
matrix[5] = sinus * matrix[4] + cosinus * matrix[5];
matrix[4] = tmp4;
float tmp12 = cosinus * matrix[12] + -sinus * matrix[13];
matrix[13] = sinus * matrix[12] + cosinus * matrix[13];
matrix[12] = tmp12;
}
void Matrix::move(float x, float y)
{
matrix[12] += -x * matrix[15];
matrix[13] += -y * matrix[15];
}
void Matrix::zoom(float zoom)
{
matrix[15] *= zoom;
}
void Matrix::scale(float x, float y)
{
matrix[0] *= x;
matrix[1] *= x;
matrix[4] *= y;
matrix[5] *= y;
matrix[12] *= x;
matrix[13] *= y;
}
void Matrix::scale(float factor)
{
matrix[0] *= factor;
matrix[1] *= factor;
matrix[4] *= factor;
matrix[5] *= factor;
matrix[12] *= factor;
matrix[13] *= factor;
}
*/
};
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::System::Profile {
struct IAnalyticsInfoStatics;
struct IAnalyticsVersionInfo;
struct IEducationSettingsStatics;
struct IHardwareIdentificationStatics;
struct IHardwareToken;
struct IKnownRetailInfoPropertiesStatics;
struct IPlatformDiagnosticsAndUsageDataSettingsStatics;
struct IRetailInfoStatics;
struct ISharedModeSettingsStatics;
struct ISharedModeSettingsStatics2;
struct ISystemIdentificationInfo;
struct ISystemIdentificationStatics;
struct AnalyticsVersionInfo;
struct HardwareToken;
struct SystemIdentificationInfo;
}
namespace Windows::System::Profile {
struct IAnalyticsInfoStatics;
struct IAnalyticsVersionInfo;
struct IEducationSettingsStatics;
struct IHardwareIdentificationStatics;
struct IHardwareToken;
struct IKnownRetailInfoPropertiesStatics;
struct IPlatformDiagnosticsAndUsageDataSettingsStatics;
struct IRetailInfoStatics;
struct ISharedModeSettingsStatics;
struct ISharedModeSettingsStatics2;
struct ISystemIdentificationInfo;
struct ISystemIdentificationStatics;
struct AnalyticsInfo;
struct AnalyticsVersionInfo;
struct EducationSettings;
struct HardwareIdentification;
struct HardwareToken;
struct KnownRetailInfoProperties;
struct PlatformDiagnosticsAndUsageDataSettings;
struct RetailInfo;
struct SharedModeSettings;
struct SystemIdentification;
struct SystemIdentificationInfo;
}
namespace Windows::System::Profile {
template <typename T> struct impl_IAnalyticsInfoStatics;
template <typename T> struct impl_IAnalyticsVersionInfo;
template <typename T> struct impl_IEducationSettingsStatics;
template <typename T> struct impl_IHardwareIdentificationStatics;
template <typename T> struct impl_IHardwareToken;
template <typename T> struct impl_IKnownRetailInfoPropertiesStatics;
template <typename T> struct impl_IPlatformDiagnosticsAndUsageDataSettingsStatics;
template <typename T> struct impl_IRetailInfoStatics;
template <typename T> struct impl_ISharedModeSettingsStatics;
template <typename T> struct impl_ISharedModeSettingsStatics2;
template <typename T> struct impl_ISystemIdentificationInfo;
template <typename T> struct impl_ISystemIdentificationStatics;
}
namespace Windows::System::Profile {
enum class PlatformDataCollectionLevel
{
Security = 0,
Basic = 1,
Enhanced = 2,
Full = 3,
};
enum class SystemIdentificationSource
{
None = 0,
Tpm = 1,
Uefi = 2,
};
}
}
|
#include "CScrollable.h"
#include "CBaseEngine.h"
CScrollable::CScrollable(const vec2d& pos, const vec2d& size):
CGuiPanel(pos, size),
_panel(new CStencilPanel(vec2d(0,0), size-vec2d(20., 0.))),
_bar(new CScrollBar(vec2d(getW()-20., 0), vec2d(20., getH())))
{
_bar->addListener(makeCListenerMemberFn(SCROLLBAR, this, &CScrollable::apFn));
addChild(_panel);
addChild(_bar);
}
void CScrollable::setScrolledItem(CGuiPanel* scrolled){
_scrolled=scrolled;
_scrolled->setPosition(0., 0.);
_scrolled->addListener(makeCListenerMemberFn(0, this, (void(CScrollable::*)(int))NULL, (void(CScrollable::*)(int))NULL, &CScrollable::updateContentHeight));
_panel->addChild(scrolled);
_bar->setContentHeight(scrolled->getH());
}
void CScrollable::updateContentHeight(int dummy){
_bar->setContentHeight(_scrolled->getH());
}
|
#pragma once
#include <landstalker-lib/patches/game_patch.hpp>
#include <landstalker-lib/model/map.hpp>
/**
* This patch removes all music inside the game, while leaving all of the SFX / jingles intact.
* This was requested by players with *lots* of hours on the game who wanted to play with their own music in the
* background. I'm so sorry, Takenouchi-san.
*/
class PatchRemoveMusic : public GamePatch
{
private:
static constexpr uint8_t MUSIC_SILENT = 0x20;
uint32_t _maps_using_tibor_music_addr = 0xFFFFFFFF;
public:
void alter_rom(md::ROM& rom) override
{
// Empty the RoomMusicLUT
for(uint32_t addr=0x2A32 ; addr < 0x2A44 ; ++addr)
rom.set_byte(addr, MUSIC_SILENT);
// Remove cutscene-triggered music
rom.set_byte(0x9E59A, MUSIC_SILENT); // Duke Fanfare before last boss
rom.set_byte(0x155EB, MUSIC_SILENT); // Last boss cutscene
rom.set_byte(0x27721, MUSIC_SILENT); // Last boss cutscene
rom.set_byte(0x15523, MUSIC_SILENT); // Last boss music
rom.set_byte(0x9EBE3, MUSIC_SILENT); // Credits music
// Remove boss musics
rom.set_byte(0x9D6A1, MUSIC_SILENT);
rom.set_byte(0x9D747, MUSIC_SILENT);
rom.set_byte(0x9E195, MUSIC_SILENT);
rom.set_byte(0x9E2C1, MUSIC_SILENT);
rom.set_byte(0x9E57C, MUSIC_SILENT);
}
void inject_data(md::ROM& rom, World& world) override
{
// Since some conditions rely on current room music being Tibor's, we need to build a list of maps using this music
// to be able to check it in another way
ByteArray maps_using_tibor_music;
for(auto& [map_id, map] : world.maps())
{
if(map->background_music() == 7)
maps_using_tibor_music.add_word(map_id);
}
maps_using_tibor_music.add_word(0xFFFF);
_maps_using_tibor_music_addr = rom.inject_bytes(maps_using_tibor_music);
}
void inject_code(md::ROM& rom, World& world) override
{
// Inject a function checking on the tree maps table to check if we should trigger
// a "wave-y" teleportation effect or the regular one
uint32_t func_check_tree_map_addr = inject_func_check_tree_map(rom);
rom.set_code(0x6310, md::Code().jsr(func_check_tree_map_addr).nop());
// This code was used to fix the check removing enemies once Tibor had been saved (which was also relying
// on music). This is not useful anymore with the flexible mapsetup system which attaches the procedure
// to the correct Tibor maps directly, not relying on music anymore.
// rom.set_code(0x1A034, md::Code().jsr(func_check_tree_map_addr).nop());
}
private:
uint32_t inject_func_check_tree_map(md::ROM& rom) const
{
md::Code func_check_tree_map;
func_check_tree_map.movem_to_stack({ reg_D0 }, { reg_A0 });
{
func_check_tree_map.movew(addr_(0xFF1206), reg_D0);
func_check_tree_map.lea(_maps_using_tibor_music_addr, reg_A0);
func_check_tree_map.label("loop_maps");
{
func_check_tree_map.cmpiw(0xFFFF, addr_(reg_A0));
func_check_tree_map.bne("not_the_end");
{
// Reached the end without finding the map, return false
func_check_tree_map.tstb(addr_(0xFF0000));
func_check_tree_map.bra("return");
}
func_check_tree_map.label("not_the_end");
func_check_tree_map.cmpw(addr_(reg_A0), reg_D0);
func_check_tree_map.bne("next_map");
{
// Found the map, return true
func_check_tree_map.bra("return");
}
func_check_tree_map.label("next_map");
func_check_tree_map.adda(2, reg_A0);
}
func_check_tree_map.bra("loop_maps");
func_check_tree_map.label("return");
}
func_check_tree_map.movem_from_stack({ reg_D0 }, { reg_A0 });
func_check_tree_map.rts();
return rom.inject_code(func_check_tree_map);
}
};
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void PrintVector(vector<int> ve);
int main()
{
vector<int> vec1;//创建一个空的vector
vector<int> vec2(vec1);//创建一个vector,并用vec1初始化vec2
vector<int> vec3(10);//创建一个有n个数据的vector
vector<int> vec4(10,0);//创建含有10个数据的vector,并全初始化为0
// vec4.~vector();//销毁所有数据,释放资源
//在vector尾部添加元素
vec1.push_back(4);
vec1.push_back(6);
vec1.push_back(8);
vec1.push_back(1);
vec1.push_back(2);
PrintVector(vec1);
//在尾部删除元素
vec1.pop_back();
PrintVector(vec1);
//在vector头部添加元素,无法完成,因为vector的数据结构是数组,无法在头部插入元素,否则需要整个数组前移
//在vector头部删除元素,无法完成,理由同上。
//取vector中某位置的元素值
cout<<"在1位置的元素值为:"<<vec1.at(1)<<endl;
cout<<"在1位置的元素值为:"<<vec1[1]<<endl;
//begin():指向容器最开始位置数据的指针,详见PrintVector
//end():指向容器最后一个数据单元的指针+1,详见PrintVector
//返回尾部数据的引用
cout<<"尾部数据的值为:"<<vec1.back()<<endl;
//返回头部数据的引用
cout<<"头部数据的值为:"<<vec1.front()<<endl;
cout<<"vector中的最大容量为:"<<vec1.max_size()<<endl;
cout<<"vector中的元素个数为:"<<vec1.size()<<endl;
cout<<"vector是否为空:"<<vec1.empty()<<endl;
//交换两个容器中的数据
vector<int> vecSwap;
vecSwap.push_back(1);
vecSwap.push_back(2);
PrintVector(vec1);
PrintVector(vecSwap);
vec1.swap(vecSwap);
PrintVector(vec1);
PrintVector(vecSwap);
//重新再交换回来
vec1.swap(vecSwap);
//对vector进行升序排序
sort(vec1.begin(),vec1.end());
PrintVector(vec1);
//对vector进行降序排序
reverse(vec1.begin(),vec1.end());
PrintVector(vec1);
//修改数组的某个元素
vec1[2]=99;
PrintVector(vec1);
vec1.at(3)=88;
PrintVector(vec1);
//删除数组的某个元素
//为什么要使用iterator来进行定位,因为数组如果要删除一个元素或者折辱一个元素,会导致其他元素移动,所有不能直接进行删除
vector<int>::iterator vItera=vec1.begin();
vItera=vItera+2;
vec1.erase(vItera);
PrintVector(vec1);
//vector插入某元素,要使用iterator来定位某个位置
vector<int>::iterator vInsert=vec1.begin();
vInsert=vInsert+2;
vec1.insert(vInsert,777);
PrintVector(vec1);
//重新设置vector的容量
vec1.resize(10);
//清除所有数据
vec1.clear();
PrintVector(vec1);
cout<<"vector是否为空:"<<vec1.empty()<<endl;
//测试vector去重
int arr1[]={6,4,1,1,6,6,9,9,6,6};
vector<int> arr1Vec(arr1,arr1+sizeof(arr1)/sizeof(int));
sort(arr1Vec.begin(),arr1Vec.end());
vector<int>::iterator arr1Ite =unique(arr1Vec.begin(),arr1Vec.end());
arr1Vec.erase(arr1Ite,arr1Vec.end());
PrintVector(arr1Vec);
return 0;
}
void PrintVector(vector<int> ve)
{
cout<<"Vector中的数据为:";
vector<int>::iterator veIterator;
for(veIterator=ve.begin();veIterator!=ve.end();veIterator++)
{
cout<<*veIterator<<" ";
}
cout<<endl;
}
|
#include <bits/stdc++.h>
#include <conio.h>
using namespace std;
int hcf(int, int);
int lcm(int, int);
int main()
{
int a, b;
cin>>a>>b;
}
int hcf(int a, int b)
{
}
|
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <pthread.h>
#include "egl_gl_fbo.h"
#include "multimedia/mm_debug.h"
#include "WaylandConnection.h"
#include <Surface.h>
MM_LOG_DEFINE_MODULE_NAME("EGL-FBO")
#if 0
#undef DEBUG
#undef INFO
#undef WARNING
#undef ERROR
#define DEBUG(format, ...) printf("[D] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__)
#define INFO(format, ...) printf("[I] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__)
#define WARNING(format, ...) printf("[W] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__)
#define ERROR(format, ...) printf("[E] %s, line: %d:" format "\n", __func__, __LINE__, ##__VA_ARGS__)
#endif
#define FUNC_TRACK() FuncTracker tracker(MM_LOG_TAG, __FUNCTION__, __LINE__)
// #define FUNC_TRACK()
#define CHECK_GL_ERROR() do { \
int error = glGetError(); \
if (error != GL_NO_ERROR) \
ERROR("glGetError() = %d", error); \
} while (0)
// shader source
#define SHADER(Src) #Src
// draw yuv texture
const char* vs0 =SHADER(
attribute vec2 position;
attribute vec2 texcoord;
varying vec2 v_texcoord;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_texcoord = texcoord;
}
);
const char* fs0 = "#extension GL_OES_EGL_image_external : require \n" SHADER(
precision mediump float;
varying vec2 v_texcoord;
uniform samplerExternalOES sampler;
void main() {
gl_FragColor = texture2D(sampler, v_texcoord);
}
);
// render to YUV FBO
const char* vs1 = "#version 300 es \n" \
SHADER(
in vec2 position;
in vec2 texcoord;
out vec2 v_texcoord;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
v_texcoord = texcoord;
}
);
const char* fs1 = "#version 300 es \n" \
"#extension GL_EXT_YUV_target : require \n" \
SHADER(
precision mediump float;
layout (yuv) out vec4 fragColor ;
in vec2 v_texcoord;
uniform sampler2D sampler;
void main() {
fragColor = texture(sampler, v_texcoord);
}
);
// gl_FragColor = texture2D(sampler, v_texcoord);
// layout (yuv) out vec4 color;
// yuvCscStandardEXT conv = itu_601;
#undef SHADER
// FIXME, FBO doesn't require native display/surface, but not reality yet (fail to eglCreateWindowSurface())
class WorkAroundEglInit {
public:
static void Init() {
mConnection = new yunos::wpc::WaylandConnection(NULL);
mWlSurface = mConnection->compositor_create_surface();
struct wl_egl_window_copy* tmp = (struct wl_egl_window_copy*)malloc(sizeof(struct wl_egl_window_copy));
memset(tmp, 0, sizeof(struct wl_egl_window_copy));
tmp->surface = mWlSurface;
tmp->attached_width = 0;
tmp->attached_height = 0;
tmp->nativewindow = 0;
mEglWindow = (struct wl_egl_window*)tmp;
ASSERT(mConnection && mWlSurface && mEglWindow);
mInited = true;
}
static void Deinit() {
usleep(50000);
mConnection->destroy_surface(mWlSurface);
mConnection->dec_ref();
delete mConnection;
free(mEglWindow);
mConnection = NULL;
mWlSurface = NULL;
}
static struct wl_display* getNativeDisplay() {
if (!mInited)
Init();
return mConnection->get_wayland_display();
}
static struct wl_egl_window* getNativeSurface() { return mEglWindow; }
private:
// hack, copied from wayland, with additional padding
struct wl_egl_window_copy {
struct wl_surface *surface;
int width;
int height;
int dx;
int dy;
int attached_width;
int attached_height;
void *nativewindow;
void (*resize_callback)(struct wl_egl_window *, void *);
void (*free_callback)(struct wl_egl_window *, void *);
uint8_t padding[20];
};
public: // C++ should support 'private-static' variable declare/define at the same time. however fails
static yunos::wpc::WaylandConnection* mConnection;
static struct wl_surface* mWlSurface; // a wl_surface to work around eglCreateWindowSurface issue
static struct wl_egl_window* mEglWindow;
static bool mInited;
};
yunos::wpc::WaylandConnection* WorkAroundEglInit::mConnection = NULL;
struct wl_surface* WorkAroundEglInit::mWlSurface = NULL;
struct wl_egl_window* WorkAroundEglInit::mEglWindow = NULL;
bool WorkAroundEglInit::mInited = false;
// ##################################################
static void printGLString() {
typedef struct {
const char* str;
GLenum e;
}GLString;
GLString glStrings[] = {
{"Version", GL_VERSION},
{"Vendor", GL_VENDOR},
{ "Renderer", GL_RENDERER},
{ "Extensions", GL_EXTENSIONS}
};
uint32_t i =0;
for (i=0; i<sizeof(glStrings)/sizeof (GLString); i++) {
const char *v = (const char *) glGetString(glStrings[i].e);
INFO("GL %s = %s", glStrings[i].str, v);
}
}
// parameter to init EGL
static const EGLint context_attribs[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
static EGLint config_attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 1,
EGL_GREEN_SIZE, 1,
EGL_BLUE_SIZE, 1,
EGL_ALPHA_SIZE, 1,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, // use gles v3
EGL_NONE
};
// singleton/global context
static EGLDisplay eglDisplay = NULL;
static EGLConfig eglConfig = NULL; // choosed EGLConfig
static EGLConfig* configs; // all possible EGLConfigs
#ifndef GL_GLEXT_PROTOTYPES
static PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR;
static PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR;
static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES;
static PFNGLDRAWBUFFERSEXTPROC glDrawBuffersEXT;
#endif
// shader program for gles2
unsigned LoadShader(unsigned type, const std::string& source) {
FUNC_TRACK();
unsigned shader = glCreateShader(type);
const char* src = source.data();
if (shader) {
glShaderSource(shader, 1, &src, NULL);
glCompileShader(shader);
int compiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
char logInfo[4096];
glGetShaderInfoLog(shader, sizeof(logInfo), NULL, logInfo);
ERROR("compile shader logInfo = %s\n", logInfo);
DEBUG("shader source:\n %s\n", src);
ASSERT(0 && "compile fragment shader failed");
glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
unsigned LoadProgram(const std::string& vertex_source, const std::string& fragment_source) {
FUNC_TRACK();
unsigned vertex_shader = LoadShader(GL_VERTEX_SHADER, vertex_source);
unsigned fragment_shader = LoadShader(GL_FRAGMENT_SHADER, fragment_source);
unsigned program = glCreateProgram();
if (vertex_shader && fragment_shader && program) {
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
int linked = 0;
glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (!linked) {
ASSERT(0 && "link shader program failed");
glDeleteProgram(program);
program = 0;
}
}
if (vertex_shader)
glDeleteShader(vertex_shader);
if (fragment_shader)
glDeleteShader(fragment_shader);
return program;
}
// destroy egl global context
static void destroyEglGlobal() __attribute__((destructor(203)));
static void destroyEglGlobal() {
if (!eglDisplay)
return;
printf("%s, about to call elgTerminate\n", __func__);
eglTerminate(eglDisplay);
free(configs);
configs = NULL;
eglDisplay= NULL;
eglConfig = NULL;
printf("%s, done\n", __func__);
WorkAroundEglInit::Deinit();
}
// init the global env for all eglContext
static bool ensureEglGlobal()
{
FUNC_TRACK();
EGLint major, minor;
EGLBoolean ret = EGL_FALSE;
EGLint count = -1, n = 0, i = 0, size = 0;
WorkAroundEglInit::Init();
if (eglDisplay && eglConfig)
return true;
ASSERT(!eglDisplay && !eglConfig);
#ifndef GL_GLEXT_PROTOTYPES
eglCreateImageKHR = (PFNEGLCREATEIMAGEKHRPROC) eglGetProcAddress("eglCreateImageKHR");
ASSERT(eglCreateImageKHR != NULL);
eglDestroyImageKHR = (PFNEGLDESTROYIMAGEKHRPROC) eglGetProcAddress("eglDestroyImageKHR");
ASSERT(eglDestroyImageKHR != NULL);
glEGLImageTargetTexture2DOES = (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress("glEGLImageTargetTexture2DOES");
ASSERT(glEGLImageTargetTexture2DOES != NULL);
glDrawBuffersEXT = (PFNGLDRAWBUFFERSEXTPROC)eglGetProcAddress("glDrawBuffersEXT");
ASSERT(glDrawBuffersEXT != NULL);
#endif
#ifdef YUNOS_ENABLE_UNIFIED_SURFACE
eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
#elif PLUGIN_HAL // FIXME, use EGL_DEFAULT_DISPLAY
eglDisplay = eglGetDisplay(WorkAroundEglInit::getNativeDisplay());
#else
eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
#endif
ASSERT(eglDisplay != NULL);
ret = eglInitialize(eglDisplay, &major, &minor);
ASSERT(ret == EGL_TRUE);
ret = eglBindAPI(EGL_OPENGL_ES_API);
ASSERT(ret == EGL_TRUE);
if (!eglGetConfigs(eglDisplay, NULL, 0, &count) || count < 1)
ASSERT(0);
configs = (EGLConfig*)malloc(sizeof(EGLConfig) * count);
ASSERT(configs);
memset(configs, 0, sizeof(EGLConfig) * count);
ret = eglChooseConfig(eglDisplay, config_attribs, configs, count, &n);
ASSERT(ret && n >= 1);
for (i = 0; i < n; i++) {
eglGetConfigAttrib(eglDisplay, configs[i], EGL_BUFFER_SIZE, &size);
if (32 == size) {
eglConfig = configs[i];
break;
}
}
DEBUG("ensureEglGlobal done");
return true;
}
namespace YUNOS_MM {
// ################################################################
// EGL context per window
EglWindowContext::EglWindowContext()
: mWidth(0), mHeight(0)
, mEglSurface(EGL_NO_SURFACE), mEglContext(EGL_NO_CONTEXT)
, mCurrTexId(0), mUseSingleTexture(true)
{
FUNC_TRACK();
int i=0;
for (i=0; i<MAX_BUFFER_NUM; i++) {
mBufferInfo[i].anb = NULL;
mBufferInfo[i].texId = 0;
mBufferInfo[i].img = EGL_NO_IMAGE_KHR;
}
for (i=0; i<2; i++) {
mProgramId[i] = 0;
mVertexPointerHandle[i] = -1;
mVertexTextureHandle[i] = -1;
mSamplerHandle[i] = -1;
}
mRgbxTexId[0] = 0;
mRgbxTexId[1] = 0;
mUseSingleTexture = YUNOS_MM::mm_check_env_str("mm.test.use.single.texture", "MM_TEST_USE_SINGLE_TEXTURE", "1", true);
}
/* usually, FBO doesn't require native-display to init EGL, doesn't require native-window to create EGLSurface.
* however, it isn't the fact on our platform yet.
*/
bool EglWindowContext::init(/*void* nativeDisplay, void* nativeWindow*/)
{
FUNC_TRACK();
EGLBoolean ret;
if (!ensureEglGlobal())
return false;
// shader source code
static const char* vs[2] = {vs0, vs1};
const char* fs[2] = {fs0, fs1};
// init EGL/GLES context
mEglContext = eglCreateContext(eglDisplay, eglConfig, NULL, context_attribs);
void *w = NULL;
// a NULL native surface to create EGLSurface should be ok (especially for FBO), however it fails. let's work around it
w = WorkAroundEglInit::getNativeSurface();
mEglSurface = eglCreateWindowSurface(eglDisplay, eglConfig,
(EGLNativeWindowType)w, NULL);
ASSERT(mEglContext != EGL_NO_CONTEXT && mEglSurface != EGL_NO_SURFACE);
ret = eglMakeCurrent(eglDisplay, mEglSurface, mEglSurface, mEglContext);
ASSERT(ret == EGL_TRUE);
printGLString();
// compile and link shader program
uint32_t i, j;
for (i=0; i<2; i++) {
ASSERT(mProgramId[i] == 0 && mVertexPointerHandle[i] == -1 && mVertexTextureHandle[i] == -1 && mSamplerHandle[i] == -1);
mProgramId[i] = LoadProgram(vs[i], fs[i]);
ASSERT(mProgramId);
glUseProgram(mProgramId[i]);
mVertexPointerHandle[i] = glGetAttribLocation(mProgramId[i], "position");
mVertexTextureHandle[i] = glGetAttribLocation(mProgramId[i], "texcoord");
mSamplerHandle[i] = glGetUniformLocation(mProgramId[i], "sampler");
// ASSERT(GLenum(GL_NO_ERROR) == glGetError());
ASSERT(mVertexPointerHandle[i] != -1);
// ASSERT(mVertexPointerHandle[i] != -1 && mVertexTextureHandle[i] != -1 && mSamplerHandle[i] != -1);
DEBUG("index: %d, mVertexPointerHandle: %d, mVertexTextureHandle: %d, mSamplerHandle: %d",
i, mVertexPointerHandle[i], mVertexTextureHandle[i], mSamplerHandle[i]);
}
// create temp RGBX texture test. [0] uses as src to draw rect, [1] uses as fbo;
// use same resolution as WindowSurface, so we needn't change glViewport() for FBO
uint32_t texW = 256, texH = 256; // I tried to use video size to create these texture. but it seems late to init EGL when the first video frame comes (mediacodec stucks)
char* texData = (char*) malloc (texW * texH * 4);
glGenTextures(2, mRgbxTexId);
for (i=0; i<2; i++) {
glBindTexture(GL_TEXTURE_2D, mRgbxTexId[i]);
// memset(texData, i*0xf0, texW * texH * 4);
uint32_t *pixel = (uint32_t*)texData;
uint32_t pixelValue = 0;
if (i == 0)
pixelValue = 0x00f000ff;
else
pixelValue = 0x0000f0ff;
for (j=0; j<texW; j++ ){
*pixel++ = pixelValue;
}
for (j=1; j<texH; j++) {
memcpy(texData+j*texW*4, texData, texW*4);
}
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, texW, texH, 0,GL_RGBA, GL_UNSIGNED_BYTE, texData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
CHECK_GL_ERROR();
}
DEBUG("mRgbxTexId[0]: %d, mRgbxTexId[1]: %d", mRgbxTexId[0], mRgbxTexId[1]);
free(texData);
DEBUG("texW: %d, texH: %d", texW, texH);
glViewport(0, 0, mWidth, mHeight);
if (mUseSingleTexture)
glGenTextures(1, &mCurrTexId);
DEBUG("mCurrTexId: %d", mCurrTexId);
return true;
}
bool EglWindowContext::deinit() {
FUNC_TRACK();
if (mUseSingleTexture && mCurrTexId)
glDeleteTextures(1, &mCurrTexId);
glDeleteTextures(2, mRgbxTexId);
int i = 0;
for (i = 0; i < MAX_BUFFER_NUM; i++) {
if (mBufferInfo[i].anb == NULL)
break;
if (mBufferInfo[i].texId)
glDeleteTextures(1, &mBufferInfo[i].texId);
eglDestroyImageKHR(eglDisplay, mBufferInfo[i].img);
mBufferInfo[i].anb = NULL;
mBufferInfo[i].texId = 0;
mBufferInfo[i].img = EGL_NO_IMAGE_KHR;
}
// Free GL resource.
for (i=0; i<2; i++) {
if (mProgramId[i]) {
glDeleteProgram(mProgramId[i]);
mProgramId[i] = 0;
mVertexPointerHandle[i] = -1;
mVertexTextureHandle[i] = -1;
mSamplerHandle[i] = -1;
}
}
ASSERT(eglDisplay != EGL_NO_DISPLAY && mEglContext != EGL_NO_CONTEXT && mEglSurface != EGL_NO_SURFACE);
eglDestroyContext(eglDisplay, mEglContext);
eglDestroySurface(eglDisplay, mEglSurface);
eglMakeCurrent(eglDisplay, NULL, NULL, NULL);
mEglContext = EGL_NO_CONTEXT;
mEglSurface = EGL_NO_SURFACE;
// workAroundEglDeinit();
return true;
}
bool EglWindowContext::bindTexture(YNativeSurfaceBuffer* anb)
{
FUNC_TRACK();
int i;
bool needBindTexture = false;
if (!anb)
return false;
for (i = 0; i < MAX_BUFFER_NUM; i++) {
if (mBufferInfo[i].anb == anb)
break;
if (mBufferInfo[i].anb == NULL) {
EGLClientBuffer clientBuffer = (EGLClientBuffer)anb;
#ifdef PLUGIN_HAL
EGLenum target = 0x3140;
#else
EGLenum target = EGL_NATIVE_BUFFER_YUNOS;
#endif
mBufferInfo[i].img = eglCreateImageKHR(eglDisplay, EGL_NO_CONTEXT, target, clientBuffer, 0);
ASSERT(mBufferInfo[i].img != EGL_NO_IMAGE_KHR);
// Note: increase ref count; since eglDestroyImageKHR will decrease one refcount for mali driver
VERBOSE("(%s, %d): eglCreateImageKHR\n", __func__, __LINE__);
if (!mUseSingleTexture)
glGenTextures(1, &mBufferInfo[i].texId);
mBufferInfo[i].anb = anb;
needBindTexture = true;
break;
}
}
if (i >= MAX_BUFFER_NUM) {
ERROR("run out of buffer, mBufferInfo is full\n");
return false;
}
if (!mUseSingleTexture)
mCurrTexId = mBufferInfo[i].texId;
glBindTexture(GL_TEXTURE_EXTERNAL_OES, mCurrTexId);
#ifdef __PHONE_BOARD_MTK__
needBindTexture = true;
#endif
if (needBindTexture || mUseSingleTexture)
glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, mBufferInfo[i].img);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES,GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES,GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES,GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_EXTERNAL_OES,GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// INFO("bind texture[%d]: %d for anb %p", i, mCurrTexId, anb);
glViewport(0, 0, mWidth, mHeight);
return true;
}
bool EglWindowContext::drawTestRect(GLuint tex, GLenum texTarget, int mode /* 0: center diamond, 1: left-half, 2: right-half , 3: full-window */)
{
FUNC_TRACK();
static const GLfloat vtx[] = {
// center diamond
0.0f, -0.75f,
-0.75f, 0.0f,
0.0f, 0.75f,
0.75f, 0.0f,
// half-left
-1.0f, 1.0f,
-1.0f, -1.0f,
0.0f, -1.0f,
0.0f, 1.0f,
// right-half
-0.0f, 1.0f,
-0.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
// full window
-1.0f, 1.0f,
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0, };
static const GLfloat texcoords[4][2] = {
{ 0.0f, 0.0f },
{ 0.0f, 1.0f },
{ 1.0f, 1.0f },
{ 1.0f, 0.0f },
};
int programIdx = 1;
if (texTarget == GL_TEXTURE_EXTERNAL_OES)
programIdx = 0;
glBindTexture(texTarget, tex);
glUseProgram(mProgramId[programIdx]);
glEnableVertexAttribArray(mVertexPointerHandle[programIdx]);
glVertexAttribPointer(mVertexPointerHandle[programIdx], 2, GL_FLOAT, GL_FALSE, 0, vtx+mode*8);
CHECK_GL_ERROR();
if (mVertexTextureHandle[programIdx] != -1) {
glEnableVertexAttribArray(mVertexTextureHandle[programIdx]);
glVertexAttribPointer(mVertexTextureHandle[programIdx], 2, GL_FLOAT, GL_FALSE, 0, texcoords);
}
if (mSamplerHandle[programIdx] != -1)
glUniform1i(mSamplerHandle[programIdx], 0);
CHECK_GL_ERROR();
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
CHECK_GL_ERROR();
return true;
}
bool EglWindowContext::updateFbo(GLenum target, GLuint FboTex, int mode)
{
FUNC_TRACK();
GLuint mFramebuffer = 0;
DEBUG("FboTex: %d", FboTex);
glBindTexture(target, FboTex);
CHECK_GL_ERROR();
glGenFramebuffers(1, &(mFramebuffer));
glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, target, FboTex, 0);
CHECK_GL_ERROR();
GLenum pDrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffersEXT(1, pDrawBuffers);
GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
CHECK_GL_ERROR();
if( status != GL_FRAMEBUFFER_COMPLETE ) {
ERROR("error creating FBO: %d", status );
}
// draw something to FBO
drawTestRect(mRgbxTexId[0], GL_TEXTURE_2D, mode);
CHECK_GL_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
bool EglWindowContext::processBuffer(YNativeSurfaceBuffer* anb, uint32_t width, uint32_t height)
{
FUNC_TRACK();
mWidth = width;
mHeight = height;
if (! bindTexture(anb))
return false;
static uint32_t drawCount = 0;
drawCount++;
// 0: does nothing
// 1: use texture as FBO and does glClear().
// 2: use texture as FBO and draw a rectangle on it. it is ok on RGBX FBO but fails on YUV FBO
int drawMode = drawCount/60 % 4;
INFO("rendering mode ##################### %d anb: %p######################", drawMode, anb);
// updateFbo(GL_TEXTURE_2D, mRgbxTexId[1], true);
updateFbo(GL_TEXTURE_EXTERNAL_OES, mCurrTexId, drawMode);
return true;
}
} // end of namespace YUNOS_MM
|
class MainForm:public Form
{
TextBox* txtFilePath;
TextBox* txtFileNumber;
public:
void Button1_Click()
{
string filePath = txtFilePath->getText();
int number = atoi(txtFileNumber->getText().c_str());
FileSplitter splitter(filePath,number);
splitter.split();
}
};
|
#ifndef NOTEITEM_H
#define NOTEITEM_H
#include "node.hpp"
#include <QDialog>
class Filter;
class FilterNode : public Node
{
public:
FilterNode(const QString &name, HandleItem::MapType outputType,
Filter *filter, QGraphicsItem *parent = 0);
~FilterNode();
enum { Type = UserType + 2 };
virtual int type() const { return Type; }
protected:
void updateMap();
const Map *rawMap();
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event);
private:
Filter *filter_;
Map *map_;
};
#endif // NOTEITEM_H
|
#ifndef USECOUNT_H
#define USECOUNT_H
#include "../instructions/register.h"
#include <map>
#include <iostream>
#include <string>
using namespace std;
typedef map<string, int> RegCount;
typedef RegCount::iterator RegCountit;
/**
* A UseCounter counts the number of times a register is used within the code.
* This is used to perform an optimization during JVM code generation.
*
* If we know a register is a temporary, and is used no more than 2 times
* within a function body (that is: it should be written to once and read from
* once), then in some cases, we can leave that temporary on the runtime stack.
*
* Example:
* x = w+y+z;
* is translated to (optimized):
* t0 = w + y
* x = t0 + z
*
* Now, it is perfectly possible to generate the following code:
* load w
* load y
* iadd
* load z
* store x
*
* Note that we did not add the statements
* store t0
* load t0
* because they are wasteful
* Such statements appear very frequently in code that makes heavy use of
* expressions (because temps are always used to store a partly computation
* of an expression).
*
* The reason we need to count the number of times a variable is used is that,
* because of the common subexpression elimination, t0 can for example be used
* in another part of the body. If we then don't add the store t0; load t0 statements,
* t0 will not be initialized, or will contain a wrong value.
* The trick is to only ommit the redundant save/load when the temporary is used
* not more than 2 times.
*
* This class is a singleton.
*/
class UseCount {
public:
static UseCount& instance();
/**
* Increment the usage count of register r
*/
void incCount(string& funname, Register* r);
/**
* Returns the number of times register r was counted
*/
int count(string& funname, Register* r);
friend ostream& operator<<(ostream& os, UseCount& uc);
private:
/**
* Qualifies the register name with the function name
*/
string qualify(string& funname, Register* r);
static UseCount instance_;
RegCount useCount_;
};
/**
* Prints each register counted and the number of times it is used.
* Used for debugging.
*/
ostream& operator<<(ostream& os, UseCount& uc);
#endif
|
#include "Decompressor.h"
Decompressor::Decompressor() {
nextBunchOfBits = 0;
nextBitsCount = 0;
}
int Decompressor::readBits(int howMany) {
while(nextBitsCount < howMany) {
int byte = decompressNextByte();
nextBunchOfBits |= ull(byte) << nextBitsCount;
nextBitsCount += 8;
}
int ret = int(nextBunchOfBits & ((1ULL << howMany) - 1));
nextBunchOfBits >>= howMany;
nextBitsCount -= howMany;
return ret;
}
|
#include "tinyxml2.h";
#include <string>;
#include <iostream>;
using namespace tinyxml2;
XMLDocument& CreateDocument();
void SaveXML(XMLDocument& XMLDoc, const std::string filename);
void WriteIntXML(XMLDocument& XMLDoc);
void WriteStringXML(XMLDocument& XMLDoc);
void ReadXML(const std::string filename);
int main()
{
//create the xml documment instance
XMLDocument& xmlDoc = CreateDocument();
WriteIntXML(xmlDoc);
WriteStringXML(xmlDoc);
SaveXML(xmlDoc,"file.xml");
ReadXML("file.xml");
system("pause");
return 0;
}
XMLDocument& CreateDocument()
{
XMLDocument* xmlDoc = new XMLDocument();
XMLElement* root = xmlDoc->NewElement("root");
xmlDoc->InsertFirstChild(root);
return *xmlDoc;
}
void SaveXML(XMLDocument& xmlDoc, const std::string filename)
{
if (xmlDoc.SaveFile(filename.c_str()) == tinyxml2::XML_SUCCESS)
{
std::cout << "Save Success!" << std::endl;
}
else
{
std::cout << "Save Failed!" << std::endl;
}
}
void WriteIntXML(XMLDocument& xmlDoc)
{
XMLNode* intsElement = xmlDoc.NewElement("ints");
for (int i = 0; i < 5; i++)
{
XMLElement* intElement = xmlDoc.NewElement("int");
intElement->SetAttribute("index", i);
intsElement->InsertEndChild(intElement);
}
xmlDoc.FirstChildElement()->InsertEndChild(intsElement);
//<ints>
// <int index="0">0</int>
//</ints>
}
void WriteStringXML(XMLDocument& XMLDoc)
{
XMLNode* stringsElement = XMLDoc.NewElement("strings");
for (int i = 0; i < 5; i++)
{
XMLElement* Element = XMLDoc.NewElement("string");
Element->SetAttribute("index", i);
Element->SetText(("string #" + std::to_string(i)).c_str());
stringsElement->InsertEndChild(Element);
}
XMLDoc.FirstChildElement()->InsertEndChild(stringsElement);
}
void ReadXML(const std::string filename)
{
XMLDocument xmlDoc;
xmlDoc.LoadFile(filename.c_str());
XMLElement* root = xmlDoc.FirstChildElement();
XMLElement* intsElements = root->FirstChildElement("ints");
XMLElement* element = intsElements->FirstChildElement();
std::cout << "List of ints:" << std::endl;
while (element != nullptr)
{
int intValue;
if (element->QueryIntAttribute("index", &intValue) == XML_SUCCESS)
{
std::cout << intValue << std::endl;
}
element = element->NextSiblingElement();
}
XMLElement* stringElement = root->FirstChildElement("strings");
element = stringElement->FirstChildElement();
std::cout << "List of strings:" << std::endl;
while (element != nullptr)
{
int intValue;
if (element->QueryIntAttribute("index", &intValue) == XML_SUCCESS)
{
std::cout << element->GetText() << ": ";
if (element->QueryIntAttribute("index", &intValue) == XML_SUCCESS)
{
std::cout << intValue;
}
std::cout << std::endl;
}
element = element->NextSiblingElement();
}
}
|
#include "stdafx.h"
#include "ScriptOMAll.h"
#include "StudioSyntaxParser.h"
#include "SCISyntaxParser.h"
#include "ParserActions.h"
#include "Operators.h"
#include "OperatorTables.h"
#include "format.h"
#ifdef ENABLE_FOREACH
#include "ScriptMakerHelper.h"
#endif
#ifdef ENABLE_GETPOLY
#include "Polygon.h"
#include "AppState.h"
#endif
using namespace sci;
using namespace std;
void NoCaseE(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (!match.Result())
{
pContext->ReportError("Expected case value or 'else' keyword.", stream);
}
}
template<typename _It>
bool IntegerNonZeroP(const ParserSCI *pParser, SyntaxContext *pContext, _It &stream)
{
bool fRet = IntegerExpandedP(pParser, pContext, stream);
if (fRet)
{
fRet = (pContext->Integer != 0);
if (!fRet)
{
pContext->ReportError("Expected non-zero integer.", stream);
}
}
return fRet;
}
// Selectors, as far as I can tell, look like this:
// A-Za-z0-9_-
// But they must have at least one letter and not start with a number
template<typename _It>
bool SelectorP(const ParserSCI *pParser, SyntaxContext *pContext, _It &stream)
{
bool fRet = false;
std::string &str = pContext->ScratchString();
str.clear();
char ch = *stream;
bool hadAlpha = !!isalpha(ch);
if (hadAlpha || (ch == '_') || (ch == '-')) // First character must be a letter or _ or -
{
fRet = true;
str += ch;
ch = *(++stream);
while (isalnum(ch) || (ch == '_') || (ch == '-')) // Then any alphanumeric character is fine.
{
hadAlpha = hadAlpha || isalpha(ch);
fRet = true;
str += ch;
ch = *(++stream);
}
}
return fRet && hadAlpha;
}
// For better error reports:
vector<string> SCIStatementKeywords =
{
"if",
"asm",
"break",
"breakif",
"continue",
"contif",
"repeat",
"switch",
"switchto",
"for",
"return",
"cond",
"while",
"define",
};
vector<string> SCIKeywords =
{
#ifdef ENABLE_EXISTS
"&exists",
#endif
#ifdef ENABLE_GETPOLY
"&getpoly",
#endif
"&tmp",
"&rest",
"&sizeof",
"and",
"asm",
"break",
"breakif",
"class#" // ** In classdef
"classdef" // **
"cond",
"continue",
"contif",
"define",
"else",
"extern" // ** For linking public procedures
"file#" // ** Procedure forward declarations
"for",
#ifdef ENABLE_FOREACH
"foreach",
#endif
"global" // ** For global var declarations
"if",
"method",
"methods" // ** Method forward declarations (also methods in classdef)
"mod",
"not",
"of",
"or",
"procedure",
"properties",
"public",
"repeat",
"return",
"script#",
"selectors" // ** For the selector list
"super#" // ** In classdef
"super",
"switch",
"switchto",
"text#",
#ifdef ENABLE_VERBS
"verbs",
#endif
"while",
// "scriptNumber", // This is special, because it's a value. So don't count it as a banned keyword.
// neg, send, case, do, default, export are also keywords, but for the Studio language.
// **: Original Sierra constructs that are not supported yet.
};
template<typename _It, typename _TContext>
bool AlphanumPNoKeywordOrTerm(const ParserSCI *pParser, _TContext *pContext, _It &stream)
{
bool fRet = SelectorP(pParser, pContext, stream);
if (fRet)
{
char chTerm = *stream;
fRet = (chTerm != ':') && (chTerm != '?');
if (fRet)
{
std::string &str = pContext->ScratchString();
fRet = std::find(SCIKeywords.begin(), SCIKeywords.end(), str) == SCIKeywords.end();
if (fRet && pContext->extraKeywords)
{
fRet = pContext->extraKeywords->find(str) == pContext->extraKeywords->end();
}
}
}
return fRet;
}
// Same as above, but ignores extra keywords.
template<typename _It, typename _TContext>
bool AlphanumPNoKeywordOrTerm2(const ParserSCI *pParser, _TContext *pContext, _It &stream)
{
bool fRet = SelectorP(pParser, pContext, stream);
if (fRet)
{
char chTerm = *stream;
fRet = (chTerm != ':') && (chTerm != '?');
if (fRet)
{
std::string &str = pContext->ScratchString();
fRet = std::find(SCIKeywords.begin(), SCIKeywords.end(), str) == SCIKeywords.end();
}
}
return fRet;
}
template<typename _It, typename _TContext>
bool AlphanumPSendTokenOrTerm(const ParserSCI *pParser, _TContext *pContext, _It &stream)
{
bool fRet = SelectorP(pParser, pContext, stream);
if (fRet)
{
char chTerm = *stream;
fRet = (chTerm != ':') && (chTerm != '?');
if (fRet)
{
std::string &str = pContext->ScratchString();
if (str != "send" && str != "super")
{
fRet = std::find(SCIKeywords.begin(), SCIKeywords.end(), str) == SCIKeywords.end();
if (fRet && pContext->extraKeywords)
{
fRet = pContext->extraKeywords->find(str) == pContext->extraKeywords->end();
}
}
}
}
return fRet;
}
// foo: or foo?, no whitespace allowed.
template<char terminator, typename _It>
bool SelectorP_Term(const ParserSCI *pParser, SyntaxContext *pContext, _It &stream)
{
bool fRet = SelectorP(pParser, pContext, stream);
fRet = fRet && (*(stream) == terminator);
if (fRet)
{
++stream; // Skip over our terminator
}
return fRet;
}
template<typename _TOpType>
_TOpType SCINameToOperator(const std::string &name);
template<>
BinaryOperator SCINameToOperator<BinaryOperator>(const std::string &name)
{
return NameToOperator(name, sciNameToBinaryOp);
}
template<>
AssignmentOperator SCINameToOperator<AssignmentOperator>(const std::string &name)
{
return NameToOperator(name, sciNameToAssignmentOp);
}
template<>
UnaryOperator SCINameToOperator<UnaryOperator>(const std::string &name)
{
return NameToOperator(name, sciNameToUnaryOp);
}
// Different from Studio syntax, since the operator must be followed by whitespace.
// That is, ++i is not allowed. It must be (++ i)
template<typename _It, typename _TContext, typename _CommentPolicy>
bool SCIOperatorP(const ParserBase<_TContext, _It, _CommentPolicy> *pParser, _TContext *pContext, _It &stream)
{
bool fRet = false;
const char *psz = pParser->_psz;
while (*psz && (*stream == *psz))
{
++stream;
++psz;
}
if (*psz == 0)
{
pContext->ScratchString() = pParser->_psz;
return !!isspace(*stream);
}
else
{
return false;
}
}
template<typename _T, typename _TOperator>
void SetOperatorA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->CreateSyntaxNode<_T>(stream);
_TOperator op = SCINameToOperator<_TOperator>(pContext->ScratchString());
assert(op != _TOperator::None);
pContext->GetSyntaxNode<_T>()->Operator = op;
}
}
void SetRepeatStatementA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->CreateSyntaxNode<WhileLoop>(stream);
pContext->GetSyntaxNode<WhileLoop>()->SetPosition(stream.GetPosition());
// A repeat loop is just a while (TRUE) loop
// 1 = TRUE
pContext->GetSyntaxNode<WhileLoop>()->SetCondition(make_unique<ConditionalExpression>(make_unique<PropertyValue>(1)));
}
}
template<typename _TBreakContinue>
void FinishBreakContinueIfA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
// We should have an If statement. Add the current thing to its conditional.
pContext->GetSyntaxNode<IfStatement>()->SetCondition(make_unique<ConditionalExpression>(move(pContext->StatementPtrReturn)));
// And its contents should be a CodeBlock with a single Break/Continue statement.
auto codeBlock = make_unique<CodeBlock>();
auto breakOrContinue = make_unique<_TBreakContinue>();
breakOrContinue->SetPosition(stream.GetPosition());
codeBlock->AddStatement(move(breakOrContinue));
pContext->GetSyntaxNode<IfStatement>()->SetStatement1(move(codeBlock));
}
}
template<typename _TBreakContinue>
_TBreakContinue *GetBreakContinueInIf(SyntaxContext *pContext)
{
// Get a break inside an if then clause
auto codeBlock = SafeSyntaxNode<CodeBlock>(pContext->GetSyntaxNode<IfStatement>()->GetStatement1());
return SafeSyntaxNode<_TBreakContinue>(codeBlock->GetStatements()[0].get());
}
template<typename _TBreakContinue>
_TBreakContinue *GetBreakContinue(SyntaxContext *pContext)
{
return pContext->GetSyntaxNode<_TBreakContinue>();
}
template<typename _TBreakContinue, _TBreakContinue *(*_TGetFunc)(SyntaxContext *)>
void SetLevelsA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
_TGetFunc(pContext)->Levels = pContext->Integer;
}
}
void FinishClassProcedureA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
// Add it to the script's procedures, not the class' methods.
auto proc = pContext->GetFunctionAsProcedure();
proc->SetClass(pContext->ClassPtr.get()->GetName());
pContext->Script().AddProcedure(move(proc));
}
else
{
pContext->ReportError("Expected method declaration.", stream);
}
}
template<typename _T>
void SetStatementAsConditionA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
// Take the current statement, and put into the next statements conditional expression
pContext->GetSyntaxNode<_T>()->SetCondition(make_unique<ConditionalExpression>(move(pContext->StatementPtrReturn)));
}
}
template<typename _T>
void AddCodeBlockA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
// Time to add a code block. First, get it.
pContext->GetSyntaxNode<_T>()->SetCodeBlock(pContext->StealStatementReturn<CodeBlock>());
}
}
void AddLooperCodeBlockA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
// Time to add a code block. First, get it.
pContext->GetSyntaxNode<ForLoop>()->SetLooper(pContext->StealStatementReturn<CodeBlock>());
}
}
template<typename _T>
void SetCaseA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
// This is the variable description we need to add to the assignment thing:
pContext->GetSyntaxNode<_T>()->AddCase(pContext->StealStatementReturn<CaseStatement>());
}
}
#ifdef ENABLE_EXISTS
void ExistsA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
// Turn &exists foobar into:
// (> argc SOME_NUM_TO_BE_DETERMINED)
pContext->GetSyntaxNode<BinaryOp>()->Operator = BinaryOperator::GreaterThan;
pContext->GetSyntaxNode<BinaryOp>()->SetStatement1(make_unique<PropertyValue>("paramTotal", ValueType::Token)); // Does it need to be ComplexPropertyValue??
pContext->GetSyntaxNode<BinaryOp>()->SetStatement2(make_unique<PropertyValue>(pContext->ScratchString(), ValueType::ParameterIndex));
}
}
#endif
#ifdef ENABLE_VERBS
unique_ptr<FunctionSignature> _CreateVerbHandlerSignature()
{
unique_ptr<FunctionSignature> signature = make_unique<FunctionSignature>();
signature->AddParam("theVerb");
return signature;
}
unique_ptr<FunctionSignature> _CreateIsVerbHandlerSignature()
{
unique_ptr<FunctionSignature> signature = make_unique<FunctionSignature>();
signature->AddParam("theVerb");
return signature;
}
void SyntaxContext::CreateVerbHandler()
{
FunctionPtr = std::make_unique<sci::VerbHandlerDefinition>();
FunctionPtr->AddSignature(_CreateVerbHandlerSignature());
}
void CreateVerbHandlerA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->CreateVerbHandler();
pContext->FunctionPtr->SetOwnerClass(pContext->ClassPtr.get());
}
}
void FinishVerbHandlerA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->ClassPtr->AddVerbHandler(move(std::unique_ptr<sci::VerbHandlerDefinition>(static_cast<sci::VerbHandlerDefinition*>(pContext->FunctionPtr.release()))));
}
else
{
pContext->ReportError("Expected verb handler declaration.", stream);
}
}
void VerbClauseVerbA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->GetSyntaxNode<VerbClauseStatement>()->Verbs.push_back(PropertyValue(pContext->ScratchString(), ValueType::Token));
}
}
#endif
void InitEnumStartA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result()) { pContext->Integer = 0; }
}
void CreateEnumDefineA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
if (pContext->ifDefDefineState != IfDefDefineState::False)
{
auto define = make_unique<Define>(pContext->ScratchString(), pContext->Integer++);
define->SetScript(&pContext->Script());
define->SetPosition(stream.GetPosition());
pContext->Script().AddDefine(move(define));
}
}
}
void RestructureNaryAssociativeOpA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
// Restructure (a b c d e) into (a (b (c (d e))))
// We want evaluation to procede left to right
auto naryOp = pContext->StealSyntaxNode<NaryOp>();
auto &statements = naryOp->GetStatements();
size_t operandCount = statements.size();
assert(operandCount >= 2);
auto binaryOp = make_unique<BinaryOp>(naryOp->Operator);
binaryOp->SetPosition(naryOp->GetPosition());
auto it = statements.rbegin();
binaryOp->SetStatement2(move(*it));
++it;
for (; it != statements.rend(); ++it)
{
if (!binaryOp->GetStatement1())
{
binaryOp->SetStatement1(move(*it));
}
else
{
// Make a new op.
auto newBinaryOp = make_unique<BinaryOp>(naryOp->Operator);
newBinaryOp->SetStatement2(move(binaryOp));
binaryOp = move(newBinaryOp);
binaryOp->SetPosition(naryOp->GetPosition());
binaryOp->SetStatement1(move(*it));
}
}
// Now set this back in as the current syntax node.
pContext->ReplaceSyntaxNode(move(binaryOp));
}
}
const size_t MaxOpLength = 4;
// Takes the operators, sorts them, puts them into a double-null terminated string.
std::vector<char> GenerateOperatorStringWorker(const set<std::string> &ops)
{
std::vector<char> result;
// Organize these by group
std::map<char, std::set<std::string>> temp;
bool hasEmpty = false;
for (auto op : ops)
{
assert(op.length() <= MaxOpLength);
// TODO: Deal with empties
hasEmpty = hasEmpty || !op[0];
if (op[0])
{
temp[op[0]].insert(op.substr(1));
}
}
// The size of our current level, plus an extra for "empty" (op that terminates at this level) and a sentinel indicating the end of this level.
size_t relativeOffsetToNext = (temp.size() + (hasEmpty ? 1 : 0)) * 2 + 1;
std::vector<std::vector<char>> subEntries;
for (auto &entry : temp)
{
std::vector<char> subEntry = GenerateOperatorStringWorker(entry.second);
result.push_back(entry.first); // The char
assert(relativeOffsetToNext < 128);
result.push_back((char)relativeOffsetToNext);
relativeOffsetToNext += subEntry.size();
subEntries.push_back(subEntry);
}
if (hasEmpty)
{
// Deal with it last.
result.push_back(' '); // A space, indicating the end
result.push_back(0); // Zero, indicating no offset to next char list.
}
// Finally, the sentinel value indicating the end:
result.push_back(0);
// Now copy the sub entries
for (auto &subEntry : subEntries)
{
copy(subEntry.begin(), subEntry.end(), back_inserter(result));
}
return result;
}
std::string GenerateOperatorString(const set<std::string> &ops)
{
auto result = GenerateOperatorStringWorker(ops);
return std::string(result.begin(), result.end());
}
template<typename _TContext>
bool SCIOptimizedOperatorP(const ParserSCI *pParser, _TContext *pContext, streamIt &stream)
{
const char *currentdb = pParser->_psz;
char finalOperator[MaxOpLength + 1];
char *buildOperator = finalOperator;
char ch;
while (ch = *stream)
{
const char *currentDbStart = currentdb;
// not at end not equal to char and isn't end of op
while (*currentdb && (ch != *currentdb) && (*currentdb != ' ' || !isspace(ch)))
{
currentdb += 2;
}
if (*currentdb)
{
if (*currentdb == ' ')
{
*buildOperator = 0;
pContext->ScratchString() = finalOperator;
return true;
}
*buildOperator++ = ch;
assert((buildOperator - finalOperator) <= MaxOpLength);
// Adjust offset and continue with the next character
int offset = *(currentdb + 1);
assert(offset);
currentdb = currentDbStart + offset;
}
else
{
// Not a match
return false;
}
++stream;
}
return false;
}
ParserSCI SCISyntaxParser::char_p(const char *psz) { return ParserSCI(CharP, psz); }
ParserSCI SCISyntaxParser::operator_p(const char *psz) { return ParserSCI(SCIOptimizedOperatorP, psz); }
ParserSCI SCISyntaxParser::keyword_p(const char *psz) { return ParserSCI(KeywordP, psz); }
ParserSCI SCISyntaxParser::generateSyntaxNodeD()
{
ParserSCI syntaxnode(SyntaxNodeD);
return syntaxnode[EndSyntaxNodeA];
}
template<typename _It, typename _TContext, typename _CommentPolicy>
bool QuotedStringSCIP(const ParserBase<_TContext, _It, _CommentPolicy> *pParser, _TContext *pContext, _It &stream)
{
return _ReadStringSCI<_TContext, _It, '"', '"'>(pContext, stream, pContext->ScratchString());
}
template<typename _It, typename _TContext, typename _CommentPolicy>
bool BraceStringSCIP(const ParserBase<_TContext, _It, _CommentPolicy> *pParser, _TContext *pContext, _It &stream)
{
return _ReadStringSCI<_TContext, _It, '{', '}'>(pContext, stream, pContext->ScratchString());
}
template<typename _It, typename _TContext, typename _CommentPolicy>
void ValueErrorE(MatchResult &match, const ParserBase<_TContext, _It, _CommentPolicy> *pParser, _TContext *pContext, const _It &stream)
{
if (!match.Result())
{
pContext->ReportError("Expected an expression.", stream);
}
}
void CreateSynA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->CreateSynonym();
pContext->SynonymPtr->MainWord = pContext->ScratchString();
pContext->SynonymPtr->SetPosition(stream.GetPosition());
}
else
{
pContext->ReportError("Expected word.", stream);
}
}
void AddSynA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->SynonymPtr->Synonyms.push_back(pContext->ScratchString());
}
else
{
pContext->ReportError("Expected word.", stream);
}
}
void FinishSynA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->Script().AddSynonym(std::move(pContext->SynonymPtr));
}
}
void SaveScratchStringA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->ScratchString2() = pContext->ScratchString();
}
}
void SaveGlobalVarIndexA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->Integer2 = pContext->Integer;
pContext->PropertyValueWasSet = false; // Also reset this.
}
}
void AddExternDeclA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
auto externDecl = make_unique<ExternDeclaration>();
externDecl->SetName(pContext->ScratchString2());
assert(pContext->PropertyValueWasSet);
externDecl->ScriptNumber = pContext->PropertyValue;
externDecl->Index = pContext->Integer;
externDecl->SetPosition(stream.GetPosition());
pContext->Script().Externs.push_back(move(externDecl));
}
}
void AddSelectorDeclA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
auto selectorDecl = make_unique<SelectorDeclaration>();
selectorDecl->SetName(pContext->ScratchString());
selectorDecl->Index = pContext->Integer;
selectorDecl->SetPosition(stream.GetPosition());
pContext->Script().Selectors.push_back(move(selectorDecl));
}
}
void AddClassDefDeclA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->Script().ClassDefs.push_back(pContext->StealSyntaxNode<ClassDefDeclaration>());
}
}
void SetScriptNumberA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->GetSyntaxNode<ClassDefDeclaration>()->ScriptNumber = pContext->Integer;
}
else
{
pContext->ReportError(errInteger, stream);
}
}
void SetClassNumberA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->GetSyntaxNode<ClassDefDeclaration>()->ClassNumber = pContext->Integer;
}
else
{
pContext->ReportError(errInteger, stream);
}
}
void SetSuperNumberA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->GetSyntaxNode<ClassDefDeclaration>()->SuperNumber = pContext->Integer;
}
else
{
pContext->ReportError(errInteger, stream);
}
}
void SetFileA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->GetSyntaxNode<ClassDefDeclaration>()->File = pContext->ScratchString();
}
else
{
pContext->ReportError(errFileNameString, stream);
}
}
void AddClassDefPropA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result()) { pContext->GetSyntaxNode<ClassDefDeclaration>()->Properties.push_back({ pContext->ScratchString(), pContext->Integer }); }
}
void AddClassDefMethodA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result()) { pContext->GetSyntaxNode<ClassDefDeclaration>()->Methods.push_back(pContext->ScratchString()); }
}
void AddGlobalEntryA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
auto globalEntry = std::make_unique<GlobalDeclaration>();
globalEntry->Index = pContext->Integer2;
if (pContext->PropertyValueWasSet)
{
globalEntry->InitialValue = std::make_unique<PropertyValue>(pContext->PropertyValue);
}
globalEntry->SetName(pContext->ScratchString2());
pContext->Script().Globals.push_back(move(globalEntry));
}
}
void AddMethodFwdA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->ClassPtr->MethodForwards.push_back(pContext->ScratchString());
}
}
void AddProcedureFwdA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->Script().ProcedureForwards.push_back(pContext->ScratchString());
}
}
#ifdef ENABLE_FOREACH
void SetIterationVariableA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->GetSyntaxNode<ForEachLoop>()->IterationVariable = pContext->ScratchString();
}
}
#ifdef ENABLE_LDMSTM
void SetIsReferenceA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->GetSyntaxNode<ForEachLoop>()->IsReference = true;
}
}
#endif
#endif
#ifdef ENABLE_LDMSTM
void DerefLValueA(MatchResult &match, const ParserSCI *pParser, SyntaxContext *pContext, const streamIt &stream)
{
if (match.Result())
{
pContext->CreateSyntaxNode<LValue>(stream);
pContext->GetSyntaxNode<LValue>()->IsDeref = true;
pContext->GetSyntaxNode<LValue>()->SetPosition(stream.GetPosition());
pContext->GetSyntaxNode<LValue>()->SetName(pContext->ScratchString());
}
}
#endif
SCISyntaxParser::SCISyntaxParser() :
oppar(char_p("(")),
clpar(char_p(")")),
opbracket(char_p("[")),
clbracket(char_p("]")),
pound(char_p("#")),
atsign(char_p("@")),
comma(char_p(",")),
colon(char_p(":")),
equalSign(char_p("=")),
question(char_p("?")),
#ifdef ENABLE_LDMSTM
period(char_p("*")),
ampersand(char_p("&")),
#endif
alphanumAsmLabel_p(AlphanumP),
selector_send_p(SelectorP_Term<':'>),
propget_p(SelectorP_Term<'?'>),
filename_p(FilenameP),
asmInstruction_p(AsmInstructionP),
alphanumNK_p(AlphanumPNoKeywordOrTerm),
alphanumNK_p2(AlphanumPNoKeywordOrTerm2),
alphanumSendToken_p(AlphanumPSendTokenOrTerm),
alphanum_p(AlphanumP),
alwaysmatch_p(AlwaysMatchP),
bracestring_p(BraceStringSCIP),
squotedstring_p(SQuotedStringP),
quotedstring_p(QuotedStringSCIP),
integer_p(IntegerExpandedP),
integerNonZero_p(IntegerNonZeroP),
syntaxnode_d(generateSyntaxNodeD())
{
}
//
// The constructor sets up the parse tree
//
void SCISyntaxParser::Load()
{
if (_fLoaded)
{
return;
}
_fLoaded = true;
// Some defaults.
ParseACChannels ch1StartStatement = SetChannel(NoChannels, ParseAutoCompleteChannel::One, ParseAutoCompleteContext::StartStatementExtras);
ParseACChannels ch1Block = SetChannel(NoChannels, ParseAutoCompleteChannel::One, ParseAutoCompleteContext::Block);
ParseACChannels ch2PureValue = SetChannel(NoChannels, ParseAutoCompleteChannel::Two, ParseAutoCompleteContext::PureValue);
ParseACChannels ch2Block = SetChannel(NoChannels, ParseAutoCompleteChannel::Two, ParseAutoCompleteContext::Block);
ParseACChannels ch3Selector = SetChannel(NoChannels, ParseAutoCompleteChannel::Three, ParseAutoCompleteContext::Selector);
ParseACChannels ch3Keyword = SetChannel(NoChannels, ParseAutoCompleteChannel::Three, ParseAutoCompleteContext::ClassLevelKeyword);
ParseACChannels ch3Block = SetChannel(NoChannels, ParseAutoCompleteChannel::Three, ParseAutoCompleteContext::Block);
ParseACChannels ch4Rest = SetChannel(NoChannels, ParseAutoCompleteChannel::Four, ParseAutoCompleteContext::Rest);
ParseACChannels ch4Else = SetChannel(NoChannels, ParseAutoCompleteChannel::Four, ParseAutoCompleteContext::Else);
ParseACChannels ch4Block = SetChannel(NoChannels, ParseAutoCompleteChannel::Four, ParseAutoCompleteContext::Block);
// (xxx -> procname, pure value or keyword
// (something xxx -> pure value or selector name
ParseACChannels acStartStatement = ch1StartStatement | ch2PureValue | ch3Keyword | ch4Block;
ParseACChannels acJustAValue = ch1Block | ch2PureValue; // Don't block channel 3, because parent parser might want to add in selectors, not sure about ch4
ParseACChannels acInSendOrProcCall = ch1Block | ch2PureValue | ch3Selector | ch4Rest;
// The else in an if statement is special because it doesn't need to be enclosed in ()
ParseACChannels acElseAddin = ch4Else;
// We could do more for else here, like removing it from the keywords list, and then manually adding
// it back for case statements in switch or cond statements.
// An integer or plain alphanumeric token
immediateValue = integer_p[PropValueIntA<errInteger>] | alphanumNK_p[PropValueStringA<ValueType::Token, errNoKeywordOrSelector>];
string_immediateValue_NoResourceString = integer_p[PropValueIntA<errInteger>] | alphanumNK_p[PropValueStringA<ValueType::Token, errNoKeywordOrSelector>] | quotedstring_p[{PropValueStringA<ValueType::String>, ParseAutoCompleteContext::Block}] | bracestring_p[PropValueStringA<ValueType::String>] | squotedstring_p[{PropValueStringA<ValueType::Said>, ParseAutoCompleteContext::Block}] | size_of[PropValueStringA<ValueType::ArraySize>];
// Top level constructs
include = keyword_p("include") >> (quotedstring_p | filename_p)[{AddIncludeA, ParseAutoCompleteContext::Block}];
use = keyword_p("use") >> (quotedstring_p | filename_p)[{AddUseA, ParseAutoCompleteContext::ScriptName}];
scriptNum = keyword_p("script#") >> immediateValue[{ScriptNumberA, ParseAutoCompleteContext::DefineValue }];
genText = keyword_p("text#") >> immediateValue[{GenTextA, ParseAutoCompleteContext::DefineValue }];
define = keyword_p("define")[CreateDefineA] >> alphanumNK_p[DefineLabelA] >> integer_p[DefineValueA];
enumStatement = keyword_p("enum")[InitEnumStartA] >> -integer_p[ErrorA<errInteger>] >> *alphanumNK_p[CreateEnumDefineA];
general_token = (alphanumNK_p)[{nullptr, ParseAutoCompleteContext::None, "TOKEN"}];
// Matches #posn
// Also matches #posn? or #posn: for backwards compatibility.
selector_literal = pound >> (alphanumNK_p2[{nullptr, ParseAutoCompleteContext::Selector}] | selector_send_p);
size_of = keyword_p("&sizeof") >> alphanumNK_p[{nullptr, ParseAutoCompleteContext::PureValue}];
#ifdef ENABLE_EXISTS
exists_statement = keyword_p("&exists")[SetStatementA<BinaryOp>] >> alphanumNK_p[{ExistsA, ParseAutoCompleteContext::PureValue}];
#endif
pointer = atsign;
export_entry = general_token[{nullptr, ParseAutoCompleteContext::Export}] >> integer_p[AddExportA];
exports = keyword_p("public") >> *export_entry;
synonym_entry = oppar >> alphanum_p[CreateSynA] >> *alphanum_p[AddSynA] >> clpar;
synonyms = keyword_p("synonyms") >> *synonym_entry[FinishSynA];
rvalue_variable =
(opbracket >> general_token[ComplexValueStringA<ValueType::Token, errVarName>] >> statement[ComplexValueIndexerA] >> clbracket) |
general_token[ComplexValueStringA<ValueType::Token>];
value =
alwaysmatch_p[SetStatementA<ComplexPropertyValue>]
>> (integer_p[ComplexValueIntA]
| keyword_p("argc")[ComplexValueParamTotalA]
| quotedstring_p[{ComplexValueStringA<ValueType::ResourceString>, ParseAutoCompleteContext::Block}]
| squotedstring_p[{ComplexValueStringA<ValueType::Said>, ParseAutoCompleteContext::Block}]
| bracestring_p[{ComplexValueStringA<ValueType::String>, ParseAutoCompleteContext::Block}]
| (-pointer[ComplexValuePointerA] >> rvalue_variable)
#ifdef ENABLE_LDMSTM
| (period >> general_token[ComplexValueStringA<ValueType::Deref>])
#endif
| selector_literal[ComplexValueStringA<ValueType::Selector>]
| size_of[ComplexValueStringA<ValueType::ArraySize>]);
repeat_statement =
keyword_p("repeat")[SetRepeatStatementA]
>> *statement[AddStatementA<WhileLoop>];
return_statement =
keyword_p("return")[SetStatementA<ReturnStatement>]
>> -statement[StatementBindTo1stA<ReturnStatement, nullptr>];
break_statement =
keyword_p("break")[SetStatementA<BreakStatement>] >>
-integerNonZero_p[SetLevelsA<BreakStatement, GetBreakContinue<BreakStatement>>];
breakif_statement =
keyword_p("breakif")[SetStatementA<IfStatement>]
>> statement[FinishBreakContinueIfA<BreakStatement>] >>
-integerNonZero_p[SetLevelsA<BreakStatement, GetBreakContinueInIf<BreakStatement>>];
continue_statement =
keyword_p("continue")[SetStatementA<ContinueStatement>] >>
-integerNonZero_p[SetLevelsA<ContinueStatement, GetBreakContinue<ContinueStatement>>];
contif_statement =
keyword_p("contif")[SetStatementA<IfStatement>]
>> statement[FinishBreakContinueIfA<ContinueStatement>] >>
-integerNonZero_p[SetLevelsA<ContinueStatement, GetBreakContinueInIf<ContinueStatement>>];
bare_code_block =
alwaysmatch_p[StartStatementA]
>> (alwaysmatch_p[SetStatementA<CodeBlock>]
>> *statement[AddStatementA<CodeBlock>])[FinishStatementA];
wrapped_code_block =
oppar[StartStatementA]
>> (alwaysmatch_p[SetStatementA<CodeBlock>]
>> *statement[AddStatementA<CodeBlock>] >> clpar)[FinishStatementA];
if_statement =
keyword_p("if")[SetStatementA<IfStatement>]
>> statement[SetStatementAsConditionA<IfStatement>] // Condition
>> bare_code_block[{StatementBindTo1stA<IfStatement, errThen>, acElseAddin }] // Code
>> -(keyword_p("else") // Optional else, followed by more code
>> bare_code_block[StatementBindTo2ndA<IfStatement, errElse>]);
while_loop =
keyword_p("while")[SetStatementA<WhileLoop>]
>> statement[SetStatementAsConditionA<WhileLoop>]
>> *statement[AddStatementA<WhileLoop>];
for_loop =
keyword_p("for")[SetStatementA<ForLoop>]
>> wrapped_code_block[AddCodeBlockA<ForLoop>]
>> statement[SetStatementAsConditionA<ForLoop>]
>> wrapped_code_block[AddLooperCodeBlockA]
>> *statement[AddStatementA<ForLoop>];
#ifdef ENABLE_FOREACH
foreach_loop =
keyword_p("foreach")[SetStatementA<ForEachLoop>]
#ifdef ENABLE_LDMSTM
>> -ampersand[SetIsReferenceA]
#endif
>> general_token[SetIterationVariableA]
>> statement[StatementBindTo1stA<ForEachLoop, errCollectionArg>]
>> *statement[AddStatementA<ForEachLoop>];
#endif
#ifdef ENABLE_GETPOLY
getpoly_statement =
keyword_p("&getpoly")[SetStatementA<GetPolyStatement>]
>> statement[StatementBindTo1stA<GetPolyStatement, nullptr>];
#endif
case_statement =
alwaysmatch_p[StartStatementA]
>> (oppar[SetStatementA<CaseStatement>]
>>
(keyword_p("else")[SetDefaultCaseA] |
statement[StatementBindTo1stA<CaseStatement, errCaseArg>])[NoCaseE] // REVIEW: does this need to be constant?
>> *statement[AddStatementA<CaseStatement>]
>> clpar[GeneralE]
)[FinishStatementA];
switch_statement =
keyword_p("switch")[SetStatementA<SwitchStatement>]
>> statement[StatementBindTo1stA<SwitchStatement, errSwitchArg>]
>> *case_statement[SetCaseA<SwitchStatement>];
// Nearly identical parsing to a switch statement. We re-work it to ifs in post-processing.
cond_statement =
keyword_p("cond")[SetStatementA<CondStatement>]
>> *case_statement[SetCaseA<CondStatement>];
switchto_case_statement =
alwaysmatch_p[StartStatementA]
>> (oppar[SetStatementA<CaseStatement>]
>> *statement[AddStatementA<CaseStatement>]
>> clpar[GeneralE]
)[FinishStatementA];
switchto_statement =
keyword_p("switchto")[SetStatementA<SwitchStatement>]
>> statement[StatementBindTo1stA<SwitchStatement, errSwitchArg>]
>> *switchto_case_statement[SetCaseA<SwitchStatement>];
// (SomeProc param1 param2 param3)
procedure_call = alphanumNK_p[SetStatementNameA<ProcedureCall>] >> (*statement[AddStatementA<ProcedureCall>])[{nullptr, acInSendOrProcCall}];
// posn: x y z
send_param_call = selector_send_p[SetStatementNameA<SendParam>] >> alwaysmatch_p[SendParamIsMethod] >> *statement[AddStatementA<SendParam>];
// expression selectorA: one two three, selectorB: one two
// expression selectorA?
send_call = (alwaysmatch_p[SetStatementA<SendCall>] // Simple form, e.g. gEgo
>> ((alphanumSendToken_p[SetNameA<SendCall>]) | statement[StatementBindTo1stA<SendCall, errSendObject>])) // Expression, e.g. [clients 4], or (GetTheGuy)
>>
(propget_p[AddSimpleSendParamA] | // Single prop get
(syntaxnode_d[send_param_call[AddSendParamA]] % -comma[GeneralE]) // Or a series regular ones separated by optional comma
)[{nullptr, acInSendOrProcCall}] // AC stuff that's inside a send call
;
// Operators
// These are binary-only operators
binaryOps = GenerateOperatorString({ ">>", "<<", "-", "/", "mod" });
binary_operator = operator_p(binaryOps.c_str());
// n-ary operators that are associative
naryAssocOps = GenerateOperatorString({ "*", "+", "&", "|", "^", "and", "or" });
naryassoc_operator = operator_p(naryAssocOps.c_str());
// n-ary comparison operators
naryCompareOps = GenerateOperatorString({ "u>=", ">=", "u>", ">", "u<=", "<=", "u<", "!=", "<", "==" });
narycompare_operator = operator_p(naryCompareOps.c_str());
unaryOps = GenerateOperatorString({"~", "not", "-", "++", "--" });
unary_operator = operator_p(unaryOps.c_str());
assignmentOps = GenerateOperatorString({ "+=", "-=", "*=", "/=", "mod=", "&=", "|=", "^=", ">>=", "<<=", "=" });
assignment_operator = operator_p(assignmentOps.c_str());
// blarg or [blarg statement]
lvalue = (opbracket >> general_token[{SetStatementNameA<LValue>, ParseAutoCompleteContext::LValue}] >> statement[LValueIndexerA] >> clbracket) |
keyword_p("argc")[SetStatementNameToParamTotalA<LValue>] |
#ifdef ENABLE_LDMSTM
(period >> general_token[{DerefLValueA, ParseAutoCompleteContext::LValue}]) |
#endif
general_token[{SetStatementNameA<LValue>, ParseAutoCompleteContext::LValue}];
rest_statement =
keyword_p("&rest")[SetStatementA<RestStatement>]
>> -alphanumNK_p[SetStatementNameA<RestStatement>];
assignment =
assignment_operator[SetOperatorA<Assignment, AssignmentOperator>]
>> syntaxnode_d[lvalue[AssignmentVariableA]]
>> statement[StatementBindTo1stA<Assignment, errArgument>];
// + 5 view
binary_operation =
binary_operator[SetOperatorA<BinaryOp, BinaryOperator>]
>> statement[StatementBindTo1stA<BinaryOp, errArgument>]
>> statement[StatementBindTo2ndA<BinaryOp, errBinaryOp>];
// (+ 1 2 3 4 5)
// These are parsed temporarily into a NaryOp node, then restructured into next BinaryOp nodes for maximum re-usability.
// At least two parameters are required.
naryassoc_operation =
(naryassoc_operator[SetOperatorA<NaryOp, BinaryOperator>]
>> statement[AddStatementA<NaryOp>]
>> ++statement[AddStatementA<NaryOp>])[RestructureNaryAssociativeOpA];
// (< 3 5 9 10)
narycompare_operation =
(narycompare_operator[SetOperatorA<NaryOp, BinaryOperator>]
>> statement[AddStatementA<NaryOp>]
>> ++statement[AddStatementA<NaryOp>]);
// ~ signal
unary_operation =
unary_operator[SetOperatorA<UnaryOp, UnaryOperator>]
>> statement[StatementBindTo1stA<UnaryOp, errArgument>];
asm_arg =
alwaysmatch_p[StartStatementA]
>> value[FinishStatementA]
>> !(colon | question); // If colon, then it's the next line's label, if question it's actaully an opcode (e.g. le? ne?)
asm_label =
alphanumAsmLabel_p
>> colon[SetLabelA];
asm_statement =
alwaysmatch_p[StartStatementA]
>> (alwaysmatch_p[SetStatementA<Asm>]
>> -asm_label // Optional label
>> asmInstruction_p[SetNameA<Asm>] // Instruction name
>> -(asm_arg[AddStatementA<Asm>] % comma[GeneralE]))[FinishStatementA]; // command separated values
asm_block = keyword_p("asm")[SetStatementA<AsmBlock>]
>> alwaysmatch_p[SetOpcodesExtraKeywordsA]
>> *asm_statement[AddStatementA<AsmBlock>]
>> alwaysmatch_p[RemoveExtraKeywordsA];
// All possible statements.
statement = alwaysmatch_p[StartStatementA]
>>
(
(oppar >>
// Add more here
(
repeat_statement |
assignment |
binary_operation |
unary_operation | // Due to -, unary must come after binary.
naryassoc_operation |
narycompare_operation |
return_statement |
#ifdef ENABLE_EXISTS
exists_statement |
#endif
if_statement |
while_loop |
for_loop |
#ifdef ENABLE_FOREACH
foreach_loop |
#endif
#ifdef ENABLE_GETPOLY
getpoly_statement |
#endif
cond_statement |
switchto_statement |
switch_statement |
breakif_statement |
break_statement |
continue_statement |
contif_statement |
asm_block |
send_call | // Send has to come before procedure. Because procedure will match (foo sel:)
procedure_call
)[{nullptr, acStartStatement}] >>
clpar)
| (rest_statement
| value)[{ValueErrorE, acJustAValue }]
)[FinishStatementA];
// TODO: we could change this to allow for constant expressions here (that can be evaluated)
// An array initializer
array_init = opbracket >> *(statement[ScriptVarInitAutoExpandA]) >> clbracket; // [0 0 $4c VIEW_EGO]
// Variable declaration, with optional array size (array size must be numeric!)
// A or [A 6] or [A MY_ARRAY_SIZE]
var_decl =
(opbracket >> alphanumNK_p[CreateVarDeclA] >> (integer_p[VarDeclSizeA] | alphanumNK_p[VarDeclSizeConstantA])[VarDeclSizeErrorA] >> clbracket) |
alphanumNK_p[CreateVarDeclA];
script_var = keyword_p("local")
>> *((var_decl[CreateScriptVarA] >> -(equalSign[GeneralE] >> (statement[ScriptVarInitA] | array_init)))[FinishScriptVarA]);
// StartFunctionTempVarA is needed to reset "was initializer value set". There are no initializer values for function variables in this syntax.
function_var_decl = keyword_p("&tmp")[{ StartFunctionTempVarA, ParseAutoCompleteContext::Temp }] >> ++(var_decl[FinishFunctionTempVarA]);
property_decl = alphanumNK_p[{CreateClassPropertyA, ParseAutoCompleteContext::ClassSelector}]
>> statement[FinishClassPropertyStatementA];
// (procname param0 param1 &tmp tmp0 tmp1 tmp2)
procedure_base = oppar
>> alphanumNK_p[FunctionNameA]
>> *alphanumNK_p[FunctionParameterA]
>> *function_var_decl
>> clpar[GeneralE]
>> *statement[FunctionStatementA];
procedure_decl = keyword_p("procedure")[CreateProcedureA] >> procedure_base[{FunctionCloseA, ParseAutoCompleteContext::Block}];
// Unsupported (unneeded) methods forward declaration
// (methods
// m1
// m2
// m3
// )
methods_fwd = keyword_p("methods")[{nullptr, ParseAutoCompleteContext::ClassLevelKeyword}] >> *alphanumNK_p[AddMethodFwdA];
// Very similar to procedure_base, but with some autocomplete differences:
method_base = oppar
>> alphanumNK_p[{FunctionNameA, ParseAutoCompleteContext::Selector}]
>> *alphanumNK_p[{FunctionParameterA, ParseAutoCompleteContext::Block}]
>> *function_var_decl
>> clpar[GeneralE]
>> *statement[FunctionStatementA];
method_decl = keyword_p("method")[{CreateMethodA, ParseAutoCompleteContext::ClassLevelKeyword}] >> method_base[FunctionCloseA];
#ifdef ENABLE_VERBS
verb_clause =
alwaysmatch_p[StartStatementA]
>> (oppar[SetStatementA<VerbClauseStatement>]
>> (alphanumNK_p[{VerbClauseVerbA, ParseAutoCompleteContext::DefineValue}] % comma[GeneralE]) // comma separated verbs - must have at least one verb though.
>> *statement[AddStatementA<VerbClauseStatement>] // then code
>> clpar[GeneralE])[FinishStatementA];
// here - first just get nearVerbs working, then do an OR for the thing
verb_handler_decl = keyword_p("verbs")[{CreateVerbHandlerA, ParseAutoCompleteContext::ClassLevelKeyword}]
// >> // Todo, allow for temp vars I guess. Not sure how though.
>> *verb_clause[FunctionStatementA];
#endif
// The properties thing in a class or instance
properties_decl = oppar >> keyword_p("properties")[{nullptr, ParseAutoCompleteContext::ClassLevelKeyword}] >> *property_decl >> clpar;
classbase_decl =
alphanumNK_p[ClassNameA]
// Though our official syntax is "of", we'll also support kindof for Sierra compatibility.
>> -((keyword_p("of")[GeneralE] | keyword_p("kindof")[GeneralE]) >> alphanumNK_p[{ClassSuperA, ParseAutoCompleteContext::SuperClass}])
>> -properties_decl
>> *(oppar[GeneralE] >>
(
methods_fwd |
method_decl[FinishClassMethodA] |
#ifdef ENABLE_VERBS
verb_handler_decl[FinishVerbHandlerA] |
#endif
procedure_decl[FinishClassProcedureA]) >> clpar);
instance_decl = keyword_p("instance")[CreateClassA<true>] >> classbase_decl[ClassCloseA];
class_decl = keyword_p("class")[CreateClassA<false>] >> classbase_decl[ClassCloseA];
// Non-code items:
class_def =
keyword_p("classdef")[SetStatementA<ClassDefDeclaration>] >> alphanumNK_p[SetNameA<ClassDefDeclaration>]; // TODO
extern_entry =
general_token[SaveScratchStringA] >> immediateValue >> integer_p[AddExternDeclA];
extern_section =
keyword_p("extern") >> *extern_entry;
selector_entry =
general_token >> integer_p[AddSelectorDeclA];
selector_section =
keyword_p("selectors") >> *selector_entry;
class_def_attributes =
(keyword_p("script#") >> integer_p[SetScriptNumberA]) |
(keyword_p("class#") >> integer_p[SetClassNumberA]) |
(keyword_p("super#") >> integer_p[SetSuperNumberA]) |
(keyword_p("file#") >> quotedstring_p[SetFileA]);
class_def_internal = alphanumNK_p[SetStatementNameA<ClassDefDeclaration>] >>
*class_def_attributes >>
oppar[GeneralE] >> keyword_p("properties") >> *(alphanumNK_p >> integer_p)[AddClassDefPropA] >> clpar[GeneralE] >>
oppar[GeneralE] >> keyword_p("methods") >> *alphanumNK_p[AddClassDefMethodA] >> clpar[GeneralE];
class_def =
keyword_p("classdef") >> syntaxnode_d[class_def_internal[AddClassDefDeclA]];
global_entry =
general_token[SaveScratchStringA] >> integer_p[SaveGlobalVarIndexA] >> -(equalSign[GeneralE] >> immediateValue);
global_section =
keyword_p("global") >> *global_entry[AddGlobalEntryA];
// Unsupported (unneeded) procedure fwd declaration. Same keyword as an actual procedure
// definition, but no opening paren after (so that's how we distinguish). In-class procs are also declared here.
// (procedure
// GetStatus
// SomeOtherProc
// SaveFile
// )
procedures_fwd =
keyword_p("procedure") >> *alphanumNK_p[AddProcedureFwdA];
entire_script = *(oppar[GeneralE]
>> (include
| use
| define[FinishDefineA]
| enumStatement
| instance_decl[FinishClassA]
| class_decl[FinishClassA]
| procedure_decl[FinishProcedureA]
| synonyms
| exports
| scriptNum
| genText
// The following are not yet supported, but we'll include them to possibly
// "reserve" for future use.
| extern_section
| global_section
| selector_section
| class_def
| procedures_fwd
| script_var)[{IdentifierE, ParseAutoCompleteContext::TopLevelKeyword}]
>> clpar[GeneralE]);
// And for headers, only defines, includes are allowed. And also #ifdef!
// REVIEW: This is kind of a hack.
entire_header = *
(
(keyword_p("#ifdef") >> alphanumNK_p[EvaluateIfDefA])
| keyword_p("#endif")[EvaluateEndIfA]
|
(oppar[GeneralE] >>
(include |
define[FinishDefineA] |
enumStatement
// The following are not yet supported, but we'll include them to possibly
// "reserve" for future use.
| extern_section
| global_section
| selector_section
| class_def
| procedures_fwd
)[IdentifierE] >>
clpar[GeneralE])
);
}
#ifdef ENABLE_VERBS
unique_ptr<CaseStatement> _MakeVerbHandlerElse()
{
unique_ptr<CaseStatement> theCase = make_unique<CaseStatement>();
theCase->SetDefault(true);
// (super doVerb: verb item &rest)
unique_ptr<SendCall> theSend = make_unique<SendCall>();
theSend->SetName("super");
// Create the send param to add to the send call
unique_ptr<SendParam> param = std::make_unique<SendParam>();
param->SetName("doVerb");
param->SetIsMethod(true);
param->AddStatement(make_unique<PropertyValue>("theVerb", ValueType::Token));
param->AddStatement(make_unique<RestStatement>());
theSend->AddSendParam(move(param));
theCase->AddStatement(move(theSend));
return theCase;
}
void _ProcessVerbHandler(ClassDefinition &theClass, VerbHandlerDefinition &verbHandler, SwitchStatement **pSwitchWeak)
{
unordered_set<string> usedVerbs;
// Make a doVerb method with params verb and item - but only do this once.
unique_ptr<MethodDefinition> doVerbMethod;
// Now create a switch
unique_ptr<SwitchStatement> _switch;
if (!*pSwitchWeak)
{
_switch = make_unique<SwitchStatement>();
_switch->SetStatement1(_MakeTokenStatement("theVerb"));
*pSwitchWeak = _switch.get();
doVerbMethod = make_unique<MethodDefinition>();
doVerbMethod->SetName("doVerb");
doVerbMethod->SetOwnerClass(&theClass);
doVerbMethod->AddSignature(_CreateVerbHandlerSignature());
}
for (auto &statement : verbHandler.GetStatements())
{
assert(statement->GetNodeType() == NodeTypeVerbClause);
VerbClauseStatement &verbClause = static_cast<VerbClauseStatement&>(*statement);
unique_ptr<CaseStatement> theCase = make_unique<CaseStatement>();
theCase->SetCaseValue(make_unique<PropertyValue>(verbClause.Verbs[0]));
// Give all the code to the case statement
swap(theCase->GetStatements(), verbClause.GetStatements());
(*pSwitchWeak)->AddCase(move(theCase));
}
if (_switch)
{
doVerbMethod->AddStatement(move(_switch));
theClass.AddMethod(move(doVerbMethod));
} // but not if we only had a weak ptr.
}
void _ProcessClassForVerbHandlers(Script &script, ClassDefinition &theClass)
{
SwitchStatement *pSwitchWeak = nullptr;
for (auto &verbHandler : theClass.GetVerbHandlers())
{
_ProcessVerbHandler(theClass, *verbHandler, &pSwitchWeak);
}
if (pSwitchWeak)
{
// It means we added one. Put in the default handler:
pSwitchWeak->AddCase(_MakeVerbHandlerElse());
}
}
#endif
#ifdef ENABLE_FOREACH
bool _IsItADeclaredVariable(const VariableDeclVector &varDecls, const string &name)
{
return find_if(varDecls.begin(), varDecls.end(), [&name](const auto &varDecl) { return varDecl->GetName() == name; }) != varDecls.end();
}
void _ReplaceIterationVariable(ICompileLog &log, Script &script, ForEachLoop &theForEach, const std::string &iterationVariableOrig, const std::string &newIterationVariable)
{
// Now replace the iteration variable with the newIterationVariable
// Replace the iteration variable with [bufferName loopIndexVariable]
EnumScriptElements<LValue>(theForEach,
[&log, &script, &iterationVariableOrig, &newIterationVariable](LValue &lValue)
{
if (lValue.GetName() == iterationVariableOrig)
{
// This is us
if (lValue.HasIndexer())
{
log.ReportResult(CompileResult("An iteration variable can not be indexed.", script.GetScriptId(), lValue.GetPosition().Line()));
}
lValue.SetName(newIterationVariable);
}
});
EnumScriptElements<ComplexPropertyValue>(theForEach,
[&log, &script, &iterationVariableOrig, &newIterationVariable](ComplexPropertyValue &propValue)
{
if ((propValue.GetType() == ValueType::Token) && (propValue.GetStringValue() == iterationVariableOrig))
{
// This is us
if (propValue.GetIndexer())
{
log.ReportResult(CompileResult("An iteration variable can not be indexed.", script.GetScriptId(), propValue.GetPosition().Line()));
}
propValue.SetValue(newIterationVariable, ValueType::Token);
}
});
EnumScriptElements<SendCall>(theForEach,
[&log, &script, &iterationVariableOrig, &newIterationVariable](SendCall &theSend)
{
if (theSend.GetTargetName() == iterationVariableOrig)
{
// This is us - if we have a tempvar we can just set a name:
theSend.SetName(newIterationVariable);
}
});
}
void _ProcessForEach(ICompileLog &log, Script &script, FunctionBase &func, ForEachLoop &theForEach, int variableGenHint)
{
// For now, just support arrays
// In the future, we could support params and lists.
// This turns this:
// (foreach boop buffer
// (boop x: 0)
// )
//
// Into:
// (for ((= i 0)) (< i &sizeof buffer) ((++ i))
// ([buffer i] x: 0)
// )
//
// This requires making a new iteration variable.
// Come up with a good loop index name.
string iterationVariableOrig = theForEach.IterationVariable;
string newIterationVariable;
#ifdef ENABLE_LDMSTM
bool isReference = theForEach.IsReference;
if (!isReference)
#endif
{
// If the foreach doesn't use a reference iteration variable, we're going to have an actual variable with this name. To reduce the possibility of conflicts,
// let's muck up the name. This lets us have multiple foreachs using the same iteration variable name in a function.
newIterationVariable = (variableGenHint < 26) ? fmt::format("{}__{}", theForEach.IterationVariable, (char)(variableGenHint + 'A')) : fmt::format("{}__{}", theForEach.IterationVariable, variableGenHint); ;
func.GetVariablesNC().push_back(make_unique<VariableDecl>(newIterationVariable));
}
bool isBuffer = true;
// Buffer name?
string bufferName = "INVALID";
if (theForEach.GetStatement1()->GetNodeType() == sci::NodeType::NodeTypeComplexValue)
{
ComplexPropertyValue &collection = static_cast<ComplexPropertyValue&>(*theForEach.GetStatement1());
if (collection.GetType() == ValueType::Token)
{
bufferName = collection.GetStringValue();
// Now, if this bufferName is a local or temp var, then we can use &sizeof.
// Otherwise, we'll assume it's a FixedList... Or rather, an object with elements and size properties.
//bool isBuffer = find_if(func.GetVariables().begin(), func.GetVariables().end(), [&bufferName](const std::unique_ptr<VariableDecl> &varDecl) { return varDecl->GetName() == bufferName; }) != func.GetVariables().end();
isBuffer = _IsItADeclaredVariable(func.GetVariables(), bufferName) || _IsItADeclaredVariable(script.GetScriptVariables(), bufferName);
}
else
{
log.ReportResult(CompileResult("The collection must be a temp or local array.", script.GetScriptId(), collection.GetPosition().Line()));
}
}
else
{
log.ReportResult(CompileResult("The collection must be a temp or local array!", script.GetScriptId(), theForEach.GetStatement1()->GetPosition().Line()));
}
// else it would be some statement...
if (isBuffer)
{
string loopIndexName = (variableGenHint < 26) ? fmt::format("i_{}", (char)(variableGenHint + 'A')) : fmt::format("i_{}", variableGenHint);
func.GetVariablesNC().push_back(make_unique<VariableDecl>(loopIndexName));
unique_ptr<ForLoop> forLoop = std::make_unique<ForLoop>();
// Condition
unique_ptr<BinaryOp> lessThan = make_unique<BinaryOp>(BinaryOperator::LessThan);
lessThan->SetStatement1(_MakeTokenStatement(loopIndexName));
lessThan->SetStatement2(_MakeStringStatement(bufferName, ValueType::ArraySize));
unique_ptr<ConditionalExpression> condition = make_unique<ConditionalExpression>();
condition->AddStatement(move(lessThan));
forLoop->SetCondition(move(condition));
// Initializer
unique_ptr<Assignment> theEquals = make_unique<Assignment>();
theEquals->Operator = AssignmentOperator::Assign;
theEquals->SetVariable(make_unique<LValue>(loopIndexName));
theEquals->SetStatement1(_MakeNumberStatement(0));
forLoop->SetCodeBlock(_WrapInCodeBlock(move(theEquals)));
// Looper
unique_ptr<UnaryOp> thePlusPlus = make_unique<UnaryOp>();
thePlusPlus->Operator = UnaryOperator::Increment;
thePlusPlus->SetStatement1(_MakeTokenStatement(loopIndexName));
forLoop->SetLooper(_WrapInCodeBlock(move(thePlusPlus)));
#ifdef ENABLE_LDMSTM
if (!isReference)
{
#endif
_ReplaceIterationVariable(log, script, theForEach, iterationVariableOrig, newIterationVariable);
#ifdef ENABLE_LDMSTM
}
else
{
// Replace the iteration variable with [bufferName loopIndexVariable]
EnumScriptElements<LValue>(theForEach,
[&log, &script, &iterationVariableOrig, &bufferName, &loopIndexName](LValue &lValue)
{
if (lValue.GetName() == iterationVariableOrig)
{
// This is us
if (lValue.HasIndexer())
{
log.ReportResult(CompileResult("An iteration variable can not be indexed.", script.GetScriptId(), lValue.GetPosition().Line()));
}
lValue.SetName(bufferName);
lValue.SetIndexer(_MakeTokenStatement(loopIndexName));
}
});
EnumScriptElements<ComplexPropertyValue>(theForEach,
[&log, &script, &iterationVariableOrig, &bufferName, &loopIndexName](ComplexPropertyValue &propValue)
{
if ((propValue.GetType() == ValueType::Token) && (propValue.GetStringValue() == iterationVariableOrig))
{
// This is us
if (propValue.GetIndexer())
{
log.ReportResult(CompileResult("An iteration variable can not be indexed.", script.GetScriptId(), propValue.GetPosition().Line()));
}
propValue.SetValue(bufferName, ValueType::Token);
propValue.SetIndexer(_MakeTokenStatement(loopIndexName));
}
});
EnumScriptElements<SendCall>(theForEach,
[&log, &script, &iterationVariableOrig, &bufferName, &loopIndexName](SendCall &theSend)
{
if (theSend.GetTargetName() == iterationVariableOrig)
{
// This is us - if we have a tempvar we can just set a name, but
// theSend.SetName()
// Otherwise, we need to mess with the sendcall to change the target to [bufferName loopIndexName]
unique_ptr<LValue> lValue = make_unique<LValue>(bufferName);
lValue->SetIndexer(_MakeTokenStatement(loopIndexName));
theSend.SetLValue(move(lValue));
theSend.SetName(""); // So we use the LValue
}
});
}
#endif
// Transfer code to forloop
swap(forLoop->GetStatements(), theForEach.GetStatements());
#ifdef ENABLE_LDMSTM
if (!isReference)
#endif
{
// Put in one of these at the beginning of the forloop body: (= newIterationVariable [buffer loopIndexName])
unique_ptr<Assignment> loopAssignment = make_unique<Assignment>();
loopAssignment->Operator = AssignmentOperator::Assign;
loopAssignment->SetVariable(make_unique<LValue>(newIterationVariable));
unique_ptr<ComplexPropertyValue> loopAssignmentValue = make_unique<ComplexPropertyValue>();
loopAssignmentValue->SetValue(bufferName, ValueType::Token);
loopAssignmentValue->SetIndexer(_MakeTokenStatement(loopIndexName));
loopAssignment->SetStatement1(move(loopAssignmentValue));
forLoop->GetStatements().insert(forLoop->GetStatements().begin(), move(loopAssignment));
}
// Our final thing is just one statement, but it might not be for more complex iterators
theForEach.FinalCode.push_back(move(forLoop));
}
else
{
// A while loop makes more sense for these things.
unique_ptr<WhileLoop> whileLoop = std::make_unique<WhileLoop>();
//KAWA: instead of what Phil did with his intended semantics, I want
// (foreach blah myList ...)
//to become
// (= curNode (FirstNode (myList elements?))
// (while curNode
// (= nextNode (NextNode curNode))
// (= blah (NodeValue curNode))
// (= curNode nextNode)
// ...
// )
string curPtrName = (variableGenHint < 26) ? fmt::format("curNode_{}", (char)(variableGenHint + 'A')) : fmt::format("curNode_{}", variableGenHint);
func.GetVariablesNC().push_back(make_unique<VariableDecl>(curPtrName));
string nextPtrName = (variableGenHint < 26) ? fmt::format("nextNode_{}", (char)(variableGenHint + 'A')) : fmt::format("nextNode_{}", variableGenHint);
func.GetVariablesNC().push_back(make_unique<VariableDecl>(nextPtrName));
// First off, (= curNode (FirstNode (myList elements?))
unique_ptr<ProcedureCall> firstNodeCall = make_unique<ProcedureCall>("FirstNode");
firstNodeCall->AddStatement(_MakeSimpleSend(bufferName, "elements"));
unique_ptr<Assignment> firstAssignment = make_unique<Assignment>();
firstAssignment->Operator = AssignmentOperator::Assign;
firstAssignment->SetVariable(make_unique<LValue>(curPtrName));
firstAssignment->SetStatement1(move(firstNodeCall));
theForEach.FinalCode.push_back(move(firstAssignment));
//The (while curNode) bit
unique_ptr<ConditionalExpression> condition = make_unique<ConditionalExpression>();
condition->AddStatement(_MakeTokenStatement(curPtrName));
whileLoop->SetCondition(move(condition));
// Now the meat of the loop
#ifdef ENABLE_LDMSTM
if (!isReference)
{
#endif
// This is the same as in a buffer-based foreach
_ReplaceIterationVariable(log, script, theForEach, iterationVariableOrig, newIterationVariable);
#ifdef ENABLE_LDMSTM
}
else
{
// Replace the iteration variable with *newIterationVariable
EnumScriptElements<LValue>(theForEach,
[&log, &script, &iterationVariableOrig, &curPtrName](LValue &lValue)
{
if (lValue.GetName() == iterationVariableOrig)
{
// This is us
if (lValue.HasIndexer())
{
log.ReportResult(CompileResult("An iteration variable can not be indexed.", script.GetScriptId(), lValue.GetPosition().Line()));
}
lValue.SetName(curPtrName);
lValue.IsDeref = true;
}
});
EnumScriptElements<ComplexPropertyValue>(theForEach,
[&log, &script, &iterationVariableOrig, &curPtrName](ComplexPropertyValue &propValue)
{
if ((propValue.GetType() == ValueType::Token) && (propValue.GetStringValue() == iterationVariableOrig))
{
// This is us
if (propValue.GetIndexer())
{
log.ReportResult(CompileResult("An iteration variable can not be indexed.", script.GetScriptId(), propValue.GetPosition().Line()));
}
propValue.SetValue(curPtrName, ValueType::Deref);
}
});
EnumScriptElements<SendCall>(theForEach,
[&log, &script, &iterationVariableOrig, &curPtrName](SendCall &theSend)
{
if (theSend.GetTargetName() == iterationVariableOrig)
{
// This is us - if we have a tempvar we can just set a name, but
// theSend.SetName()
// Otherwise, we need to mess with the sendcall to change the target to *newIterationVariable
// I don't even think this would compile without foreach! Can't have (*ptr poop:) -> we'd mistake it for multiplcation.
unique_ptr<LValue> lValue = make_unique<LValue>(curPtrName);
lValue->IsDeref = true;
theSend.SetLValue(move(lValue));
theSend.SetName(""); // So we use the LValue
}
});
}
#endif
// Transfer code to whileLoop
swap(whileLoop->GetStatements(), theForEach.GetStatements());
#ifdef ENABLE_LDMSTM
if (!isReference)
#endif
{
//KAWA: We don't want this. We want (= nextNode (NextNode curNode))
unique_ptr<ProcedureCall> nextNodeCall = make_unique<ProcedureCall>("NextNode");
nextNodeCall->AddStatement(_MakeStringStatement(curPtrName, ValueType::Token));
unique_ptr<Assignment> nextAssignment = make_unique<Assignment>();
nextAssignment->Operator = AssignmentOperator::Assign;
nextAssignment->SetVariable(make_unique<LValue>(nextPtrName));
nextAssignment->SetStatement1(move(nextNodeCall));
//and then (= blah (NodeValue curNode))
unique_ptr<ProcedureCall> nodeValueCall = make_unique<ProcedureCall>();
nodeValueCall->SetName("NodeValue");
nodeValueCall->AddStatement(_MakeStringStatement(curPtrName, ValueType::Token));
unique_ptr<Assignment> valueAssignment = make_unique<Assignment>();
valueAssignment->Operator = AssignmentOperator::Assign;
valueAssignment->SetVariable(make_unique<LValue>(newIterationVariable));
valueAssignment->SetStatement1(move(nodeValueCall));
//and then finally (= curNode nextNode)
unique_ptr<Assignment> passAssignment = make_unique<Assignment>();
passAssignment->Operator = AssignmentOperator::Assign;
passAssignment->SetVariable(make_unique<LValue>(curPtrName));
passAssignment->SetStatement1(_MakeStringStatement(nextPtrName, ValueType::Token));
//Add them in REVERSE ORDER you doof.
whileLoop->GetStatements().insert(whileLoop->GetStatements().begin(), move(passAssignment));
whileLoop->GetStatements().insert(whileLoop->GetStatements().begin(), move(valueAssignment));
whileLoop->GetStatements().insert(whileLoop->GetStatements().begin(), move(nextAssignment));
}
theForEach.FinalCode.push_back(move(whileLoop));
}
}
void _ProcessForEaches(ICompileLog &log, Script &script)
{
EnumScriptElements<FunctionBase>(script,
[&log, &script](FunctionBase &func)
{
int variableGenHint = 0;
EnumScriptElements<ForEachLoop>(func,
[&log, &script, &func, &variableGenHint](ForEachLoop &forEachLoop)
{
_ProcessForEach(log, script, func, forEachLoop, variableGenHint);
variableGenHint++;
});
});
}
#endif
#ifdef ENABLE_GETPOLY
void _ProcessGetPoly(ICompileLog &log, Script &script, FunctionBase &func, GetPolyStatement &theGetPoly)
{
if (theGetPoly.GetStatement1()->GetNodeType() == sci::NodeType::NodeTypeComplexValue)
{
auto cpv = static_cast<ComplexPropertyValue&>(*theGetPoly.GetStatement1());
if (cpv.GetType() == ValueType::String || cpv.GetType() == ValueType::ResourceString)
{
auto ourScriptNum = script.GetScriptNumber();
auto ourPolyName = "P_" + cpv.GetStringValue();
if (ourPolyName == "P_")
ourPolyName = "";
//TODO: Load polygon data for current script, find ourPolyName, and USE THAT BITCH
auto polyComponent = CreatePolygonComponent(appState->GetResourceMap().Helper().GetPolyFolder(), ourScriptNum);
const SCIPolygon *ourPolygon = nullptr;
for (const SCIPolygon &poly : polyComponent->Polygons())
{
//if (!poly.Name.empty())
{
auto thisPolyName = poly.Name;
if (thisPolyName.compare(ourPolyName) == 0)
{
ourPolygon = &poly;
break;
}
}
}
if (ourPolygon)
{
unique_ptr<SendCall> polySend = std::make_unique<SendCall>();
polySend->SetName("Polygon");
unique_ptr<SendParam> polyNew = std::make_unique<SendParam>();
polyNew->SetName("new");
polyNew->SetIsMethod(true);
polySend->AddSendParam(move(polyNew));
unique_ptr<SendParam> typeParam = std::make_unique<SendParam>();
typeParam->SetName("type");
typeParam->SetIsMethod(false);
//typeParam->AddStatement(_MakeNumberStatement(2));
typeParam->AddStatement(_MakeNumberStatement((int)ourPolygon->Type));
unique_ptr<SendParam> initParam = std::make_unique<SendParam>();
initParam->SetName("init");
initParam->SetIsMethod(false);
//Repeat as needed
//initParam->AddStatement(_MakeNumberStatement(64));
//initParam->AddStatement(_MakeNumberStatement(42));
for (point16 point : ourPolygon->Points())
{
initParam->AddStatement(_MakeNumberStatement(point.x));
initParam->AddStatement(_MakeNumberStatement(point.y));
}
//
unique_ptr<SendParam> yourParam = std::make_unique<SendParam>();
yourParam->SetName("yourself");
yourParam->SetIsMethod(false);
unique_ptr<SendCall> pSend = std::make_unique<SendCall>();
pSend->SetStatement1(move(polySend));
pSend->AddSendParam(move(typeParam));
pSend->AddSendParam(move(initParam));
pSend->AddSendParam(move(yourParam));
theGetPoly.FinalCode.push_back(move(pSend));
}
else
{
log.ReportResult(CompileResult(fmt::format("Unknown polygon name {} in &getpoly.", cpv.GetStringValue()), script.GetScriptId(), cpv.GetPosition().Line()));
}
}
else
{
log.ReportResult(CompileResult("&getpoly must have a polygon name as a string parameter, without the P_ in front, or an empty string for Default.", script.GetScriptId(), cpv.GetPosition().Line()));
}
}
else
{
log.ReportResult(CompileResult("&getpoly must have a polygon name as a string parameter, without the P_ in front, or an empty string for Default.", script.GetScriptId(), theGetPoly.GetLineNumber()));
}
}
void _ProcessGetPolys(ICompileLog &log, Script &script)
{
EnumScriptElements<FunctionBase>(script,
[&log, &script](FunctionBase &func)
{
EnumScriptElements<GetPolyStatement>(func,
[&log, &script, &func](GetPolyStatement &getPolyStatement)
{
_ProcessGetPoly(log, script, func, getPolyStatement);
});
});
}
#endif
//
// Fix up scripts so that they conform to standards. Differences in the SCI syntax make
// it difficult to get the script OM in its final state just in the parsing phase.
//
// - Propagate "public" from exports section to the individual procedures/instances
// - Identify switchtos and auto-number their cases
// - Transform cond into if-elseif-else
//
void PostProcessScript(ICompileLog *pLog, Script &script)
{
// Push public down to instances and procedures
EnumScriptElements<ProcedureDefinition>(script,
[&script](ProcedureDefinition &proc)
{
proc.SetPublic(script.IsExport(proc.GetName()));
}
);
EnumScriptElements<ClassDefinition>(script,
[&script](ClassDefinition &instance)
{
// This could be a class too (not just instance). The main game class is public.
instance.SetPublic(script.IsExport(instance.GetName()));
#ifdef ENABLE_VERBS
_ProcessClassForVerbHandlers(script, instance);
#endif
}
);
#ifdef ENABLE_FOREACH
// Re-work foreach's into for loops (only for compiles where there is a log, e.g. actual compiles)
if (pLog)
{
_ProcessForEaches(*pLog, script);
}
#endif
#ifdef ENABLE_GETPOLY
if (pLog)
{
_ProcessGetPolys(*pLog, script);
}
#endif
// Re-work conds into if-elses.
EnumScriptElements<CondStatement>(script,
[pLog, &script](CondStatement &cond)
{
// TODO: Enforce that else needs to be last.
// TODO: What if only one else?
assert(!cond.GetStatement1());
if (!cond._clausesTemp.empty())
{
std::unique_ptr<CodeBlock> elseCodeBlock;
auto it = cond._clausesTemp.rbegin();
if ((*it)->IsDefault())
{
elseCodeBlock = make_unique<CodeBlock>(move((*it)->GetStatements()));
++it;
}
std::unique_ptr<IfStatement> currentIf;
while (it != cond._clausesTemp.rend())
{
auto &clause = *it;
if (clause->IsDefault())
{
if (pLog)
{
pLog->ReportResult(CompileResult("The else clause must be the last clause in a cond.", script.GetScriptId(), clause->GetPosition().Line()));
}
break;
}
std::unique_ptr<IfStatement> newIf = make_unique<IfStatement>();
if (currentIf)
{
// Put this in our new if's else block.
newIf->SetStatement2(make_unique<CodeBlock>(move(currentIf)));
}
currentIf = move(newIf);
// Grab the statement1 of the CaseStatement and put it in the if condition.
currentIf->SetCondition(make_unique<ConditionalExpression>(move(clause->GetStatement1Internal())));
// Then transfer all the statements into a CodeBlock for the if.
currentIf->SetStatement1(make_unique<CodeBlock>(move(clause->GetStatements())));
if (elseCodeBlock)
{
// This goes into the final if.
currentIf->SetStatement2(move(elseCodeBlock));
}
++it;
}
// Case where there is just a single else, just copy statements into a codeblock.
if (elseCodeBlock)
{
assert(!currentIf);
cond.SetStatement1(move(elseCodeBlock));
}
else
{
assert(!elseCodeBlock);
cond.SetStatement1(move(currentIf));
}
}
cond._clausesTemp.clear();
}
);
// Identify switchto statements and auto-enumerate the cases. If no case statements have values and none are default,
// it's a switchto
EnumScriptElements<SwitchStatement>(script,
[](SwitchStatement &switchStatement)
{
if (all_of(switchStatement._cases.begin(), switchStatement._cases.end(),
[](std::unique_ptr<CaseStatement> &caseStatement) { return !caseStatement->IsDefault() && (caseStatement->GetCaseValue() == nullptr); }))
{
uint16_t value = 0;
for (auto &caseStatement : switchStatement._cases)
{
caseStatement->SetCaseValue(std::make_unique<PropertyValue>(value));
value++;
}
}
}
);
// Report warnings if any un-implemented constructs are used.
std::vector<std::string> unimplementedWarnings;
if (!script.Externs.empty())
{
unimplementedWarnings.push_back("extern statements(s)");
}
if (!script.Globals.empty())
{
unimplementedWarnings.push_back("global statements(s)");
}
if (!script.ClassDefs.empty())
{
unimplementedWarnings.push_back("classdef statements(s)");
}
if (!script.Selectors.empty())
{
unimplementedWarnings.push_back("selectors statements(s)");
}
if (!script.ProcedureForwards.empty())
{
unimplementedWarnings.push_back("procedure fwd declaration(s)");
}
bool hasMethodFwdDeclarations = false;
for (auto &theClass : script.GetClasses())
{
hasMethodFwdDeclarations = hasMethodFwdDeclarations || !theClass->MethodForwards.empty();
}
if (hasMethodFwdDeclarations)
{
unimplementedWarnings.push_back("methods fwd declaration(s)");
}
if (pLog)
{
for (auto &warning : unimplementedWarnings)
{
std::string text = warning + "ignored - not implemented";
pLog->ReportResult(CompileResult(text, script.GetScriptId(), 1, 0, CompileResult::CompileResultType::CRT_Warning));
}
}
}
// For error reporting:
template<typename _It>
void ExtractSomeToken(std::string &str, _It &stream)
{
char ch = *stream;
while (ch && !isspace(ch) && (ch != '(') && (ch != ')'))
{
str += ch;
ch = *(++stream);
}
}
//
// This does the parsing.
//
bool SCISyntaxParser::Parse(Script &script, streamIt &stream, std::unordered_set<std::string> preProcessorDefines, ICompileLog *pError, bool addCommentsToOM, bool collectComments)
{
g_compileSyntaxParseTimer.Start();
SyntaxContext context(stream, script, preProcessorDefines, addCommentsToOM, collectComments);
bool fRet = false;
#ifdef PARSE_DEBUG
context.ParseDebug = true;
#endif
if (entire_script.Match(&context, stream).Result() && (*stream == 0)) // Needs a full match
{
PostProcessScript(pError, script);
fRet = true;
}
else
{
// With regards to syntax errors - there can really only be one, because we can't
// recover afterwards.
std::string strError = "Error: (" + script.GetScriptId().GetFileNameOrig() + ") ";
strError += context.GetErrorText();
streamIt errorPos = context.GetErrorPosition();
strError += fmt::format(" ({}, {})", errorPos.GetLineNumber(), errorPos.GetColumnNumber());
// We can maybe improve the error by extracting a token here and seeing if it's a keyword.
std::string maybeKeyword;
streamIt errorPosCopy = errorPos;
ExtractSomeToken(maybeKeyword, errorPosCopy);
if (!maybeKeyword.empty())
{
if (std::find(SCIStatementKeywords.begin(), SCIStatementKeywords.end(), maybeKeyword) != SCIStatementKeywords.end())
{
strError += fmt::format(" (Statements must being with a parenthesis: \"({0}\").", maybeKeyword);
}
else if (IsOperator(maybeKeyword, sciNameToBinaryOp) || IsOperator(maybeKeyword, sciNameToAssignmentOp) || IsOperator(maybeKeyword, sciNameToUnaryOp))
{
strError += fmt::format(" (Operator expressions must begin with a parenthesis: \"({0}\").", maybeKeyword);
}
else if (maybeKeyword == "else")
{
strError += ": \"else\" cannot appear here.";
}
// Maybe more?
else
{
strError += fmt::format(": \"{0}\"", maybeKeyword);
}
}
ScriptId scriptId(script.GetPath().c_str());
if (pError)
{
// Add one to line#, since editor lines are 1-based
pError->ReportResult(CompileResult(strError, scriptId, errorPos.GetLineNumber() + 1, errorPos.GetColumnNumber(), CompileResult::CRT_Error));
}
}
g_compileSyntaxParseTimer.Stop();
return fRet;
}
bool SCISyntaxParser::Parse(Script &script, streamIt &stream, std::unordered_set<std::string> preProcessorDefines, SyntaxContext &context)
{
g_compileSyntaxParseTimer.Start();
bool fRet = false;
if (entire_script.Match(&context, stream).Result() && (*stream == 0)) // Needs a full match
{
PostProcessScript(nullptr, script);
fRet = true;
}
g_compileSyntaxParseTimer.Stop();
return fRet;
}
bool SCISyntaxParser::ParseHeader(Script &script, streamIt &stream, std::unordered_set<std::string> preProcessorDefines, ICompileLog *pError, bool collectComments)
{
g_compileSyntaxParseTimer.Start();
SyntaxContext context(stream, script, preProcessorDefines, false, collectComments);
bool fRet = entire_header.Match(&context, stream).Result() && (*stream == 0);
if (!fRet)
{
std::string strError = context.GetErrorText();
streamIt errorPos = context.GetErrorPosition();
ScriptId scriptId(script.GetPath().c_str());
if (pError)
{
pError->ReportResult(CompileResult(strError, scriptId, errorPos.GetLineNumber() + 1, errorPos.GetColumnNumber(), CompileResult::CRT_Error));
}
}
else
{
PostProcessScript(pError, script);
}
g_compileSyntaxParseTimer.Stop();
return fRet;
}
|
#include <whiskey/AST/FieldTag.hpp>
#include <ostream>
namespace whiskey {
namespace {
FieldTagInfo fieldTagInfos[] {
FieldTagInfo("Children", 0), // List_Children
FieldTagInfo("TemplateEvalArgs", 0), // TypeSymbol_TemplateEvalArgs
FieldTagInfo("Arg", 0), // TypeAccessUnary_Arg
FieldTagInfo("Args", 0), // TypeAccess_Args
FieldTagInfo("Arg", 0), // TypeGroup_Arg
FieldTagInfo("Return", 0), // TypeFunction_Return
FieldTagInfo("Args", 1), // TypeFunction_Args
FieldTagInfo("Value", 0), // ExprLiteralBool_Value
FieldTagInfo("Value", 0), // ExprLiteralInt8_Value
FieldTagInfo("Value", 0), // ExprLiteralInt16_Value
FieldTagInfo("Value", 0), // ExprLiteralInt32_Value
FieldTagInfo("Value", 0), // ExprLiteralInt64_Value
FieldTagInfo("Value", 0), // ExprLiteralUInt8_Value
FieldTagInfo("Value", 0), // ExprLiteralUInt16_Value
FieldTagInfo("Value", 0), // ExprLiteralUInt32_Value
FieldTagInfo("Value", 0), // ExprLiteralUInt64_Value
FieldTagInfo("Value", 0), // ExprLiteralChar8_Value
FieldTagInfo("Value", 0), // ExprLiteralChar16_Value
FieldTagInfo("Value", 0), // ExprLiteralChar32_Value
FieldTagInfo("Value", 0), // ExprLiteralFloat32_Value
FieldTagInfo("Value", 0), // ExprLiteralFloat64_Value
FieldTagInfo("Value", 0), // ExprLiteralReal_Value
FieldTagInfo("TemplateEvalArgs", 0), // ExprSymbol_TemplateEvalArgs
FieldTagInfo("Arg", 0), // ExprAccessUnary_Arg
FieldTagInfo("Args", 0), // ExprAccess_Args
FieldTagInfo("Arg", 0), // ExprGroup_Arg
FieldTagInfo("Callee", 0), // ExprCall_Callee
FieldTagInfo("Args", 1), // ExprCall_Args
FieldTagInfo("Args", 0), // ExprAdd_Args
FieldTagInfo("Arg", 0), // ExprIncPre_Arg
FieldTagInfo("Arg", 0), // ExprIncPost_Arg
FieldTagInfo("LHS", 0), // ExprSub_LHS
FieldTagInfo("RHS", 1), // ExprSub_RHS
FieldTagInfo("Arg", 0), // ExprNeg_Arg
FieldTagInfo("Arg", 0), // ExprDecPre_Arg
FieldTagInfo("Arg", 0), // ExprDecPost_Arg
FieldTagInfo("Args", 0), // ExprMul_Args
FieldTagInfo("LHS", 0), // ExprExp_LHS
FieldTagInfo("RHS", 1), // ExprExp_RHS
FieldTagInfo("LHS", 0), // ExprDiv_LHS
FieldTagInfo("RHS", 1), // ExprDiv_RHS
FieldTagInfo("LHS", 0), // ExprDivInt_LHS
FieldTagInfo("RHS", 1), // ExprDivInt_RHS
FieldTagInfo("LHS", 0), // ExprDivReal_LHS
FieldTagInfo("RHS", 1), // ExprDivReal_RHS
FieldTagInfo("LHS", 0), // ExprMod_LHS
FieldTagInfo("RHS", 1), // ExprMod_RHS
FieldTagInfo("Arg", 0), // ExprBitNot_Arg
FieldTagInfo("Args", 0), // ExprBitAnd_Args
FieldTagInfo("Args", 0), // ExprBitOr_Args
FieldTagInfo("Args", 0), // ExprBitXor_Args
FieldTagInfo("LHS", 0), // ExprBitShL_LHS
FieldTagInfo("RHS", 1), // ExprBitShL_RHS
FieldTagInfo("LHS", 0), // ExprBitShR_LHS
FieldTagInfo("RHS", 1), // ExprBitShR_RHS
FieldTagInfo("LHS", 0), // ExprLT_LHS
FieldTagInfo("RHS", 1), // ExprLT_RHS
FieldTagInfo("LHS", 0), // ExprLE_LHS
FieldTagInfo("RHS", 1), // ExprLE_RHS
FieldTagInfo("LHS", 0), // ExprGT_LHS
FieldTagInfo("RHS", 1), // ExprGT_RHS
FieldTagInfo("LHS", 0), // ExprGE_LHS
FieldTagInfo("RHS", 1), // ExprGE_RHS
FieldTagInfo("LHS", 0), // ExprNE_LHS
FieldTagInfo("RHS", 1), // ExprNE_RHS
FieldTagInfo("LHS", 0), // ExprEQ_LHS
FieldTagInfo("RHS", 1), // ExprEQ_RHS
FieldTagInfo("Arg", 0), // ExprBoolNot_Arg
FieldTagInfo("Args", 0), // ExprBoolAnd_Args
FieldTagInfo("Args", 0), // ExprBoolOr_Args
FieldTagInfo("Args", 0), // ExprBoolImplies_Args
FieldTagInfo("LHS", 0), // ExprAddAssign_LHS
FieldTagInfo("RHS", 1), // ExprAddAssign_RHS
FieldTagInfo("LHS", 0), // ExprSubAssign_LHS
FieldTagInfo("RHS", 1), // ExprSubAssign_RHS
FieldTagInfo("LHS", 0), // ExprMulAssign_LHS
FieldTagInfo("RHS", 1), // ExprMulAssign_RHS
FieldTagInfo("LHS", 0), // ExprExpAssign_LHS
FieldTagInfo("RHS", 1), // ExprExpAssign_RHS
FieldTagInfo("LHS", 0), // ExprDivAssign_LHS
FieldTagInfo("RHS", 1), // ExprDivAssign_RHS
FieldTagInfo("LHS", 0), // ExprDivIntAssign_LHS
FieldTagInfo("RHS", 1), // ExprDivIntAssign_RHS
FieldTagInfo("LHS", 0), // ExprDivRealAssign_LHS
FieldTagInfo("RHS", 1), // ExprDivRealAssign_RHS
FieldTagInfo("LHS", 0), // ExprModAssign_LHS
FieldTagInfo("RHS", 1), // ExprModAssign_RHS
FieldTagInfo("LHS", 0), // ExprBitAndAssign_LHS
FieldTagInfo("RHS", 1), // ExprBitAndAssign_RHS
FieldTagInfo("LHS", 0), // ExprBitOrAssign_LHS
FieldTagInfo("RHS", 1), // ExprBitOrAssign_RHS
FieldTagInfo("LHS", 0), // ExprBitXorAssign_LHS
FieldTagInfo("RHS", 1), // ExprBitXorAssign_RHS
FieldTagInfo("LHS", 0), // ExprBitShLAssign_LHS
FieldTagInfo("RHS", 1), // ExprBitShLAssign_RHS
FieldTagInfo("LHS", 0), // ExprBitShRAssign_LHS
FieldTagInfo("RHS", 1), // ExprBitShRAssign_RHS
FieldTagInfo("LHS", 0), // ExprAssign_LHS
FieldTagInfo("RHS", 1), // ExprAssign_RHS
FieldTagInfo("Expr", 0), // StmtExpr_Expr
FieldTagInfo("Decl", 0), // StmtDecl_Decl
FieldTagInfo("Arg", 0), // StmtReturn_Arg
FieldTagInfo("Name", 0), // StmtContinue_Name
FieldTagInfo("Name", 0), // StmtBreak_Name
FieldTagInfo("Condition", 0), // StmtIf_Condition
FieldTagInfo("Then", 1), // StmtIf_Then
FieldTagInfo("Else", 2), // StmtIf_Else
FieldTagInfo("Condition", 0), // StmtWhile_Condition
FieldTagInfo("Body", 1), // StmtWhile_Body
FieldTagInfo("Name", 2), // StmtWhile_Name
FieldTagInfo("Decls", 0), // StmtFor_Decls
FieldTagInfo("Condition", 1), // StmtFor_Condition
FieldTagInfo("Steps", 2), // StmtFor_Steps
FieldTagInfo("Body", 3), // StmtFor_Body
FieldTagInfo("Name", 4), // StmtFor_Name
FieldTagInfo("Decl", 0), // StmtForEach_Decl
FieldTagInfo("Sequence", 1), // StmtForEach_Sequence
FieldTagInfo("Body", 2), // StmtForEach_Body
FieldTagInfo("Name", 3), // StmtForEach_Name
FieldTagInfo("Stmts", 0), // StmtBlock_Stmts
FieldTagInfo("Scope", 1), // StmtBlock_Scope
FieldTagInfo("Type", 0), // DeclVariable_Type
FieldTagInfo("TemplateDeclArgs", 1), // DeclVariable_TemplateDeclArgs
FieldTagInfo("Initial", 2), // DeclVariable_Initial
FieldTagInfo("Return", 0), // DeclFunction_Return
FieldTagInfo("TemplateDeclArgs", 1), // DeclFunction_TemplateDeclArgs
FieldTagInfo("Args", 2), // DeclFunction_Args
FieldTagInfo("Body", 3), // DeclFunction_Body
FieldTagInfo("Scope", 4), // DeclFunction_Scope
FieldTagInfo("TemplateDeclArgs", 0), // DeclClass_TemplateDeclArgs
FieldTagInfo("Inherits", 1), // DeclClass_Inherits
FieldTagInfo("Members", 2), // DeclClass_Members
FieldTagInfo("Scope", 3), // DeclClass_Scope
FieldTagInfo("Members", 0), // DeclNamespace_Members
FieldTagInfo("Scope", 1), // DeclNamespace_Scope
FieldTagInfo("Path", 0), // Import_Path
FieldTagInfo("Members", 0), // Unit_Members
FieldTagInfo("Scope", 1) // Unit_Scope
};
}
std::ostream &operator<<(std::ostream &os, FieldTag value) {
os << FieldTagInfo::get(value).getName();
return os;
}
std::ostream &operator<<(std::ostream &os, FieldFormat value) {
switch (value) {
case FieldFormat::Int:
os << "Int";
break;
case FieldFormat::UInt:
os << "UInt";
break;
case FieldFormat::Real:
os << "Real";
break;
case FieldFormat::String:
os << "String";
break;
case FieldFormat::Node:
os << "Node";
break;
case FieldFormat::NodeVector:
os << "NodeVector";
break;
case FieldFormat::Scope:
os << "Scope";
break;
}
return os;
}
const FieldTagInfo &FieldTagInfo::get(FieldTag fieldTag) {
return fieldTagInfos[static_cast<int>(fieldTag)];
}
FieldTagInfo::FieldTagInfo(std::string name, std::vector<std::unique_ptr<Field>>::size_type index) : name(name), index(index) {}
const std::string &FieldTagInfo::getName() const {
return name;
}
std::vector<std::unique_ptr<Field>>::size_type FieldTagInfo::getIndex() const {
return index;
}
}
|
#pragma once
#include "stdafx.h"
//#include "Playingfield.h"
#include "Inventory.h"
class Playingfield;
class InputController
{
public:
static InputController& Instance() {
static InputController mInstance;
return mInstance;
}
InputController();
~InputController();
void CheckInput();
void setPlayingField(Playingfield* setPf);
private:
void quitGame();
void monsterDetection();
void itemDetection();
void attackMonster();
Playingfield* pf;
Inventory inventory;
};
|
#include <sstream>
#include "barra_indicadora.h"
#include "../recursos.h"
using namespace App_Graficos;
Barra_indicadora::Barra_indicadora(int x, int y, int vmax, int vact, const std::string& pnombre)
:caja(DLibH::Herramientas_SDL::nuevo_sdl_rect(x, y, W, H), R, G, B),
txt_nombre(DLibV::Gestor_superficies::obtener(App::Recursos_graficos::rs_fuente_base), pnombre),
txt_cantidad(DLibV::Gestor_superficies::obtener(App::Recursos_graficos::rs_fuente_base), "100"),
nombre(pnombre),
w_max(W), valor_max(vmax), valor_actual(vact),
tiempo_vigencia(-1.f)
{
caja.establecer_alpha(192);
txt_nombre.establecer_posicion(caja.acc_posicion());
txt_cantidad.establecer_posicion(caja.acc_posicion());
txt_cantidad.desplazar(-30, 0);
txt_nombre.hacer_estatica();
txt_cantidad.hacer_estatica();
}
void Barra_indicadora::establecer_posicion(int x, int y)
{
caja.ir_a(x, y);
txt_nombre.ir_a(x, y);
}
void Barra_indicadora::establecer_dimensiones(unsigned int w, unsigned int h)
{
caja.establecer_posicion(0, 0, w, h, DLibV::Representacion::FRECT_W | DLibV::Representacion::FRECT_H);
w_max=w;
}
void Barra_indicadora::establecer_color(unsigned int r, unsigned int g, unsigned int b)
{
caja.mut_rgb(r, g, b);
}
void Barra_indicadora::establecer_nombre(const std::string v)
{
nombre=v;
txt_nombre.asignar(nombre);
}
void Barra_indicadora::establecer_valor_max(int v)
{
valor_max=v;
}
void Barra_indicadora::establecer_valor_actual(int v)
{
valor_actual=v;
std::stringstream ss;
ss<<valor_actual;
txt_cantidad.asignar(ss.str());
}
void Barra_indicadora::volcar(DLibV::Pantalla& pantalla)
{
int wcalc=(valor_actual * w_max) / valor_max;
caja.establecer_posicion(0, 0, wcalc, 0, DLibV::Representacion::FRECT_W);
caja.volcar(pantalla);
txt_nombre.volcar(pantalla);
txt_cantidad.volcar(pantalla);
}
void Barra_indicadora::turno(float v)
{
if(tiempo_vigencia > 0.0f)
{
tiempo_vigencia-=v;
if(tiempo_vigencia < 0.0f) tiempo_vigencia=0.0f;
}
}
|
#ifndef D3DUTIL_H
#define D3DUTIL_H
#if defined(DEBUG) || defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>//1.使用_PRTn的宏显示调试信息 2.侦测内存泄漏用_CrtSetDbgFlag函数(本例是用这个)
#endif
#include <d3dx11.h>
#include "d3dx11Effect.h"
#include <xnamath.h>
#include <dxerr.h>
#include <cassert>
#include <ctime>
#include <algorithm>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include "MathHelper.h"
#include "LightHelper.h"
//定义错误检测//
#if defined(DEBUG) | defined(_DEBUG)
#ifndef HR
#define HR(x) {
HRESULT hr = (x);//x函数返回值返回类型为HRESULT,小于0失败//
if(FAILED(hr)){
DXTrace(__FILE__, (DWORD)__LINE__, hr, L#x, true);//当前文件通常为__FILE__,当前行__LINE__,一个将被跟踪到调试流的HRESULT,一个将被跟踪到调试流的宽字符串(可能是空)通过L#转化为宽字符串,bool是否弹出消息框//
}
};
#endif
#else
#ifndef HR
#define HR(x)(x)
#endif
#endif
//DEBUG
//定义一个释放清空COM组件的指针对象的宏//清空
#define ReleaseCOM(x){if(x){x->Release();x=0;}}
//定义删除指针对象的宏//删除
#define SafeDelete(x){delete x;x=0;}
//定义工具类//
class d3dHelper
{
public:
//SRV只读,RTV可写//
static ID3D11ShaderResourceView* CreateTexture2DArraySRV(
ID3D11Device*device,ID3D11DeviceContext*context,
std::vector<std::wstring>&filenames,
DXGI_FORMAT format=DXGI_FORMAT_FROM_FILE,
UINT filter=D3DX11_FILTER_NONE,
UINT mipFilter=D3DX11_FILTER_LINEAR
);
static ID3D11ShaderResourceView* CreateRandomTexture1DSRV(ID3D11Device* device);
};
class TextHelper
{
public:
//T转化为宽字符
template<typename T>
static D3DX11INLINE std::wstring ToString(const T&s)
{
std::wostringstream oss;
oss<<s;
return oss.str();
}
//宽字符转化为T
template<typename T>
static D3DX11INLINE T FromString(const std::wstring&s)
{
T x;
std::wistringstream iss(s);
iss>>x;
return x;
}
};
//提取平截头体的四个面//
void ExtractFrustumPlanes(XMFLOAT4 planes[6], CXMMATRIX M);
namespace Colors
{
XMGLOBALCONST XMVECTORF32 White = {1.0f, 1.0f, 1.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Black = {0.0f, 0.0f, 0.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Red = {1.0f, 0.0f, 0.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Green = {0.0f, 1.0f, 0.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Blue = {0.0f, 0.0f, 1.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Yellow = {1.0f, 1.0f, 0.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Cyan = {0.0f, 1.0f, 1.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Magenta = {1.0f, 0.0f, 1.0f, 1.0f};
XMGLOBALCONST XMVECTORF32 Silver = {0.75f, 0.75f, 0.75f, 1.0f};
XMGLOBALCONST XMVECTORF32 LightSteelBlue = {0.69f, 0.77f, 0.87f, 1.0f};
}
//
//types和formats进行转换的工具类//
//
class Convert
{
public:
//XMVECTOR to XMCOLOR//
static D3DX11INLINE XMCOLOR ToXmColor(FXMVECTOR v)
{
XMCOLOR dest;
XMStoreColor(&dest,v);
return dest;
}
// XMVECTOR to XMFLOAT4//
static D3DX11INLINE XMFLOAT4 ToXmFloat4(FXMVECTOR v)
{
XMFLOAT4 dest;
XMStoreFloat4(&dest,v);
return dest;
}
//argb to abgr //
static D3DX11INLINE UINT ArgbToAbgr(UINT argb)
{
BYTE A=(argb>>24)&0xff;
BYTE R=(argb>>16)&0xff;
BYTE G=(argb>>8)&0xff;
BYTE B=(argb>>0)&0xff;
return(A<<24)|(B<<16)|(G<<8)|(R<<0);
}
};
#endif//D3DUTIL_H
|
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package
#ifndef JACTORIO_INCLUDE_DATA_CEREAL_SUPPORT_DECIMAL_H
#define JACTORIO_INCLUDE_DATA_CEREAL_SUPPORT_DECIMAL_H
#pragma once
#include "core/data_type.h"
#include "data/cereal/serialize.h"
namespace cereal
{
CEREAL_LOAD_EXTERN(archive, jactorio::Decimal3T, m) {
dec::int64 before_val;
dec::int64 after_val;
archive(before_val, after_val);
m.pack(before_val, after_val);
}
CEREAL_SAVE_EXTERN(archive, jactorio::Decimal3T, m) {
dec::int64 before_val;
dec::int64 after_val;
m.unpack(before_val, after_val);
archive(before_val, after_val);
}
} // namespace cereal
#endif // JACTORIO_INCLUDE_DATA_CEREAL_SUPPORT_DECIMAL_H
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_INT = std::numeric_limits<int>::max();
const int MIN_INT = std::numeric_limits<int>::min();
const int INF = 1000000000;
const int NEG_INF = -1000000000;
#define max(a,b)(a>b?a:b)
#define min(a,b)(a<b?a:b)
#define MEM(arr,val)memset(arr,val, sizeof arr)
#define PI acos(0)*2.0
#define eps 1.0e-9
#define are_equal(a,b)fabs(a-b)<eps
#define LS(b)(b& (-b)) // Least significant bit
#define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians
typedef long long ll;
typedef pair<int,int> ii;
typedef pair<int,char> ic;
typedef pair<long,char> lc;
typedef vector<int> vi;
typedef vector<ii> vii;
int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);}
int lcm(int a,int b){return a*(b/gcd(a,b));}
int d [100 + 5] [100 + 5];
void reset (int c){
for ( int i = 0; i <= c; i++ )
for ( int j = 0; j <= c; j++ )
d[i][j] = INF;
}
int main ()
{
int c, s, q;
int cases = 0;
bool blank = false;
while (scanf("%d %d %d", &c, &s, &q)) {
if ( c == 0 && s == 0 && q == 0 ) break;
reset (c);
int c1, c2, deci;
for ( int i = 0; i < s; i++ ) {
scanf ("%d %d %d", &c1, &c2, &deci);
d[c1][c2] = d[c2][c1] = deci;
}
for ( int k = 1; k <= c; k++ )
for ( int i = 1; i <= c; i++ )
for ( int j = 1; j <= c; j++ )
d[i][j] = d[j][i] = min(d[i][j], max(d[i][k], d[k][j]));
if ( blank ) printf ("\n");
blank = true;
printf ("Case #%d\n", ++cases);
for ( int i = 0; i < q; i++ ) {
scanf ("%d %d", &c1, &c2);
if (c1 <= 0 || c1 > c || c2 <= 0 || c2 > c) printf ("%d\n" , 0);
else if ( d[c1][c2] == INF ) printf ("no path\n");
else printf ("%d\n", d[c1][c2]);
}
}
return 0;
}
//
//int C, S, Q, x, y, z, a, b, mst_cost;
//map<int, vii> adj;
//map<int, vii> parent;
//vi taken;
//priority_queue<pair<int, ii> > pq;
//
//class UnionFind{
//private: vi p, rank;
//public:
// UnionFind(int N){
// rank.assign(N, 0);
// p.assign(N, 0);
// for(int i = 0; i < N; i++)
// p[i] = i;
// }
// int findSet(int i){
// return (p[i] == i) ? i : (p[i] = findSet(p[i]));
// }
// bool isSameSet(int i, int j){
// return findSet(i) == findSet(j);
// }
// void unionSet(int i, int j){
// if (!isSameSet(i, j)){
// int x = findSet(i), y = findSet(j);
// if (rank[x] > rank[y]) p[y] = x;
// else {
// p[x] = y;
// if (rank[x] == rank[y]) rank[y]++;
// }
// }
// }
//};
//
//void process(int vtx){
// taken[vtx] = 1;
// for (int j = 0; j < (int)adj[vtx].size(); j++){
// ii v = adj[vtx][j];
// if (!taken[v.first]) pq.push(make_pair(-v.second, ii(vtx, v.first)));
// }
//}
//
//int main(){
// int caseNum = 1;
// while (cin >> C >> S >> Q){
// if (C == 0)
// break;
// for (int i = 1; i <= C; i++){
// vii l;
// adj[i] = l;
// }
// int total = 0;
// for (int i = 0; i < S; i++){
// cin >> x >> y >> z;
// total += z;
// adj[x].push_back(ii(y, z));
// adj[y].push_back(ii(x, z));
// }
//// for (int i = 0; i < m; i++){
//// cout << i << ": ";
//// for (int j = 0; j < adj[i].size();j++){
//// cout << adj[i][j].first << "," << adj[i][j].second << " ";
//// }
//// cout << endl;
//// }
// taken.assign(C + 1, 0);
// for (int i = 1; i <= C; i++){
// vii p;
// parent[i] = p;
// }
// for (int i = 1; i <= C; i++){
// if (!taken[i]){
// process(i);
// vii l;
// l.assign(C + 1, ii(-1, 0));
// parent[i] = l;
// }
// while(!pq.empty()){
// pair<int, ii> front = pq.top(); pq.pop();
// int w = -front.first;
// int u = front.second.first;
// int v = front.second.second;
// if (!taken[v]){
// parent[i][v] = ii(u, w);
// process(v);
// }
// }
// }
// if (caseNum > 1)
// cout << endl;
// cout << "Case #" << caseNum++ << endl;
// for (int i = 0; i < Q; i++){
// bool found = false;
// int maxi = 0;
// cin >> a >> b;
// for (int j = 1; j <= C; j++){
// UnionFind UF(C + 1);
// if (parent[j].size() == 0)
// continue;
// for (int k = a; k != -1; k = parent[j][k].first){
// maxi = max(maxi, parent[j][k].second);
// if (parent[j][k].first != -1)
// UF.unionSet(k, parent[j][k].first);
//// cout << k << " and " << parent[j][k].first << " " << UF.isSameSet(a, b) << endl;
//// cout << UF.findSet(a) << " " << UF.findSet(b) << endl;
// if (UF.isSameSet(a, b)){
// found = true;
// break;
// }
// }
// if (!found){
//// UnionFind UF(C + 1);
// for (int k = b; k != -1; k = parent[j][k].first){
// maxi = max(maxi, parent[j][k].second);
// UF.unionSet(k, parent[j][k].first);
//// cout << k << " and " << parent[j][k].first << " " << UF.isSameSet(a, b) << endl;
//// cout << UF.findSet(a) << " " << UF.findSet(b) << endl;
// if (UF.isSameSet(a, b)){
// found = true;
// break;
// }
// }
// }
// }
// if (!found)
// cout << "no path" << endl;
// else cout << maxi << endl;
// }
// }
// return 0;
//}
|
/*
* example showing how to use events
* This simplyfied example may seem pointless
* Events realy shines when building a gui were each widget cant be modified all the time to suit each usecase
*/
#include <DList.h> // events depends on this module
#include <mgui.h> // pulls in the event module
// define recever classes (that is able to take events)
class MyValue:
public EventReciever // all objects that wants to recieve events must derive from EventReciever
{
int _value;
public:
MyValue() { _value = 0; }
void up() { _value++; }
void down() { _value--; }
void print() { Serial.println(String("MyValue = ") + _value); }
};
class LastInput : public EventReciever {
String _str;
public:
LastInput(){ }
void onInput(const EventInfo *evt) {
_str = evt->str;
}
void print() { Serial.println(String("your last text was:") + _str); }
};
// this class is the event sender that send out events to any object that is connected to it
class InputReader {
public:
// define 3 events that EventReciever object can connect to
EventSender upEvent;
EventSender downEvent;
EventSender textEvent;
EventSender printEvent;
void printUsage(){
Serial.println("Please input +, - or any text (max 64 chars):");
}
void readSerialIn() {
// read from serial input
String str;
while(Serial.available() > 0) {
str += Serial.readString(); // read char by char until end of input stream
}
if (str.length() > 0){
if (str == "+") {
upEvent.send(); // we want to increment
} else if (str == "-") {
downEvent.send(); // we want to decrement
} else {
EventInfo evt; // create a eventinfo that can carry the the str to the reciever/recievers
// (you can have as many recievers as you want connected to any event, the RAM is the limit)
evt.str = str; // here we send a string, but we could also send a int, ptr float etc see EventInfo union for more info
textEvent.send(&evt); // send out this string to all recievers
}
// make them print out what they have
printEvent.send(); // note that this object doesnt now if it has any events connected here
// it doesnt have to have any events
}
}
};
// declare some object on the stack
InputReader sendObj;
LastInput textObj;
MyValue valueObj;
// create the listeners, they relay the event from the sender to the listener
EventListener upListener = EVENTLISTENER(valueObj, up);
EventListener downListener = EVENTLISTENER(valueObj, down);
EventListener printValueListener = EVENTLISTENER(valueObj, print);
// and the relays for textObj
EventListener textListener = EVENTLISTENER_WITH_INFO(textObj, onInput);
EventListener printTextListener = EVENTLISTENER(textObj, print);
void setup(){
Serial.begin(115200);
Serial.setTimeout(20); // only wait fro 20ms before we move on when reading string
// print
sendObj.printUsage();
// attach the event listeners to the send object
sendObj.upEvent.addListener(upListener);
sendObj.downEvent.addListener(downListener);
sendObj.textEvent.addListener(textListener);
// note that we can add 2 or ore listeners to the same event, they will be called in insertion order
sendObj.printEvent.addListener(printValueListener);
sendObj.printEvent.addListener(printTextListener);
}
void loop(){
sendObj.readSerialIn();
delay(10);
}
|
#include <bits/stdc++.h>
using namespace std;
int solve(vector<vector<int>> mat, int k)
{
priority_queue<int, vector<int>, greater<int>> q;
for (int i = 0; i < mat.size(); i++)
{
for (int j = 0; j < mat[0].size(); j++)
q.push(mat[i][j]);
}
k -= 1;
while (k--)
q.pop();
return q.top();
}
int anotherSolution(vector<vector<int>> matrix, int k)
{
vector<int> t;
int len = 0;
for (int i = 0; i < matrix.size(); i++)
{
t.insert(t.end(), matrix[i].begin(), matrix[i].end());
}
sort(t.begin(), t.end());
return t[k - 1];
}
int main()
{
vector<vector<int>> matrix = {
{1, 5, 9},
{10, 11, 13},
{12, 13, 15}};
cout << solve(matrix, 7) << endl;
return 0;
}
|
/*
* UAE - The Un*x Amiga Emulator
*
* transparent archive handling
*
* 2007 Toni Wilen
*/
#include "sysconfig.h"
#include "sysdeps.h"
#ifdef _WIN32
#include <windows.h>
#include "win32.h"
#endif
#include "options.h"
#include "zfile.h"
#include "archivers/zip/unzip.h"
#include "archivers/dms/pfile.h"
#include "crc32.h"
#include "zarchive.h"
#include "disk.h"
#include <zlib.h>
#define unpack_log write_log
#undef unpack_log
#define unpack_log(fmt, ...)
static time_t fromdostime (uae_u32 dd)
{
struct tm tm;
time_t t;
memset (&tm, 0, sizeof tm);
tm.tm_hour = (dd >> 11) & 0x1f;
tm.tm_min = (dd >> 5) & 0x3f;
tm.tm_sec = ((dd >> 0) & 0x1f) * 2;
tm.tm_year = ((dd >> 25) & 0x7f) + 80;
tm.tm_mon = ((dd >> 21) & 0x0f) - 1;
tm.tm_mday = (dd >> 16) & 0x1f;
t = mktime (&tm);
t -= _timezone;
return t;
}
static struct zvolume *getzvolume (struct znode *parent, struct zfile *zf, unsigned int id)
{
struct zvolume *zv = NULL;
switch (id)
{
#ifdef A_ZIP
case ArchiveFormatZIP:
zv = archive_directory_zip (zf);
break;
#endif
#ifdef A_7Z
case ArchiveFormat7Zip:
zv = archive_directory_7z (zf);
break;
#endif
#ifdef A_RAR
case ArchiveFormatRAR:
zv = archive_directory_rar (zf);
break;
#endif
#ifdef A_LHA
case ArchiveFormatLHA:
zv = archive_directory_lha (zf);
break;
#endif
#ifdef A_LZX
case ArchiveFormatLZX:
zv = archive_directory_lzx (zf);
break;
#endif
case ArchiveFormatPLAIN:
zv = archive_directory_plain (zf);
break;
case ArchiveFormatADF:
zv = archive_directory_adf (parent, zf);
break;
case ArchiveFormatRDB:
zv = archive_directory_rdb (zf);
break;
case ArchiveFormatTAR:
zv = archive_directory_tar (zf);
break;
case ArchiveFormatFAT:
zv = archive_directory_fat (zf);
break;
}
#ifdef ARCHIVEACCESS
if (!zv)
zv = archive_directory_arcacc (zf, id);
#endif
return zv;
}
struct zfile *archive_access_select (struct znode *parent, struct zfile *zf, unsigned int id, int dodefault, int *retcode, int index)
{
struct zvolume *zv;
struct znode *zn;
int zipcnt, first, select;
TCHAR tmphist[MAX_DPATH];
struct zfile *z = NULL;
int we_have_file;
int diskimg;
int mask = zf->zfdmask;
int canhistory = (mask & ZFD_DISKHISTORY) && !(mask & ZFD_CHECKONLY);
int getflag = (mask & ZFD_DELAYEDOPEN) ? FILE_DELAYEDOPEN : 0;
if (retcode)
*retcode = 0;
if (index > 0)
return NULL;
if (zfile_needwrite (zf)) {
if (retcode)
*retcode = -1;
return NULL;
}
zv = getzvolume (parent, zf, id);
if (!zv)
return NULL;
we_have_file = 0;
tmphist[0] = 0;
zipcnt = 1;
first = 1;
zn = &zv->root;
while (zn) {
int isok = 1;
diskimg = -1;
if (zn->type != ZNODE_FILE)
isok = 0;
if (zfile_is_ignore_ext (zn->fullname))
isok = 0;
diskimg = zfile_is_diskimage (zn->fullname);
if (isok) {
if (tmphist[0]) {
#ifndef _CONSOLE
if (diskimg >= 0 && canhistory)
DISK_history_add (tmphist, -1, diskimg, 1);
#endif
tmphist[0] = 0;
first = 0;
}
if (first) {
if (diskimg >= 0)
_tcscpy (tmphist, zn->fullname);
} else {
_tcscpy (tmphist, zn->fullname);
#ifndef _CONSOLE
if (diskimg >= 0 && canhistory)
DISK_history_add (tmphist, -1, diskimg, 1);
#endif
tmphist[0] = 0;
}
select = 0;
if (!zf->zipname)
select = 1;
if (zf->zipname && _tcslen (zn->fullname) >= _tcslen (zf->zipname) && !strcasecmp (zf->zipname, zn->fullname + _tcslen (zn->fullname) - _tcslen (zf->zipname)))
select = -1;
if (zf->zipname && zf->zipname[0] == '#' && _tstol (zf->zipname + 1) == zipcnt)
select = -1;
if (select && we_have_file < 10) {
struct zfile *zt = NULL;
const TCHAR *ext = zfile_get_ext(zn->fullname);
int whf = 1;
int ft = 0;
if (mask & ZFD_CD) {
if (ext && !_tcsicmp (ext, _T(".iso"))) {
whf = 2;
ft = ZFILE_CDIMAGE;
}
if (ext && !_tcsicmp (ext, _T(".chd"))) {
whf = 2;
ft = ZFILE_CDIMAGE;
}
if (ext && !_tcsicmp (ext, _T(".ccd"))) {
whf = 9;
ft = ZFILE_CDIMAGE;
}
if (ext && !_tcsicmp (ext, _T(".cue"))) {
whf = 10;
ft = ZFILE_CDIMAGE;
}
} else {
zt = archive_getzfile (zn, id, getflag);
ft = zfile_gettype (zt);
}
if ((select < 0 || ft) && whf > we_have_file) {
if (!zt)
zt = archive_getzfile (zn, id, getflag);
we_have_file = whf;
if (z)
zfile_fclose (z);
z = zt;
zt = NULL;
}
zfile_fclose (zt);
}
}
zipcnt++;
zn = zn->next;
}
#ifndef _CONSOLE
diskimg = zfile_is_diskimage (zfile_getname (zf));
if (diskimg >= 0 && first && tmphist[0] && canhistory)
DISK_history_add (zfile_getname (zf), -1, diskimg, 1);
#endif
zfile_fclose_archive (zv);
if (z) {
zfile_fclose (zf);
zf = z;
} else if (!dodefault && zf->zipname && zf->zipname[0]) {
if (retcode)
*retcode = -1;
zf = NULL;
} else {
zf = NULL;
}
return zf;
}
struct zfile *archive_access_arcacc_select (struct zfile *zf, unsigned int id, int *retcode)
{
if (zfile_needwrite (zf)) {
if (retcode)
*retcode = -1;
return NULL;
}
return zf;
}
void archive_access_scan (struct zfile *zf, zfile_callback zc, void *user, unsigned int id)
{
struct zvolume *zv;
struct znode *zn;
zv = getzvolume (NULL, zf, id);
if (!zv)
return;
zn = &zv->root;
while (zn) {
if (zn->type == ZNODE_FILE) {
struct zfile *zf2 = archive_getzfile (zn, id, 0);
if (zf2) {
int ztype = iszip (zf2);
if (ztype) {
zfile_fclose (zf2);
} else {
int ret = zc (zf2, user);
zfile_fclose (zf2);
if (ret)
break;
}
}
}
zn = zn->next;
}
zfile_fclose_archive (zv);
}
/* TAR */
static void archive_close_tar (void *handle)
{
}
struct zvolume *archive_directory_tar (struct zfile *z)
{
struct zvolume *zv;
struct znode *zn;
_tzset ();
zv = zvolume_alloc (z, ArchiveFormatTAR, NULL, NULL);
for (;;) {
uae_u8 block[512];
char name[MAX_DPATH];
int ustar = 0;
struct zarchive_info zai;
int valid = 1;
uae_u64 size;
if (zfile_fread (block, 512, 1, z) != 1)
break;
if (block[0] == 0)
break;
if (!memcmp (block + 257, "ustar ", 8))
ustar = 1;
name[0] = 0;
if (ustar)
strcpy (name, (char*)block + 345);
strcat (name, (char*)block);
if (name[0] == 0)
valid = 0;
if (block[156] != '0')
valid = 0;
if (ustar && (block[256] != 0 && block[256] != '0'))
valid = 0;
size = _strtoui64 ((char*)block + 124, NULL, 8);
if (valid) {
memset (&zai, 0, sizeof zai);
zai.name = au (name);
zai.size = size;
zai.tv.tv_sec = _strtoui64 ((char*)block + 136, NULL, 8);
zai.tv.tv_sec += _timezone;
if (_daylight)
zai.tv.tv_sec -= 1 * 60 * 60;
if (zai.name[_tcslen (zai.name) - 1] == '/') {
zn = zvolume_adddir_abs (zv, &zai);
} else {
zn = zvolume_addfile_abs (zv, &zai);
if (zn)
zn->offset = zfile_ftell32(z);
}
xfree (zai.name);
}
zfile_fseek (z, (size + 511) & ~511, SEEK_CUR);
}
zv->method = ArchiveFormatTAR;
return zv;
}
struct zfile *archive_access_tar (struct znode *zn)
{
#if 0
struct zfile *zf = zfile_fopen_empty (zn->volume->archive, zn->fullname, zn->size);
zfile_fseek (zn->volume->archive, zn->offset, SEEK_SET);
zfile_fwrite (zf->data, zn->size, 1, zn->volume->archive);
return zf;
#else
return zfile_fopen_parent (zn->volume->archive, zn->fullname, zn->offset, zn->size);
#endif
}
/* ZIP */
#ifdef A_ZIP
static void archive_close_zip (void *handle)
{
}
struct zvolume *archive_directory_zip (struct zfile *z)
{
unzFile uz;
unz_file_info file_info;
struct zvolume *zv;
int err;
uz = unzOpen (z);
if (!uz)
return 0;
if (unzGoToFirstFile (uz) != UNZ_OK)
return 0;
zv = zvolume_alloc (z, ArchiveFormatZIP, NULL, NULL);
for (;;) {
char filename_inzip2[MAX_DPATH];
TCHAR c;
struct zarchive_info zai;
time_t t;
unsigned int dd;
TCHAR *filename_inzip;
err = unzGetCurrentFileInfo (uz, &file_info, filename_inzip2, sizeof (filename_inzip2), NULL, 0, NULL, 0);
if (err != UNZ_OK)
return 0;
if (file_info.flag & (1 << 11)) { // UTF-8 encoded
filename_inzip = utf8u (filename_inzip2);
} else {
filename_inzip = au (filename_inzip2);
}
dd = file_info.dosDate;
t = fromdostime (dd);
memset (&zai, 0, sizeof zai);
zai.name = filename_inzip;
zai.tv.tv_sec = t;
zai.flags = -1;
c = filename_inzip[_tcslen (filename_inzip) - 1];
if (c != '/' && c != '\\') {
int err = unzOpenCurrentFile (uz);
if (err == UNZ_OK) {
struct znode *zn;
zai.size = file_info.uncompressed_size;
zn = zvolume_addfile_abs (zv, &zai);
}
} else {
filename_inzip[_tcslen (filename_inzip) - 1] = 0;
zvolume_adddir_abs (zv, &zai);
}
xfree (filename_inzip);
err = unzGoToNextFile (uz);
if (err != UNZ_OK)
break;
}
unzClose (uz);
zv->method = ArchiveFormatZIP;
return zv;
}
static struct zfile *archive_do_zip (struct znode *zn, struct zfile *z, int flags)
{
unzFile uz;
int i;
TCHAR tmp[MAX_DPATH];
TCHAR *name = z ? z->archiveparent->name : zn->volume->root.fullname;
char *s;
uz = unzOpen (z ? z->archiveparent : zn->volume->archive);
if (!uz)
return 0;
if (z)
_tcscpy (tmp, z->archiveparent->name);
else
_tcscpy (tmp, zn->fullname + _tcslen (zn->volume->root.fullname) + 1);
if (unzGoToFirstFile (uz) != UNZ_OK)
goto error;
for (i = 0; tmp[i]; i++) {
if (tmp[i] == '\\')
tmp[i] = '/';
}
s = ua (tmp);
if (unzLocateFile (uz, s, 1) != UNZ_OK) {
xfree (s);
for (i = 0; tmp[i]; i++) {
if (tmp[i] == '/')
tmp[i] = '\\';
}
s = ua (tmp);
if (unzLocateFile (uz, s, 1) != UNZ_OK) {
xfree (s);
goto error;
}
}
xfree (s);
s = NULL;
if (unzOpenCurrentFile (uz) != UNZ_OK)
goto error;
if (!z)
z = zfile_fopen_empty (NULL, zn->fullname, zn->size);
if (z) {
int err = -1;
if (!(flags & FILE_DELAYEDOPEN) || z->size <= PEEK_BYTES) {
unpack_log (_T("ZIP: unpacking %s, flags=%d\n"), name, flags);
err = unzReadCurrentFile (uz, z->data, (unsigned int)z->datasize);
unpack_log (_T("ZIP: unpacked, code=%d\n"), err);
} else {
z->archiveparent = zfile_dup (zn->volume->archive);
if (z->archiveparent) {
unpack_log (_T("ZIP: delayed open '%s'\n"), name);
xfree (z->archiveparent->name);
z->archiveparent->name = my_strdup (tmp);
z->datasize = PEEK_BYTES;
err = unzReadCurrentFile (uz, z->data, (unsigned int)z->datasize);
unpack_log (_T("ZIP: unpacked, code=%d\n"), err);
} else {
unpack_log (_T("ZIP: unpacking %s (failed DELAYEDOPEN)\n"), name);
err = unzReadCurrentFile (uz, z->data, (unsigned int)z->datasize);
unpack_log (_T("ZIP: unpacked, code=%d\n"), err);
}
}
}
unzCloseCurrentFile (uz);
unzClose (uz);
return z;
error:
unzClose (uz);
return NULL;
}
static struct zfile *archive_access_zip (struct znode *zn, int flags)
{
return archive_do_zip (zn, NULL, flags);
}
static struct zfile *archive_unpack_zip (struct zfile *zf)
{
return archive_do_zip (NULL, zf, 0);
}
#endif
#ifdef A_7Z
/* 7Z */
#include "7z/7z.h"
#include "7z/Alloc.h"
#include "7z/7zFile.h"
#include "7z/7zVersion.h"
#include "7z/7zCrc.h"
static void *SzAlloc (void *p, size_t size)
{
return xmalloc (uae_u8, size);
}
static void SzFree(void *p, void *address)
{
xfree (address);
}
static ISzAlloc allocImp;
static ISzAlloc allocTempImp;
static SRes SzFileReadImp (void *object, void *buffer, size_t *size)
{
CFileInStream *s = (CFileInStream *)object;
struct zfile *zf = (struct zfile*)s->file.myhandle;
*size = zfile_fread (buffer, 1, *size, zf);
return SZ_OK;
}
static SRes SzFileSeekImp(void *object, Int64 *pos, ESzSeek origin)
{
CFileInStream *s = (CFileInStream *)object;
struct zfile *zf = (struct zfile*)s->file.myhandle;
int org = 0;
switch (origin)
{
case SZ_SEEK_SET: org = SEEK_SET; break;
case SZ_SEEK_CUR: org = SEEK_CUR; break;
case SZ_SEEK_END: org = SEEK_END; break;
}
zfile_fseek (zf, *pos, org);
*pos = zfile_ftell (zf);
return SZ_OK;
}
static void init_7z (void)
{
static int initialized;
if (initialized)
return;
initialized = 1;
allocImp.Alloc = SzAlloc;
allocImp.Free = SzFree;
allocTempImp.Alloc = SzAlloc;
allocTempImp.Free = SzFree;
CrcGenerateTable ();
_tzset ();
}
struct SevenZContext
{
CSzArEx db;
CFileInStream archiveStream;
CLookToRead lookStream;
Byte *outBuffer;
size_t outBufferSize;
UInt32 blockIndex;
};
static void archive_close_7z (void *ctx)
{
struct SevenZContext *ctx7 = (struct SevenZContext*)ctx;
SzArEx_Free (&ctx7->db, &allocImp);
allocImp.Free (&allocImp, ctx7->outBuffer);
xfree (ctx);
}
#define EPOCH_DIFF 0x019DB1DED53E8000LL /* 116444736000000000 nsecs */
#define RATE_DIFF 10000000 /* 100 nsecs */
struct zvolume *archive_directory_7z (struct zfile *z)
{
SRes res;
struct zvolume *zv;
int i;
struct SevenZContext *ctx;
init_7z ();
ctx = xcalloc (struct SevenZContext, 1);
ctx->blockIndex = 0xffffffff;
ctx->archiveStream.s.Read = SzFileReadImp;
ctx->archiveStream.s.Seek = SzFileSeekImp;
ctx->archiveStream.file.myhandle = (void*)z;
LookToRead_CreateVTable (&ctx->lookStream, False);
ctx->lookStream.realStream = &ctx->archiveStream.s;
LookToRead_Init (&ctx->lookStream);
SzArEx_Init (&ctx->db);
res = SzArEx_Open (&ctx->db, &ctx->lookStream.s, &allocImp, &allocTempImp);
if (res != SZ_OK) {
write_log (_T("7Z: SzArchiveOpen %s returned %d\n"), zfile_getname (z), res);
xfree (ctx);
return NULL;
}
zv = zvolume_alloc (z, ArchiveFormat7Zip, ctx, NULL);
for (i = 0; i < ctx->db.db.NumFiles; i++) {
CSzFileItem *f = ctx->db.db.Files + i;
TCHAR *name = (TCHAR*)(ctx->db.FileNames.data + ctx->db.FileNameOffsets[i] * 2);
struct zarchive_info zai;
memset(&zai, 0, sizeof zai);
zai.name = name;
zai.flags = f->AttribDefined ? f->Attrib : -1;
zai.size = f->Size;
if (f->MTimeDefined) {
uae_u64 t = (((uae_u64)f->MTime.High) << 32) | f->MTime.Low;
if (t >= EPOCH_DIFF) {
zai.tv.tv_sec = (t - EPOCH_DIFF) / RATE_DIFF;
zai.tv.tv_sec -= _timezone;
if (_daylight)
zai.tv.tv_sec += 1 * 60 * 60;
}
}
if (!f->IsDir) {
struct znode *zn = zvolume_addfile_abs (zv, &zai);
if (zn)
zn->offset = i;
}
}
zv->method = ArchiveFormat7Zip;
return zv;
}
static struct zfile *archive_access_7z (struct znode *zn)
{
SRes res;
struct zvolume *zv = zn->volume;
struct zfile *z = NULL;
size_t offset;
size_t outSizeProcessed;
struct SevenZContext *ctx;
z = zfile_fopen_empty (NULL, zn->fullname, zn->size);
if (!z)
return NULL;
ctx = (struct SevenZContext*)zv->handle;
res = SzArEx_Extract (&ctx->db, &ctx->lookStream.s, zn->offset,
&ctx->blockIndex, &ctx->outBuffer, &ctx->outBufferSize,
&offset, &outSizeProcessed,
&allocImp, &allocTempImp);
if (res == SZ_OK) {
zfile_fwrite (ctx->outBuffer + offset, (size_t)zn->size, 1, z);
} else {
write_log (_T("7Z: SzExtract %s returned %d\n"), zn->fullname, res);
zfile_fclose (z);
z = NULL;
}
return z;
}
#endif
/* RAR */
#ifdef A_RAR
/* copy and paste job? you are only imagining it! */
static struct zfile *rarunpackzf; /* stupid unrar.dll */
#include <unrar.h>
typedef HANDLE (_stdcall* RAROPENARCHIVEEX)(struct RAROpenArchiveDataEx*);
static RAROPENARCHIVEEX pRAROpenArchiveEx;
typedef int (_stdcall* RARREADHEADEREX)(HANDLE,struct RARHeaderDataEx*);
static RARREADHEADEREX pRARReadHeaderEx;
typedef int (_stdcall* RARPROCESSFILE)(HANDLE,int,char*,char*);
static RARPROCESSFILE pRARProcessFile;
typedef int (_stdcall* RARCLOSEARCHIVE)(HANDLE);
static RARCLOSEARCHIVE pRARCloseArchive;
typedef void (_stdcall* RARSETCALLBACK)(HANDLE,UNRARCALLBACK,LONG);
static RARSETCALLBACK pRARSetCallback;
typedef int (_stdcall* RARGETDLLVERSION)(void);
static RARGETDLLVERSION pRARGetDllVersion;
static int canrar (void)
{
static int israr;
if (israr == 0) {
israr = -1;
#ifdef _WIN32
{
HMODULE rarlib;
rarlib = WIN32_LoadLibrary (_T("unrar.dll"));
if (rarlib) {
TCHAR tmp[MAX_DPATH];
tmp[0] = 0;
GetModuleFileName (rarlib, tmp, sizeof tmp / sizeof (TCHAR));
pRAROpenArchiveEx = (RAROPENARCHIVEEX)GetProcAddress (rarlib, "RAROpenArchiveEx");
pRARReadHeaderEx = (RARREADHEADEREX)GetProcAddress (rarlib, "RARReadHeaderEx");
pRARProcessFile = (RARPROCESSFILE)GetProcAddress (rarlib, "RARProcessFile");
pRARCloseArchive = (RARCLOSEARCHIVE)GetProcAddress (rarlib, "RARCloseArchive");
pRARSetCallback = (RARSETCALLBACK)GetProcAddress (rarlib, "RARSetCallback");
pRARGetDllVersion = (RARGETDLLVERSION)GetProcAddress (rarlib, "RARGetDllVersion");
if (pRAROpenArchiveEx && pRARReadHeaderEx && pRARProcessFile && pRARCloseArchive && pRARSetCallback) {
int version = -1;
israr = 1;
if (pRARGetDllVersion)
version = pRARGetDllVersion ();
write_log (_T("%s version %08X detected\n"), tmp, version);
if (version < 4) {
write_log (_T("Too old unrar.dll, must be at least version 4\n"));
israr = -1;
}
}
}
}
#endif
}
return israr < 0 ? 0 : 1;
}
static int CALLBACK RARCallbackProc (UINT msg, LPARAM UserData, LPARAM P1, LPARAM P2)
{
if (msg == UCM_PROCESSDATA) {
zfile_fwrite ((uae_u8*)P1, 1, P2, rarunpackzf);
return 0;
}
return -1;
}
struct RARContext
{
struct RAROpenArchiveDataEx OpenArchiveData;
struct RARHeaderDataEx HeaderData;
HANDLE hArcData;
};
static void archive_close_rar (void *ctx)
{
struct RARContext* rc = (struct RARContext*)ctx;
xfree (rc);
}
struct zvolume *archive_directory_rar (struct zfile *z)
{
struct zvolume *zv;
struct RARContext *rc;
struct zfile *zftmp;
int cnt;
if (!canrar ())
return archive_directory_arcacc (z, ArchiveFormatRAR);
if (z->data)
/* wtf? stupid unrar.dll only accept filename as an input.. */
return archive_directory_arcacc (z, ArchiveFormatRAR);
rc = xcalloc (struct RARContext, 1);
zv = zvolume_alloc (z, ArchiveFormatRAR, rc, NULL);
rc->OpenArchiveData.ArcNameW = z->name;
rc->OpenArchiveData.OpenMode = RAR_OM_LIST;
rc->hArcData = pRAROpenArchiveEx (&rc->OpenArchiveData);
if (rc->OpenArchiveData.OpenResult != 0) {
zfile_fclose_archive (zv);
return archive_directory_arcacc (z, ArchiveFormatRAR);
}
pRARSetCallback (rc->hArcData, RARCallbackProc, 0);
cnt = 0;
while (pRARReadHeaderEx (rc->hArcData, &rc->HeaderData) == 0) {
struct zarchive_info zai;
struct znode *zn;
memset (&zai, 0, sizeof zai);
zai.name = rc->HeaderData.FileNameW;
zai.size = rc->HeaderData.UnpSize;
zai.flags = -1;
zai.tv.tv_sec = fromdostime (rc->HeaderData.FileTime);
zn = zvolume_addfile_abs (zv, &zai);
if (zn)
zn->offset = cnt++;
pRARProcessFile (rc->hArcData, RAR_SKIP, NULL, NULL);
}
pRARCloseArchive (rc->hArcData);
zftmp = zfile_fopen_empty (z, z->name, 0);
zv->archive = zftmp;
zv->method = ArchiveFormatRAR;
return zv;
}
static struct zfile *archive_access_rar (struct znode *zn)
{
struct RARContext *rc = (struct RARContext*)zn->volume->handle;
int i;
struct zfile *zf = NULL;
if (zn->volume->method != ArchiveFormatRAR)
return archive_access_arcacc (zn);
rc->OpenArchiveData.OpenMode = RAR_OM_EXTRACT;
rc->hArcData = pRAROpenArchiveEx (&rc->OpenArchiveData);
if (rc->OpenArchiveData.OpenResult != 0)
return NULL;
pRARSetCallback (rc->hArcData, RARCallbackProc, 0);
for (i = 0; i <= zn->offset; i++) {
if (pRARReadHeaderEx (rc->hArcData, &rc->HeaderData))
return NULL;
if (i < zn->offset) {
if (pRARProcessFile (rc->hArcData, RAR_SKIP, NULL, NULL))
goto end;
}
}
zf = zfile_fopen_empty (zn->volume->archive, zn->fullname, zn->size);
if (zf) {
rarunpackzf = zf;
if (pRARProcessFile (rc->hArcData, RAR_TEST, NULL, NULL)) {
zfile_fclose (zf);
zf = NULL;
}
}
end:
pRARCloseArchive(rc->hArcData);
return zf;
}
#endif
/* ArchiveAccess */
#if defined(ARCHIVEACCESS)
struct aaFILETIME
{
uae_u32 dwLowDateTime;
uae_u32 dwHighDateTime;
};
typedef void* aaHandle;
// This struct contains file information from an archive. The caller may store
// this information for accessing this file after calls to findFirst, findNext
#define FileInArchiveInfoStringSize 1024
struct aaFileInArchiveInfo {
int ArchiveHandle; // handle for Archive/class pointer
uae_u64 CompressedFileSize;
uae_u64 UncompressedFileSize;
uae_u32 attributes;
int IsDir;
struct aaFILETIME LastWriteTime;
char path[FileInArchiveInfoStringSize];
};
typedef HRESULT (__stdcall *aaReadCallback)(int StreamID, uae_u64 offset, uae_u32 count, void* buf, uae_u32 *processedSize);
typedef HRESULT (__stdcall *aaWriteCallback)(int StreamID, uae_u64 offset, uae_u32 count, const void *buf, uae_u32 *processedSize);
typedef aaHandle (__stdcall *aapOpenArchive)(aaReadCallback function, int StreamID, uae_u64 FileSize, int ArchiveType, int *result, TCHAR *password);
typedef int (__stdcall *aapGetFileCount)(aaHandle ArchiveHandle);
typedef int (__stdcall *aapGetFileInfo)(aaHandle ArchiveHandle, int FileNum, struct aaFileInArchiveInfo *FileInfo);
typedef int (__stdcall *aapExtract)(aaHandle ArchiveHandle, int FileNum, int StreamID, aaWriteCallback WriteFunc, uae_u64 *written);
typedef int (__stdcall *aapCloseArchive)(aaHandle ArchiveHandle);
static aapOpenArchive aaOpenArchive;
static aapGetFileCount aaGetFileCount;
static aapGetFileInfo aaGetFileInfo;
static aapExtract aaExtract;
static aapCloseArchive aaCloseArchive;
#ifdef _WIN32
static HMODULE arcacc_mod;
static void arcacc_free (void)
{
if (arcacc_mod)
FreeLibrary (arcacc_mod);
arcacc_mod = NULL;
}
static int arcacc_init (struct zfile *zf)
{
if (arcacc_mod)
return 1;
arcacc_mod = WIN32_LoadLibrary (_T("archiveaccess.dll"));
if (!arcacc_mod) {
write_log (_T("failed to open archiveaccess.dll ('%s')\n"), zfile_getname (zf));
return 0;
}
aaOpenArchive = (aapOpenArchive) GetProcAddress (arcacc_mod, "aaOpenArchive");
aaGetFileCount = (aapGetFileCount) GetProcAddress (arcacc_mod, "aaGetFileCount");
aaGetFileInfo = (aapGetFileInfo) GetProcAddress (arcacc_mod, "aaGetFileInfo");
aaExtract = (aapExtract) GetProcAddress (arcacc_mod, "aaExtract");
aaCloseArchive = (aapCloseArchive) GetProcAddress (arcacc_mod, "aaCloseArchive");
if (!aaOpenArchive || !aaGetFileCount || !aaGetFileInfo || !aaExtract || !aaCloseArchive) {
write_log (_T("Missing functions in archiveaccess.dll. Old version?\n"));
arcacc_free ();
return 0;
}
return 1;
}
#endif
#define ARCACC_STACKSIZE 10
static struct zfile *arcacc_stack[ARCACC_STACKSIZE];
static int arcacc_stackptr = -1;
static int arcacc_push (struct zfile *f)
{
if (arcacc_stackptr == ARCACC_STACKSIZE - 1)
return -1;
arcacc_stackptr++;
arcacc_stack[arcacc_stackptr] = f;
return arcacc_stackptr;
}
static void arcacc_pop (void)
{
arcacc_stackptr--;
}
static HRESULT __stdcall readCallback (int StreamID, uae_u64 offset, uae_u32 count, void *buf, uae_u32 *processedSize)
{
struct zfile *f = arcacc_stack[StreamID];
int ret;
zfile_fseek (f, (long)offset, SEEK_SET);
ret = (int)zfile_fread (buf, 1, count, f);
if (processedSize)
*processedSize = ret;
return 0;
}
static HRESULT __stdcall writeCallback (int StreamID, uae_u64 offset, uae_u32 count, const void *buf, uae_u32 *processedSize)
{
struct zfile *f = arcacc_stack[StreamID];
int ret;
ret = (int)zfile_fwrite ((void*)buf, 1, count, f);
if (processedSize)
*processedSize = ret;
if (ret != count)
return -1;
return 0;
}
struct zvolume *archive_directory_arcacc (struct zfile *z, unsigned int id)
{
aaHandle ah;
int id_r, status;
int fc, f;
struct zvolume *zv;
int skipsize = 0;
if (!arcacc_init (z))
return NULL;
zv = zvolume_alloc (z, ArchiveFormatAA, NULL, NULL);
id_r = arcacc_push (z);
ah = aaOpenArchive (readCallback, id_r, zv->archivesize, id, &status, NULL);
if (!status) {
zv->handle = ah;
fc = aaGetFileCount (ah);
for (f = 0; f < fc; f++) {
struct aaFileInArchiveInfo fi;
TCHAR *name;
struct znode *zn;
struct zarchive_info zai;
memset (&fi, 0, sizeof (fi));
aaGetFileInfo (ah, f, &fi);
if (fi.IsDir)
continue;
name = au (fi.path);
memset (&zai, 0, sizeof zai);
zai.name = name;
zai.flags = -1;
zai.size = (unsigned int)fi.UncompressedFileSize;
zn = zvolume_addfile_abs (zv, &zai);
if (zn) {
zn->offset = f;
zn->method = id;
}
xfree(name);
if (id == ArchiveFormat7Zip) {
if (fi.CompressedFileSize)
skipsize = 0;
skipsize += (int)fi.UncompressedFileSize;
}
}
aaCloseArchive (ah);
}
arcacc_pop ();
zv->method = ArchiveFormatAA;
return zv;
}
static struct zfile *archive_access_arcacc (struct znode *zn)
{
struct zfile *zf = NULL;
struct zfile *z = zn->volume->archive;
int status, id_r, id_w;
aaHandle ah;
int ok = 0;
id_r = arcacc_push (z);
ah = aaOpenArchive (readCallback, id_r, zn->volume->archivesize, zn->method, &status, NULL);
if (!status) {
int err;
uae_u64 written = 0;
struct aaFileInArchiveInfo fi;
memset (&fi, 0, sizeof (fi));
aaGetFileInfo (ah, zn->offset, &fi);
zf = zfile_fopen_empty (z, zn->fullname, zn->size);
id_w = arcacc_push (zf);
err = aaExtract(ah, zn->offset, id_w, writeCallback, &written);
if (zf->seek == fi.UncompressedFileSize)
ok = 1;
arcacc_pop();
}
aaCloseArchive(ah);
arcacc_pop();
if (ok)
return zf;
zfile_fclose(zf);
return NULL;
}
#endif
/* plain single file */
static struct znode *addfile (struct zvolume *zv, struct zfile *zf, const TCHAR *path, uae_u8 *data, int size)
{
struct zarchive_info zai;
struct znode *zn;
struct zfile *z;
z = zfile_fopen_empty (zf, path, size);
if (!z)
return NULL;
zfile_fwrite (data, size, 1, z);
memset (&zai, 0, sizeof zai);
zai.name = my_strdup (path);
zai.flags = -1;
zai.size = size;
zn = zvolume_addfile_abs (zv, &zai);
if (zn)
zn->f = z;
else
zfile_fclose (z);
xfree (zai.name);
return zn;
}
static uae_u8 exeheader[]={0x00,0x00,0x03,0xf3,0x00,0x00,0x00,0x00};
struct zvolume *archive_directory_plain (struct zfile *z)
{
struct zfile *zf, *zf2;
struct zvolume *zv;
struct znode *zn;
struct zarchive_info zai;
uae_u8 id[8];
int rc, index;
memset (&zai, 0, sizeof zai);
zv = zvolume_alloc (z, ArchiveFormatPLAIN, NULL, NULL);
memset(id, 0, sizeof id);
zai.name = zfile_getfilename (z);
zai.flags = -1;
zfile_fseek(z, 0, SEEK_END);
zai.size = zfile_ftell (z);
zfile_fseek(z, 0, SEEK_SET);
zfile_fread(id, sizeof id, 1, z);
zfile_fseek(z, 0, SEEK_SET);
zn = zvolume_addfile_abs (zv, &zai);
if (!memcmp (id, exeheader, sizeof id)) {
char *an = ua (zai.name);
char *data = xmalloc (char, 1 + strlen (an) + 1 + 1 + 1);
sprintf (data, "\"%s\"\n", an);
zn = addfile (zv, z, _T("s/startup-sequence"), (uae_u8*)data, uaestrlen (data));
xfree (data);
xfree (an);
}
index = 0;
for (;;) {
zf = zfile_dup (z);
if (!zf)
break;
zf2 = zuncompress (NULL, zf, 0, ZFD_ALL & ~ZFD_ADF, &rc, index);
if (zf2) {
zf = NULL;
zai.name = zfile_getfilename (zf2);
zai.flags = -1;
zfile_fseek (zf2, 0, SEEK_END);
zai.size = zfile_ftell (zf2);
zfile_fseek (zf2, 0, SEEK_SET);
zn = zvolume_addfile_abs (zv, &zai);
if (zn)
zn->f = zf2;
// if (zn)
// zn->offset = index + 1;
// zfile_fclose (zf2);
} else {
if (rc == 0) {
zfile_fclose (zf);
break;
}
}
index++;
zfile_fclose (zf);
}
return zv;
}
static struct zfile *archive_access_plain (struct znode *zn)
{
struct zfile *z;
if (zn->offset) {
struct zfile *zf;
z = zfile_fopen_empty (zn->volume->archive, zn->fullname, zn->size);
zf = zfile_fopen (zfile_getname (zn->volume->archive), _T("rb"), zn->volume->archive->zfdmask & ~ZFD_ADF, zn->offset - 1);
if (zf) {
zfile_fread (z->data, (size_t)zn->size, 1, zf);
zfile_fclose (zf);
}
} else {
z = zfile_fopen_empty (zn->volume->archive, zn->fullname, zn->size);
if (z) {
zfile_fseek (zn->volume->archive, 0, SEEK_SET);
zfile_fread (z->data, (size_t)zn->size, 1, zn->volume->archive);
}
}
return z;
}
struct adfhandle {
int size;
int highblock;
int blocksize;
int rootblock;
struct zfile *z;
uae_u8 block[65536];
uae_u32 dostype;
};
static int dos_checksum (uae_u8 *p, int blocksize)
{
uae_u32 cs = 0;
int i;
for (i = 0; i < blocksize; i += 4)
cs += (p[i] << 24) | (p[i + 1] << 16) | (p[i + 2] << 8) | (p[i + 3] << 0);
return cs;
}
static int sfs_checksum (uae_u8 *p, int blocksize, int sfs2)
{
uae_u32 cs = sfs2 ? 2 : 1;
int i;
for (i = 0; i < blocksize; i += 4)
cs += (p[i] << 24) | (p[i + 1] << 16) | (p[i + 2] << 8) | (p[i + 3] << 0);
return cs;
}
static TCHAR *getBSTR (uae_u8 *bstr)
{
int n = *bstr++;
uae_char buf[257];
int i;
for (i = 0; i < n; i++)
buf[i] = *bstr++;
buf[i] = 0;
return au (buf);
}
static uae_u32 gl (struct adfhandle *adf, int off)
{
uae_u8 *p = adf->block + off;
return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | (p[3] << 0);
}
static uae_u32 glx (uae_u8 *p)
{
return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | (p[3] << 0);
}
static uae_u32 gwx (uae_u8 *p)
{
return (p[0] << 8) | (p[1] << 0);
}
static const int secs_per_day = 24 * 60 * 60;
static const int diff = (8 * 365 + 2) * (24 * 60 * 60);
static const int diff2 = (-8 * 365 - 2) * (24 * 60 * 60);
static time_t put_time (long days, long mins, long ticks)
{
time_t t;
if (days < 0)
days = 0;
if (days > 9900 * 365)
days = 9900 * 365; // in future far enough?
if (mins < 0 || mins >= 24 * 60)
mins = 0;
if (ticks < 0 || ticks >= 60 * 50)
ticks = 0;
t = ticks / 50;
t += mins * 60;
t += ((uae_u64)days) * secs_per_day;
t += diff;
return t;
}
static int adf_read_block (struct adfhandle *adf, int block)
{
memset (adf->block, 0, adf->blocksize);
if (block >= adf->highblock || block < 0)
return 0;
zfile_fseek (adf->z, block * adf->blocksize, SEEK_SET);
zfile_fread (adf->block, adf->blocksize, 1, adf->z);
return 1;
}
static void recurseadf (struct znode *zn, int root, TCHAR *name)
{
int i;
struct zvolume *zv = zn->volume;
struct adfhandle *adf = (struct adfhandle*)zv->handle;
TCHAR name2[MAX_DPATH];
int bs = adf->blocksize;
for (i = 0; i < bs / 4 - 56; i++) {
int block;
if (!adf_read_block (adf, root))
return;
block = gl (adf, (i + 6) * 4);
while (block > 0 && block < adf->size / bs) {
struct zarchive_info zai;
TCHAR *fname;
uae_u32 size, secondary;
if (!adf_read_block (adf, block))
return;
if (gl (adf, 0) != 2)
break;
if (gl (adf, 1 * 4) != block)
break;
secondary = gl (adf, bs - 1 * 4);
if (secondary != -3 && secondary != 2)
break;
memset (&zai, 0, sizeof zai);
fname = getBSTR (adf->block + bs - 20 * 4);
size = gl (adf, bs - 47 * 4);
name2[0] = 0;
if (name[0]) {
TCHAR sep[] = { FSDB_DIR_SEPARATOR, 0 };
_tcscpy (name2, name);
_tcscat (name2, sep);
}
_tcscat (name2, fname);
zai.name = name2;
if (size < 0 || size > 0x7fffffff)
size = 0;
zai.size = size;
zai.flags = gl (adf, bs - 48 * 4);
amiga_to_timeval (&zai.tv, gl (adf, bs - 23 * 4), gl (adf, bs - 22 * 4),gl (adf, bs - 21 * 4), 50);
if (secondary == -3) {
struct znode *znnew = zvolume_addfile_abs (zv, &zai);
if (znnew)
znnew->offset = block;
} else {
struct znode *znnew = zvolume_adddir_abs (zv, &zai);
if (znnew) {
znnew->offset = block;
recurseadf (znnew, block, name2);
}
if (!adf_read_block (adf, block))
return;
}
xfree (fname);
block = gl (adf, bs - 4 * 4);
}
}
}
static void recursesfs (struct znode *zn, int root, TCHAR *name, int sfs2)
{
struct zvolume *zv = zn->volume;
struct adfhandle *adf = (struct adfhandle*)zv->handle;
TCHAR name2[MAX_DPATH];
int block;
uae_u8 *p, *s;
struct zarchive_info zai;
block = root;
while (block) {
if (!adf_read_block (adf, block))
return;
p = adf->block + 12 + 3 * 4;
while (glx (p + 4) && p < adf->block + adf->blocksize - 27) {
TCHAR *fname;
int i;
int align;
memset (&zai, 0, sizeof zai);
zai.flags = glx (p + 8) ^ 0x0f;
s = p + (sfs2 ? 27 : 25);
fname = au ((char*)s);
i = 0;
while (*s) {
s++;
i++;
}
s++;
i++;
if (*s)
zai.comment = au ((char*)s);
while (*s) {
s++;
i++;
}
s++;
i++;
i += sfs2 ? 27 : 25;
align = i & 1;
name2[0] = 0;
if (name[0]) {
TCHAR sep[] = { FSDB_DIR_SEPARATOR, 0 };
_tcscpy (name2, name);
_tcscat (name2, sep);
}
_tcscat (name2, fname);
zai.name = name2;
if (sfs2)
zai.tv.tv_sec = glx (p + 22) - diff2;
else
zai.tv.tv_sec = glx (p + 20) - diff;
if (p[sfs2 ? 26 : 24] & 0x80) { // dir
struct znode *znnew = zvolume_adddir_abs (zv, &zai);
int newblock = glx (p + 16);
if (newblock) {
znnew->offset = block;
recursesfs (znnew, newblock, name2, sfs2);
}
if (!adf_read_block (adf, block))
return;
} else {
struct znode *znnew;
if (sfs2) {
uae_u64 b1 = p[16];
uae_u64 b2 = p[17];
zai.size = (b1 << 40) | (b2 << 32) | glx (p + 18) ;
} else {
zai.size = glx (p + 16);
}
znnew = zvolume_addfile_abs (zv, &zai);
if (znnew) {
znnew->offset = block;
znnew->offset2 = addrdiff(p, adf->block);
}
}
xfree (zai.comment);
xfree (fname);
p += i + align;
}
block = gl (adf, 12 + 4);
}
}
struct zvolume *archive_directory_adf (struct znode *parent, struct zfile *z)
{
struct zvolume *zv;
struct adfhandle *adf;
TCHAR name[MAX_DPATH];
int gotroot = 0;
adf = xcalloc (struct adfhandle, 1);
zfile_fseek (z, 0, SEEK_END);
adf->size = zfile_ftell32(z);
zfile_fseek (z, 0, SEEK_SET);
adf->blocksize = 512;
if (parent && parent->offset2) {
if (parent->offset2 == 1024 || parent->offset2 == 2048 || parent->offset2 == 4096 || parent->offset2 == 8192 ||
parent->offset2 == 16384 || parent->offset2 == 32768 || parent->offset2 == 65536) {
adf->blocksize = parent->offset2;
gotroot = 1;
}
}
adf->highblock = adf->size / adf->blocksize;
adf->z = z;
if (!adf_read_block (adf, 0))
goto fail;
adf->dostype = gl (adf, 0);
if ((adf->dostype & 0xffffff00) == MCC('D', 'O', 'S', '\0')) {
int bs = adf->blocksize;
int res;
adf->rootblock = ((adf->size / bs) - 1 + 2) / 2;
if (!gotroot) {
for (res = 2; res >= 1; res--) {
for (bs = 512; bs < 65536; bs <<= 1) {
adf->blocksize = bs;
adf->rootblock = ((adf->size / bs) - 1 + res) / 2;
if (!adf_read_block (adf, adf->rootblock))
continue;
if (gl (adf, 0) != 2 || gl (adf, bs - 1 * 4) != 1)
continue;
if (dos_checksum (adf->block, bs) != 0)
continue;
gotroot = 1;
break;
}
if (gotroot)
break;
}
}
if (!gotroot) {
bs = adf->blocksize = 512;
if (adf->size < 2000000 && adf->rootblock != 880) {
adf->rootblock = 880;
if (!adf_read_block (adf, adf->rootblock))
goto fail;
if (gl (adf, 0) != 2 || gl (adf, bs - 1 * 4) != 1)
goto fail;
if (dos_checksum (adf->block, bs) != 0)
goto fail;
}
}
if (!adf_read_block (adf, adf->rootblock))
goto fail;
if (gl (adf, 0) != 2 || gl (adf, bs - 1 * 4) != 1)
goto fail;
if (dos_checksum (adf->block, adf->blocksize) != 0)
goto fail;
adf->blocksize = bs;
adf->highblock = adf->size / adf->blocksize;
zv = zvolume_alloc (z, ArchiveFormatADF, NULL, NULL);
zv->method = ArchiveFormatADF;
zv->handle = adf;
zv->volumename = getBSTR (adf->block + adf->blocksize - 20 * 4);
name[0] = 0;
recurseadf (&zv->root, adf->rootblock, name);
} else if ((adf->dostype & 0xffffff00) == MCC('S', 'F', 'S', '\0')) {
uae_u16 version, sfs2;
for (;;) {
for (;;) {
version = gl (adf, 12) >> 16;
sfs2 = version > 3;
if (version > 4)
break;
adf->rootblock = gl (adf, 104);
if (!adf_read_block (adf, adf->rootblock))
break;
if (gl (adf, 0) != MCC('O', 'B', 'J', 'C'))
break;
if (sfs_checksum (adf->block, adf->blocksize, sfs2))
break;
adf->rootblock = gl (adf, 40);
if (!adf_read_block (adf, adf->rootblock))
break;
if (gl (adf, 0) != MCC('O', 'B', 'J', 'C'))
break;
if (sfs_checksum (adf->block, adf->blocksize, sfs2))
break;
gotroot = 1;
break;
}
if (gotroot)
break;
adf->blocksize <<= 1;
if (adf->blocksize == 65536)
break;
}
if (!gotroot)
goto fail;
zv = zvolume_alloc (z, ArchiveFormatADF, NULL, NULL);
zv->method = ArchiveFormatADF;
zv->handle = adf;
name[0] = 0;
recursesfs (&zv->root, adf->rootblock, name, version > 3);
} else {
goto fail;
}
return zv;
fail:
xfree (adf);
return NULL;
}
struct sfsblock
{
int block;
int length;
};
static int sfsfindblock (struct adfhandle *adf, int btree, int theblock, struct sfsblock **sfsb, int *sfsblockcnt, int *sfsmaxblockcnt, int sfs2)
{
int nodecount, isleaf, nodesize;
int i;
uae_u8 *p;
if (!btree)
return 0;
if (!adf_read_block (adf, btree))
return 0;
if (memcmp (adf->block, "BNDC", 4))
return 0;
nodecount = gwx (adf->block + 12);
isleaf = adf->block[14];
nodesize = adf->block[15];
p = adf->block + 16;
for (i = 0; i < nodecount; i++) {
if (isleaf) {
uae_u32 key = glx (p);
uae_u32 next = glx (p + 4);
uae_u32 prev = glx (p + 8);
uae_u32 blocks;
if (sfs2)
blocks = glx (p + 12);
else
blocks = gwx (p + 12);
if (key == theblock) {
struct sfsblock *sb;
if (*sfsblockcnt >= *sfsmaxblockcnt) {
*sfsmaxblockcnt += 100;
*sfsb = xrealloc (struct sfsblock, *sfsb, *sfsmaxblockcnt);
}
sb = *sfsb + (*sfsblockcnt);
sb->block = key;
sb->length = blocks;
(*sfsblockcnt)++;
return next;
}
} else {
uae_u32 key = glx (p);
uae_u32 data = glx (p + 4);
int newblock = sfsfindblock (adf, data, theblock, sfsb, sfsblockcnt, sfsmaxblockcnt, sfs2);
if (newblock)
return newblock;
if (!adf_read_block (adf, btree))
return 0;
if (memcmp (adf->block, "BNDC", 4))
return 0;
}
p += nodesize;
}
return 0;
}
static struct zfile *archive_access_adf (struct znode *zn)
{
struct zfile *z = NULL;
int root, ffs;
struct adfhandle *adf = (struct adfhandle*)zn->volume->handle;
uae_s64 size;
int i, bs;
uae_u8 *dst;
size = zn->size;
bs = adf->blocksize;
z = zfile_fopen_empty (zn->volume->archive, zn->fullname, size);
if (!z)
return NULL;
if ((adf->dostype & 0xffffff00) == MCC('D', 'O', 'S', '\0')) {
ffs = adf->dostype & 1;
root = zn->offset;
dst = z->data;
for (;;) {
adf_read_block (adf, root);
for (i = bs / 4 - 51; i >= 6; i--) {
uae_s64 bsize = ffs ? bs : bs - 24;
int block = gl (adf, i * 4);
if (size < bsize)
bsize = size;
if (ffs)
zfile_fseek (adf->z, block * adf->blocksize, SEEK_SET);
else
zfile_fseek (adf->z, block * adf->blocksize + 24, SEEK_SET);
zfile_fread (dst, (size_t)bsize, 1, adf->z);
size -= bsize;
dst += bsize;
if (size <= 0)
break;
}
if (size <= 0)
break;
root = gl (adf, bs - 2 * 4);
}
} else if ((adf->dostype & 0xffffff00) == MCC('S', 'F', 'S', '\0')) {
struct sfsblock *sfsblocks;
int sfsblockcnt, sfsmaxblockcnt, i;
uae_s64 bsize;
int block = zn->offset;
int dblock;
int btree, version, sfs2;
uae_u8 *p;
if (!adf_read_block (adf, 0))
goto end;
btree = glx (adf->block + 108);
version = gwx (adf->block + 12);
sfs2 = version > 3;
if (!adf_read_block (adf, block))
goto end;
p = adf->block + zn->offset2;
dblock = glx (p + 12);
sfsblockcnt = 0;
sfsmaxblockcnt = 0;
sfsblocks = NULL;
if (size > 0) {
int nextblock = dblock;
while (nextblock) {
nextblock = sfsfindblock (adf, btree, nextblock, &sfsblocks, &sfsblockcnt, &sfsmaxblockcnt, sfs2);
}
}
bsize = 0;
for (i = 0; i < sfsblockcnt; i++)
bsize += sfsblocks[i].length * adf->blocksize;
if (bsize < size)
write_log (_T("SFS extracting error, %s size mismatch %d<%d\n"), z->name, bsize, size);
dst = z->data;
block = zn->offset;
for (i = 0; i < sfsblockcnt; i++) {
block = sfsblocks[i].block;
bsize = sfsblocks[i].length * adf->blocksize;
zfile_fseek (adf->z, block * adf->blocksize, SEEK_SET);
if (bsize > size)
bsize = size;
zfile_fread (dst, (size_t)bsize, 1, adf->z);
dst += bsize;
size -= bsize;
}
xfree (sfsblocks);
}
return z;
end:
zfile_fclose (z);
return NULL;
}
static void archive_close_adf (void *v)
{
struct adfhandle *adf = (struct adfhandle*)v;
xfree (adf);
}
static int rl (uae_u8 *p)
{
return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | (p[3]);
}
static TCHAR *tochar (uae_u8 *s, int len)
{
int i, j;
uae_char tmp[256];
j = 0;
for (i = 0; i < len; i++) {
uae_char c = *s++;
if (c >= 0 && c <= 9) {
tmp[j++] = FSDB_DIR_SEPARATOR;
tmp[j++] = '0' + c;
} else if (c < ' ' || c > 'z') {
tmp[j++] = '.';
} else {
tmp[j++] = c;
}
tmp[j] = 0;
}
return au (tmp);
}
struct zvolume *archive_directory_rdb (struct zfile *z)
{
uae_u8 buf[512] = { 0 };
int partnum, bs;
TCHAR *devname;
struct zvolume *zv;
struct zarchive_info zai;
uae_u8 *p;
struct znode *zn;
zv = zvolume_alloc (z, ArchiveFormatRDB, NULL, NULL);
zfile_fseek (z, 0, SEEK_SET);
zfile_fread (buf, 1, 512, z);
partnum = 0;
for (;;) {
int partblock;
TCHAR tmp[MAX_DPATH];
int surf, spt, spb, lowcyl, highcyl, reserved;
int size, block, blocksize, rootblock;
TCHAR comment[81], *dos;
if (partnum == 0)
partblock = rl (buf + 28);
else
partblock = rl (buf + 4 * 4);
partnum++;
if (partblock <= 0)
break;
zfile_fseek (z, partblock * 512, SEEK_SET);
zfile_fread (buf, 1, 512, z);
if (memcmp (buf, "PART", 4))
break;
p = buf + 128 - 16;
surf = rl (p + 28);
spb = rl (p + 32);
spt = rl (p + 36);
reserved = rl (p + 40);
lowcyl = rl (p + 52);
highcyl = rl (p + 56);
blocksize = rl (p + 20) * 4 * spb;
block = lowcyl * surf * spt;
size = (highcyl - lowcyl + 1) * surf * spt;
size *= blocksize;
dos = tochar (buf + 192, 4);
if (!memcmp (dos, _T("DOS"), 3))
rootblock = ((size / blocksize) - 1 + 2) / 2;
else
rootblock = 0;
devname = getBSTR (buf + 36);
_stprintf (tmp, _T("%s.hdf"), devname);
memset (&zai, 0, sizeof zai);
_stprintf (comment, _T("FS=%s LO=%d HI=%d HEADS=%d SPT=%d RES=%d BLOCK=%d ROOT=%d"),
dos, lowcyl, highcyl, surf, spt, reserved, blocksize, rootblock);
zai.comment = comment;
xfree (dos);
zai.name = tmp;
zai.size = size;
zai.flags = -1;
zn = zvolume_addfile_abs (zv, &zai);
if (zn) {
zn->offset = partblock;
zn->offset2 = blocksize; // abuse of offset2..
}
}
zfile_fseek (z, 0, SEEK_SET);
p = buf;
zfile_fread (buf, 1, 512, z);
zai.name = my_strdup(_T("rdb_dump.dat"));
bs = rl (p + 16);
zai.size = rl (p + 140) * bs;
zai.comment = NULL;
zn = zvolume_addfile_abs (zv, &zai);
zn->offset = 0;
zv->method = ArchiveFormatRDB;
return zv;
}
static struct zfile *archive_access_rdb (struct znode *zn)
{
struct zfile *z = zn->volume->archive;
struct zfile *zf;
uae_u8 buf[512] = { 0 };
int surf, spb, spt, lowcyl, highcyl;
int block, blocksize;
uae_s64 size;
uae_u8 *p;
if (zn->offset) {
zfile_fseek (z, zn->offset * 512, SEEK_SET);
zfile_fread (buf, 1, 512, z);
p = buf + 128 - 16;
surf = rl (p + 28);
spb = rl (p + 32);
spt = rl (p + 36);
lowcyl = rl (p + 52);
highcyl = rl (p + 56);
blocksize = rl (p + 20) * 4;
block = lowcyl * surf * spt;
size = (highcyl - lowcyl + 1) * surf * spt;
size *= blocksize;
} else {
zfile_fseek (z, 0, SEEK_SET);
zfile_fread (buf, 1, 512, z);
p = buf;
blocksize = rl (p + 16);
block = 0;
size = zn->size;
}
zf = zfile_fopen_parent (z, zn->fullname, block * blocksize, size);
return zf;
}
int isfat (uae_u8 *p)
{
int i, b;
if ((p[0x15] & 0xf0) != 0xf0)
return 0;
if (p[0x0b] != 0x00 || p[0x0c] != 0x02)
return 0;
b = 0;
for (i = 0; i < 8; i++) {
if (p[0x0d] & (1 << i))
b++;
}
if (b != 1)
return 0;
if (p[0x0f] != 0)
return 0;
if (p[0x0e] > 8 || p[0x0e] == 0)
return 0;
if (p[0x10] == 0 || p[0x10] > 8)
return 0;
b = (p[0x12] << 8) | p[0x11];
if (b > 8192 || b <= 0)
return 0;
b = p[0x16] | (p[0x17] << 8);
if (b == 0 || b > 8192)
return 0;
return 1;
}
/*
* The epoch of FAT timestamp is 1980.
* : bits : value
* date: 0 - 4: day (1 - 31)
* date: 5 - 8: month (1 - 12)
* date: 9 - 15: year (0 - 127) from 1980
* time: 0 - 4: sec (0 - 29) 2sec counts
* time: 5 - 10: min (0 - 59)
* time: 11 - 15: hour (0 - 23)
*/
#define SECS_PER_MIN 60
#define SECS_PER_HOUR (60 * 60)
#define SECS_PER_DAY (SECS_PER_HOUR * 24)
#define UNIX_SECS_1980 315532800L
#if BITS_PER_LONG == 64
#define UNIX_SECS_2108 4354819200L
#endif
/* days between 1.1.70 and 1.1.80 (2 leap days) */
#define DAYS_DELTA (365 * 10 + 2)
/* 120 (2100 - 1980) isn't leap year */
#define YEAR_2100 120
#define IS_LEAP_YEAR(y) (!((y) & 3) && (y) != YEAR_2100)
/* Linear day numbers of the respective 1sts in non-leap years. */
static time_t days_in_year[] = {
/* Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec */
0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 0, 0, 0,
};
/* Convert a FAT time/date pair to a UNIX date (seconds since 1 1 70). */
static time_t fat_time_fat2unix (uae_u16 time, uae_u16 date, int fat12)
{
time_t second, day, leap_day, month, year;
if (0 && fat12) {
year = date & 0x7f;
month = (date >> 7) & 0x0f;
day = (date >> 11);
} else {
year = date >> 9;
month = max(1, (date >> 5) & 0xf);
day = max(1, date & 0x1f) - 1;
}
leap_day = (year + 3) / 4;
if (year > YEAR_2100) /* 2100 isn't leap year */
leap_day--;
if (IS_LEAP_YEAR(year) && month > 2)
leap_day++;
second = (time & 0x1f) << 1;
second += ((time >> 5) & 0x3f) * SECS_PER_MIN;
second += (time >> 11) * SECS_PER_HOUR;
second += (year * 365 + leap_day
+ days_in_year[month] + day
+ DAYS_DELTA) * SECS_PER_DAY;
return second;
}
static int getcluster (struct zfile *z, int cluster, int fatstart, int fatbits)
{
uae_u32 fat = 0;
uae_u8 p[4];
int offset = cluster * fatbits;
zfile_fseek (z, fatstart * 512 + offset / 8, SEEK_SET);
if (fatbits == 12) {
zfile_fread (p, 2, 1, z);
if ((offset & 4))
fat = ((p[0] & 0xf0) >> 4) | (p[1] << 4);
else
fat = (p[0]) | ((p[1] & 0x0f) << 8);
if (fat >= 0xff0)
return -1;
} else if (fatbits == 16) {
zfile_fread (p, 2, 1, z);
fat = p[0] | (p[1] << 8);
if (fat >= 0xfff0)
return -1;
} else if (fatbits == 32) {
zfile_fread (p, 4, 1, z);
fat = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
fat &= ~0x0fffffff;
if (fat >= 0x0ffffff0)
return -1;
}
return fat;
}
static void fatdirectory (struct zfile *z, struct zvolume *zv, const TCHAR *name, int startblock, int entries, int sectorspercluster, int fatstart, int dataregion, int fatbits)
{
struct zarchive_info zai;
struct znode *znnew;
int i, j;
for (i = 0; i < entries; i++) {
TCHAR name2[MAX_DPATH], *fname;
uae_s64 size;
uae_u8 fatname[16];
uae_u8 buf[32];
int attr, cnt, ext;
int startcluster;
memset (buf, 0, sizeof buf);
memset (&zai, 0, sizeof zai);
zfile_fseek (z, startblock * 512 + i * 32, SEEK_SET);
zfile_fread (buf, 32, 1, z);
if (buf[0] == 0)
break;
if (buf[0] == 0xe5)
continue;
if (buf[0] == 0x05)
buf[0] = 0xe5;
size = buf[0x1c] | (buf[0x1d] << 8) | (buf[0x1e] << 16) | (buf[0x1f] << 24);
attr = buf[0x0b];
startcluster = buf[0x1a] | (buf[0x1b] << 8);
if ((attr & (0x4 | 0x2)) == 0x06) // system+hidden
continue;
if (attr & 8) // disk name
continue;
if (attr & 1) // read-only
zai.flags |= 1 << 3;
if (!(attr & 32)) // archive
zai.flags |= 1 << 4;
cnt = 0;
ext = 0;
for (j = 0; j < 8 && buf[j] != 0x20 && buf[j] != 0; j++)
fatname[cnt++] = buf[j];
for (j = 0; j < 3 && buf[8 + j] != 0x20 && buf[8 + j] != 0; j++) {
if (ext == 0)
fatname[cnt++] = '.';
ext = 1;
fatname[cnt++] = buf[8 + j];
}
fatname[cnt] = 0;
fname = au ((char*)fatname);
name2[0] = 0;
if (name[0]) {
TCHAR sep[] = { FSDB_DIR_SEPARATOR, 0 };
_tcscpy (name2, name);
_tcscat (name2, sep);
}
_tcscat (name2, fname);
zai.name = name2;
zai.tv.tv_sec = fat_time_fat2unix (buf[0x16] | (buf[0x17] << 8), buf[0x18] | (buf[0x19] << 8), 1);
if (attr & (16 | 8)) {
int nextblock, cluster;
nextblock = dataregion + (startcluster - 2) * sectorspercluster;
cluster = getcluster (z, startcluster, fatstart, fatbits);
if ((cluster < 0 || cluster >= 3) && nextblock != startblock) {
znnew = zvolume_adddir_abs (zv, &zai);
fatdirectory (z, zv, name2, nextblock, sectorspercluster * 512 / 32, sectorspercluster, fatstart, dataregion, fatbits);
while (cluster >= 3) {
nextblock = dataregion + (cluster - 2) * sectorspercluster;
fatdirectory (z, zv, name2, nextblock, sectorspercluster * 512 / 32, sectorspercluster, fatstart, dataregion, fatbits);
cluster = getcluster (z, cluster, fatstart, fatbits);
}
}
} else {
zai.size = size;
znnew = zvolume_addfile_abs (zv, &zai);
if (znnew) {
znnew->offset = startcluster;
}
}
xfree (fname);
}
}
struct zvolume *archive_directory_fat (struct zfile *z)
{
uae_u8 buf[512] = { 0 };
int fatbits = 12;
struct zvolume *zv;
int rootdir, reserved, sectorspercluster;
int numfats, sectorsperfat, rootentries;
int dataregion;
zfile_fseek (z, 0, SEEK_SET);
zfile_fread (buf, 1, 512, z);
if (!isfat (buf))
return NULL;
reserved = buf[0x0e] | (buf[0x0f] << 8);
numfats = buf[0x10];
sectorsperfat = buf[0x16] | (buf[0x17] << 8);
rootentries = buf[0x11] | (buf[0x12] << 8);
sectorspercluster = buf[0x0d];
rootdir = reserved + numfats * sectorsperfat;
dataregion = rootdir + rootentries * 32 / 512;
zv = zvolume_alloc (z, ArchiveFormatFAT, NULL, NULL);
fatdirectory (z, zv, _T(""), rootdir, rootentries, sectorspercluster, reserved, dataregion, fatbits);
zv->method = ArchiveFormatFAT;
return zv;
}
static struct zfile *archive_access_fat (struct znode *zn)
{
uae_u8 buf[512] = { 0 };
int fatbits = 12;
uae_s64 size = zn->size;
struct zfile *sz, *dz;
int rootdir, reserved, sectorspercluster;
int numfats, sectorsperfat, rootentries;
int dataregion, cluster;
uae_s64 offset;
sz = zn->volume->archive;
zfile_fseek (sz, 0, SEEK_SET);
zfile_fread (buf, 1, 512, sz);
if (!isfat (buf))
return NULL;
reserved = buf[0x0e] | (buf[0x0f] << 8);
numfats = buf[0x10];
sectorsperfat = buf[0x16] | (buf[0x17] << 8);
rootentries = buf[0x11] | (buf[0x12] << 8);
sectorspercluster = buf[0x0d];
rootdir = reserved + numfats * sectorsperfat;
dataregion = rootdir + rootentries * 32 / 512;
dz = zfile_fopen_empty (sz, zn->fullname, size);
if (!dz)
return NULL;
offset = 0;
cluster = zn->offset;
while (size && cluster >= 2) {
uae_s64 left = size > sectorspercluster * 512 ? sectorspercluster * 512 : size;
int sector = dataregion + (cluster - 2) * sectorspercluster;
zfile_fseek (sz, sector * 512, SEEK_SET);
zfile_fread (dz->data + offset, 1, (size_t)left, sz);
size -= left;
offset += left;
cluster = getcluster (sz, cluster, reserved, fatbits);
}
return dz;
}
void archive_access_close (void *handle, unsigned int id)
{
switch (id)
{
#ifdef A_ZIP
case ArchiveFormatZIP:
archive_close_zip (handle);
break;
#endif
#ifdef A_7Z
case ArchiveFormat7Zip:
archive_close_7z (handle);
break;
#endif
#ifdef A_RAR
case ArchiveFormatRAR:
archive_close_rar (handle);
break;
#endif
#ifdef A_LHA
case ArchiveFormatLHA:
break;
#endif
case ArchiveFormatADF:
archive_close_adf (handle);
break;
case ArchiveFormatTAR:
archive_close_tar (handle);
break;
}
}
static struct zfile *archive_access_dir (struct znode *zn)
{
return zfile_fopen (zn->fullname, _T("rb"), 0);
}
struct zfile *archive_unpackzfile (struct zfile *zf)
{
struct zfile *zout = NULL;
if (!zf->archiveparent)
return NULL;
unpack_log (_T("delayed unpack '%s'\n"), zf->name);
zf->datasize = zf->size;
switch (zf->archiveid)
{
#ifdef A_ZIP
case ArchiveFormatZIP:
zout = archive_unpack_zip (zf);
break;
#endif
}
zfile_fclose (zf->archiveparent);
zf->archiveparent = NULL;
zf->archiveid = 0;
return NULL;
}
struct zfile *archive_getzfile (struct znode *zn, unsigned int id, int flags)
{
struct zfile *zf = NULL;
switch (id)
{
#ifdef A_ZIP
case ArchiveFormatZIP:
zf = archive_access_zip (zn, flags);
break;
#endif
#ifdef A_7Z
case ArchiveFormat7Zip:
zf = archive_access_7z (zn);
break;
#endif
#ifdef A_RAR
case ArchiveFormatRAR:
zf = archive_access_rar (zn);
break;
#endif
#ifdef A_LHA
case ArchiveFormatLHA:
zf = archive_access_lha (zn);
break;
#endif
#ifdef A_LZX
case ArchiveFormatLZX:
zf = archive_access_lzx (zn);
break;
#endif
case ArchiveFormatPLAIN:
zf = archive_access_plain (zn);
break;
case ArchiveFormatADF:
zf = archive_access_adf (zn);
break;
case ArchiveFormatRDB:
zf = archive_access_rdb (zn);
break;
case ArchiveFormatFAT:
zf = archive_access_fat (zn);
break;
case ArchiveFormatDIR:
zf = archive_access_dir (zn);
break;
case ArchiveFormatTAR:
zf = archive_access_tar (zn);
break;
}
if (zf) {
zf->archiveid = id;
zfile_fseek (zf, 0, SEEK_SET);
}
return zf;
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FILEFINDER_HPP_
#define FILEFINDER_HPP_
#include <string>
#include <vector>
#include <filesystem>
namespace fs = std::filesystem;
/**
* Structure encapsulating the enumeration of path 'types', i.e. what a path
* can be relative to. This allows us to write things like RelativeTo::ChasteTestOutput
* for readability.
*/
struct RelativeTo
{
/**
* What things a path can be relative to.
*/
enum Value
{
CWD, /**< The current working directory */
ChasteTestOutput, /**< The CHASTE_TEST_OUTPUT folder */
ChasteSourceRoot, /**< The root of the Chaste source tree */
ChasteBuildRoot, /**< The root of the Chaste build tree */
Absolute, /**< This is an absolute path */
AbsoluteOrCwd /**< If it starts with a / then it's absolute, otherwise interpret relative to CWD */
};
};
/**
* A helper class for finding files or directories, given paths which can be relative
* to various locations (e.g. the Chaste source tree root, the current directory, the
* Chaste test output directory, or an absolute path).
*/
class FileFinder
{
public:
/**
* Default constructor for subclasses to use. They should call
* SetPath() in their constructor.
*
* This also allows classes to store a FileFinder instance that hasn't
* been properly set up yet, and assign to it later using operator=.
*/
FileFinder();
/**
* Main constructor.
*
* @param rPath the path to the file/dir to find
* @param relativeTo how to interpret this path
*/
FileFinder(const std::string& rPath, RelativeTo::Value relativeTo);
/**
* Find a file (or folder) relative to some file or directory.
* If the second argument is a directory, we look for the given leaf name within it.
* If the second argument is a file, then we look for a sibling.
* An exception is raised if rParentOrSibling does not exist.
*
* @param rLeafName the leaf name of the file/dir to find
* @param rParentOrSibling where to look for it
*/
FileFinder(const std::string& rLeafName, const FileFinder& rParentOrSibling);
/**
* Conversion constructor from a std::filesystem path object.
* Note that since fs::path has a conversion constructor from std::string,
* this allows us to be initialised with a string or character constant, too.
* The path will be interpreted as relative to the current working directory,
* unless it is an absolute path.
*
* @param rPath the path to the file/dir to find
*/
FileFinder(const fs::path& rPath);
/**
* Needed because we have virtual methods.
*/
virtual ~FileFinder();
/**
* Change this FileFinder to point at a new location.
*
* @param rPath the path to the file/dir to find
* @param relativeTo how to interpret this path
*/
virtual void SetPath(const std::string& rPath, RelativeTo::Value relativeTo);
/**
* Change this FileFinder to point at a new location, relative to some file or directory.
*
* @param rLeafName the leaf name of the file/dir to find
* @param rParentOrSibling where to look for it
*/
virtual void SetPath(const std::string& rLeafName, const FileFinder& rParentOrSibling);
/**
* @return true if this FileFinder has been given a path.
*/
bool IsPathSet() const;
/**
* @return true if we exist (as either a file or a directory).
*/
bool Exists() const;
/**
* @return true if we are pointing at a file
*/
bool IsFile() const;
/**
* @return true if we are pointing at a directory
*/
bool IsDir() const;
/**
* @return true if this is a file of size zero or
* if this is a folder, whether it contains no non-hidden items.
* If this doesn't exist, throws.
*/
bool IsEmpty() const;
/**
* @return the absolute path to this file/dir.
*
* If this is a directory that exists (at the instant of this call), the absolute path is
* guaranteed to end in a '/'. Otherwise, the path is guaranteed not to end in a '/'.
*/
std::string GetAbsolutePath() const;
/**
* @return true if this file/dir is newer than another file/dir.
* Compares modification times.
*
* @param rOtherEntity the entity to test against.
*/
bool IsNewerThan(const FileFinder& rOtherEntity) const;
/**
* @return the leaf name of this file or directory.
*
* i.e. the individual file or directory name and none of the preceding folders on its path.
*/
std::string GetLeafName() const;
/**
* @return the leaf name of this file or directory, with any file extension removed.
*
* i.e. the individual file or directory name and none of the preceding folders on its path.
*/
std::string GetLeafNameNoExtension() const;
/**
* @return the extension of the leaf name of this file or directory, if any.
* The '.' will be included in the extension if an extension exists.
*/
std::string GetExtension() const;
/**
* @return a finder for the folder containing this file or directory.
*/
FileFinder GetParent() const;
/**
* @return the relative path to this finder from another. Throws if this is not found under rBasePath.
*
* @param rBasePath where the returned path should be relative to
*/
std::string GetRelativePath(const FileFinder& rBasePath) const;
/**
* Copy this file or folder (recursively in the latter case) to the given destination.
* If the destination is a folder that exists, the source will be copied with the same
* name inside that folder. Otherwise the source will be copied with the given destination
* name.
*
* If the source is a file and the destination is a file that exists it will be removed prior to copying.
* If the source is a folder and the destination is a file that exists then an error is thrown.
*
* @param rDest where to copy to
* @return a finder for the copied entity
*/
FileFinder CopyTo(const FileFinder& rDest) const;
/**
* Recursively remove this file or folder.
* Since this is a potentially very dangerous operation, only locations under the Chaste
* test output folder may be removed.
*
* Only folders created by an OutputFileHandler, or the contents of such a folder, may be
* deleted (folders that have .chaste_deletable_folder present).
*
* If you need to delete a file or folder without .chaste_deletable_folder, then you have to use
* DangerousRemove().
*
*/
void Remove() const;
/**
* This method will allow you to remove any file from under either
* * CHASTE_TEST_OUTPUT
* or
* * the source tree
* (but not elsewhere).
*
* For this reason it is a very dangerous operation and should not be used if Remove could be instead.
*
* BEWARE: if you have managed to set CHASTE_TEST_OUTPUT to "/" this could wipe your system!
*/
void DangerousRemove() const;
/**
* @return a list of files in this folder matching a simple glob pattern.
* This method must be called on a FileFinder that points at a folder, and the pattern
* will be matched against file (or folder) names in that folder. The pattern can use
* a subset of shell-style glob syntax. A '?' anywhere in the string matches any single
* character at that position. A '*' may be used at the start or end of the string to
* match any number of leading or trailing characters, respectively.
* Hidden files (names starting with a '.') will never be matched. Returns a sorted alphabetical list.
*
* @param rPattern the pattern to match names against
*/
std::vector<FileFinder> FindMatches(const std::string& rPattern) const;
/**
* @return true if the path is absolute.
*
* @param rPath the path to test
*/
static bool IsAbsolutePath(const std::string& rPath);
/**
* Replace any spaces in a path or filename with underscores.
*
* @param rPath a path or file name
*/
static void ReplaceSpacesWithUnderscores(std::string& rPath);
/**
* Replace any underscores in a path or filename with spaces (for making titles etc.).
*
* @param rPath a path or file name
*/
static void ReplaceUnderscoresWithSpaces(std::string& rPath);
/**
* For testing purposes, fake the value of one of the normally fixed paths, e.g. ChasteSourceRoot.
*
* @param fakeWhat which path to fake
* @param rFakePath its fake value
*/
static void FakePath(RelativeTo::Value fakeWhat, const std::string& rFakePath);
/**
* Stop faking one of the fixed paths.
*/
static void StopFaking();
/**
* Provide a sort operator to get a logical ordering from FindMatches
* it orders by alphabetical (or ASCII really).
* @param otherFinder Another FileFinder
* @return Whether this FileFinder is earlier in the alphabetical ordering than otherFinder
* */
bool operator<(const FileFinder& otherFinder) const;
private:
/** The absolute path to our file. */
std::string mAbsPath;
/** Whether to fake one of the fixed paths, e.g. ChasteSourceRoot. */
static bool msFaking;
/** Which path to fake. */
static RelativeTo::Value msFakeWhat;
/** The fake value of the faked path. */
static std::string msFakePath;
/**
* This is code common to Remove() and DangerousRemove(). Should remain private and not to be called from elsewhere.
* Remove() is only allowed to delete things with a .chaste_deletable_folder in the testoutput directory.
*
* DangerousRemove() is allowed to delete anything in the source or testoutput directories.
*
* @param dangerous whether we are doing a dangerous remove.
*/
void PrivateRemove(bool dangerous = false) const;
};
#endif /*FILEFINDER_HPP_*/
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "../base.h"
#include "Windows.Globalization.NumberFormatting.0.h"
#include "Windows.Foundation.1.h"
#include "Windows.Foundation.Collections.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Globalization::NumberFormatting {
struct __declspec(uuid("11730ca5-4b00-41b2-b332-73b12a497d54")) __declspec(novtable) ICurrencyFormatter : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Currency(hstring * value) = 0;
virtual HRESULT __stdcall put_Currency(hstring value) = 0;
};
struct __declspec(uuid("072c2f1d-e7ba-4197-920e-247c92f7dea6")) __declspec(novtable) ICurrencyFormatter2 : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Mode(winrt::Windows::Globalization::NumberFormatting::CurrencyFormatterMode * value) = 0;
virtual HRESULT __stdcall put_Mode(winrt::Windows::Globalization::NumberFormatting::CurrencyFormatterMode value) = 0;
virtual HRESULT __stdcall abi_ApplyRoundingForCurrency(winrt::Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm) = 0;
};
struct __declspec(uuid("86c7537e-b938-4aa2-84b0-2c33dc5b1450")) __declspec(novtable) ICurrencyFormatterFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_CreateCurrencyFormatterCode(hstring currencyCode, Windows::Globalization::NumberFormatting::ICurrencyFormatter ** result) = 0;
virtual HRESULT __stdcall abi_CreateCurrencyFormatterCodeContext(hstring currencyCode, Windows::Foundation::Collections::IIterable<hstring> * languages, hstring geographicRegion, Windows::Globalization::NumberFormatting::ICurrencyFormatter ** result) = 0;
};
struct __declspec(uuid("0d018c9a-e393-46b8-b830-7a69c8f89fbb")) __declspec(novtable) IDecimalFormatterFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_CreateDecimalFormatter(Windows::Foundation::Collections::IIterable<hstring> * languages, hstring geographicRegion, Windows::Globalization::NumberFormatting::INumberFormatter ** result) = 0;
};
struct __declspec(uuid("70a64ff8-66ab-4155-9da1-739e46764543")) __declspec(novtable) IIncrementNumberRounder : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_RoundingAlgorithm(winrt::Windows::Globalization::NumberFormatting::RoundingAlgorithm * value) = 0;
virtual HRESULT __stdcall put_RoundingAlgorithm(winrt::Windows::Globalization::NumberFormatting::RoundingAlgorithm value) = 0;
virtual HRESULT __stdcall get_Increment(double * value) = 0;
virtual HRESULT __stdcall put_Increment(double value) = 0;
};
struct __declspec(uuid("a5007c49-7676-4db7-8631-1b6ff265caa9")) __declspec(novtable) INumberFormatter : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_FormatInt(int64_t value, hstring * result) = 0;
virtual HRESULT __stdcall abi_FormatUInt(uint64_t value, hstring * result) = 0;
virtual HRESULT __stdcall abi_FormatDouble(double value, hstring * result) = 0;
};
struct __declspec(uuid("d4a8c1f0-80d0-4b0d-a89e-882c1e8f8310")) __declspec(novtable) INumberFormatter2 : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_FormatInt(int64_t value, hstring * result) = 0;
virtual HRESULT __stdcall abi_FormatUInt(uint64_t value, hstring * result) = 0;
virtual HRESULT __stdcall abi_FormatDouble(double value, hstring * result) = 0;
};
struct __declspec(uuid("80332d21-aee1-4a39-baa2-07ed8c96daf6")) __declspec(novtable) INumberFormatterOptions : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Languages(Windows::Foundation::Collections::IVectorView<hstring> ** value) = 0;
virtual HRESULT __stdcall get_GeographicRegion(hstring * value) = 0;
virtual HRESULT __stdcall get_IntegerDigits(int32_t * value) = 0;
virtual HRESULT __stdcall put_IntegerDigits(int32_t value) = 0;
virtual HRESULT __stdcall get_FractionDigits(int32_t * value) = 0;
virtual HRESULT __stdcall put_FractionDigits(int32_t value) = 0;
virtual HRESULT __stdcall get_IsGrouped(bool * value) = 0;
virtual HRESULT __stdcall put_IsGrouped(bool value) = 0;
virtual HRESULT __stdcall get_IsDecimalPointAlwaysDisplayed(bool * value) = 0;
virtual HRESULT __stdcall put_IsDecimalPointAlwaysDisplayed(bool value) = 0;
virtual HRESULT __stdcall get_NumeralSystem(hstring * value) = 0;
virtual HRESULT __stdcall put_NumeralSystem(hstring value) = 0;
virtual HRESULT __stdcall get_ResolvedLanguage(hstring * value) = 0;
virtual HRESULT __stdcall get_ResolvedGeographicRegion(hstring * value) = 0;
};
struct __declspec(uuid("e6659412-4a13-4a53-83a1-392fbe4cff9f")) __declspec(novtable) INumberParser : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_ParseInt(hstring text, Windows::Foundation::IReference<int64_t> ** result) = 0;
virtual HRESULT __stdcall abi_ParseUInt(hstring text, Windows::Foundation::IReference<uint64_t> ** result) = 0;
virtual HRESULT __stdcall abi_ParseDouble(hstring text, Windows::Foundation::IReference<double> ** result) = 0;
};
struct __declspec(uuid("5473c375-38ed-4631-b80c-ef34fc48b7f5")) __declspec(novtable) INumberRounder : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_RoundInt32(int32_t value, int32_t * result) = 0;
virtual HRESULT __stdcall abi_RoundUInt32(uint32_t value, uint32_t * result) = 0;
virtual HRESULT __stdcall abi_RoundInt64(int64_t value, int64_t * result) = 0;
virtual HRESULT __stdcall abi_RoundUInt64(uint64_t value, uint64_t * result) = 0;
virtual HRESULT __stdcall abi_RoundSingle(float value, float * result) = 0;
virtual HRESULT __stdcall abi_RoundDouble(double value, double * result) = 0;
};
struct __declspec(uuid("3b088433-646f-4efe-8d48-66eb2e49e736")) __declspec(novtable) INumberRounderOption : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_NumberRounder(Windows::Globalization::NumberFormatting::INumberRounder ** value) = 0;
virtual HRESULT __stdcall put_NumberRounder(Windows::Globalization::NumberFormatting::INumberRounder * value) = 0;
};
struct __declspec(uuid("28f5bc2c-8c23-4234-ad2e-fa5a3a426e9b")) __declspec(novtable) INumeralSystemTranslator : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_Languages(Windows::Foundation::Collections::IVectorView<hstring> ** value) = 0;
virtual HRESULT __stdcall get_ResolvedLanguage(hstring * value) = 0;
virtual HRESULT __stdcall get_NumeralSystem(hstring * value) = 0;
virtual HRESULT __stdcall put_NumeralSystem(hstring value) = 0;
virtual HRESULT __stdcall abi_TranslateNumerals(hstring value, hstring * result) = 0;
};
struct __declspec(uuid("9630c8da-36ef-4d88-a85c-6f0d98d620a6")) __declspec(novtable) INumeralSystemTranslatorFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_Create(Windows::Foundation::Collections::IIterable<hstring> * languages, Windows::Globalization::NumberFormatting::INumeralSystemTranslator ** result) = 0;
};
struct __declspec(uuid("b7828aef-fed4-4018-a6e2-e09961e03765")) __declspec(novtable) IPercentFormatterFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_CreatePercentFormatter(Windows::Foundation::Collections::IIterable<hstring> * languages, hstring geographicRegion, Windows::Globalization::NumberFormatting::INumberFormatter ** result) = 0;
};
struct __declspec(uuid("2b37b4ac-e638-4ed5-a998-62f6b06a49ae")) __declspec(novtable) IPermilleFormatterFactory : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall abi_CreatePermilleFormatter(Windows::Foundation::Collections::IIterable<hstring> * languages, hstring geographicRegion, Windows::Globalization::NumberFormatting::INumberFormatter ** result) = 0;
};
struct __declspec(uuid("fd1cdd31-0a3c-49c4-a642-96a1564f4f30")) __declspec(novtable) ISignedZeroOption : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_IsZeroSigned(bool * value) = 0;
virtual HRESULT __stdcall put_IsZeroSigned(bool value) = 0;
};
struct __declspec(uuid("f5941bca-6646-4913-8c76-1b191ff94dfd")) __declspec(novtable) ISignificantDigitsNumberRounder : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_RoundingAlgorithm(winrt::Windows::Globalization::NumberFormatting::RoundingAlgorithm * value) = 0;
virtual HRESULT __stdcall put_RoundingAlgorithm(winrt::Windows::Globalization::NumberFormatting::RoundingAlgorithm value) = 0;
virtual HRESULT __stdcall get_SignificantDigits(uint32_t * value) = 0;
virtual HRESULT __stdcall put_SignificantDigits(uint32_t value) = 0;
};
struct __declspec(uuid("1d4dfcdd-2d43-4ee8-bbf1-c1b26a711a58")) __declspec(novtable) ISignificantDigitsOption : Windows::Foundation::IInspectable
{
virtual HRESULT __stdcall get_SignificantDigits(int32_t * value) = 0;
virtual HRESULT __stdcall put_SignificantDigits(int32_t value) = 0;
};
}
namespace ABI {
template <> struct traits<Windows::Globalization::NumberFormatting::CurrencyFormatter> { using default_interface = Windows::Globalization::NumberFormatting::ICurrencyFormatter; };
template <> struct traits<Windows::Globalization::NumberFormatting::DecimalFormatter> { using default_interface = Windows::Globalization::NumberFormatting::INumberFormatter; };
template <> struct traits<Windows::Globalization::NumberFormatting::IncrementNumberRounder> { using default_interface = Windows::Globalization::NumberFormatting::INumberRounder; };
template <> struct traits<Windows::Globalization::NumberFormatting::NumeralSystemTranslator> { using default_interface = Windows::Globalization::NumberFormatting::INumeralSystemTranslator; };
template <> struct traits<Windows::Globalization::NumberFormatting::PercentFormatter> { using default_interface = Windows::Globalization::NumberFormatting::INumberFormatter; };
template <> struct traits<Windows::Globalization::NumberFormatting::PermilleFormatter> { using default_interface = Windows::Globalization::NumberFormatting::INumberFormatter; };
template <> struct traits<Windows::Globalization::NumberFormatting::SignificantDigitsNumberRounder> { using default_interface = Windows::Globalization::NumberFormatting::INumberRounder; };
}
namespace Windows::Globalization::NumberFormatting {
template <typename D>
struct WINRT_EBO impl_ICurrencyFormatter
{
hstring Currency() const;
[[deprecated("Currency may be read-only for releases after Windows 8.1. Instead, use a new CurrencyFormatter.")]] void Currency(hstring_view value) const;
};
template <typename D>
struct WINRT_EBO impl_ICurrencyFormatter2
{
Windows::Globalization::NumberFormatting::CurrencyFormatterMode Mode() const;
void Mode(Windows::Globalization::NumberFormatting::CurrencyFormatterMode value) const;
void ApplyRoundingForCurrency(Windows::Globalization::NumberFormatting::RoundingAlgorithm roundingAlgorithm) const;
};
template <typename D>
struct WINRT_EBO impl_ICurrencyFormatterFactory
{
Windows::Globalization::NumberFormatting::CurrencyFormatter CreateCurrencyFormatterCode(hstring_view currencyCode) const;
Windows::Globalization::NumberFormatting::CurrencyFormatter CreateCurrencyFormatterCodeContext(hstring_view currencyCode, iterable<hstring> languages, hstring_view geographicRegion) const;
};
template <typename D>
struct WINRT_EBO impl_IDecimalFormatterFactory
{
Windows::Globalization::NumberFormatting::DecimalFormatter CreateDecimalFormatter(iterable<hstring> languages, hstring_view geographicRegion) const;
};
template <typename D>
struct WINRT_EBO impl_IIncrementNumberRounder
{
Windows::Globalization::NumberFormatting::RoundingAlgorithm RoundingAlgorithm() const;
void RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm value) const;
double Increment() const;
void Increment(double value) const;
};
template <typename D>
struct WINRT_EBO impl_INumberFormatter
{
hstring Format(int64_t value) const;
hstring Format(uint64_t value) const;
hstring Format(double value) const;
};
template <typename D>
struct WINRT_EBO impl_INumberFormatter2
{
hstring FormatInt(int64_t value) const;
hstring FormatUInt(uint64_t value) const;
hstring FormatDouble(double value) const;
};
template <typename D>
struct WINRT_EBO impl_INumberFormatterOptions
{
Windows::Foundation::Collections::IVectorView<hstring> Languages() const;
hstring GeographicRegion() const;
int32_t IntegerDigits() const;
void IntegerDigits(int32_t value) const;
int32_t FractionDigits() const;
void FractionDigits(int32_t value) const;
bool IsGrouped() const;
void IsGrouped(bool value) const;
bool IsDecimalPointAlwaysDisplayed() const;
void IsDecimalPointAlwaysDisplayed(bool value) const;
hstring NumeralSystem() const;
void NumeralSystem(hstring_view value) const;
hstring ResolvedLanguage() const;
hstring ResolvedGeographicRegion() const;
};
template <typename D>
struct WINRT_EBO impl_INumberParser
{
Windows::Foundation::IReference<int64_t> ParseInt(hstring_view text) const;
Windows::Foundation::IReference<uint64_t> ParseUInt(hstring_view text) const;
Windows::Foundation::IReference<double> ParseDouble(hstring_view text) const;
};
template <typename D>
struct WINRT_EBO impl_INumberRounder
{
int32_t RoundInt32(int32_t value) const;
uint32_t RoundUInt32(uint32_t value) const;
int64_t RoundInt64(int64_t value) const;
uint64_t RoundUInt64(uint64_t value) const;
float RoundSingle(float value) const;
double RoundDouble(double value) const;
};
template <typename D>
struct WINRT_EBO impl_INumberRounderOption
{
Windows::Globalization::NumberFormatting::INumberRounder NumberRounder() const;
void NumberRounder(const Windows::Globalization::NumberFormatting::INumberRounder & value) const;
};
template <typename D>
struct WINRT_EBO impl_INumeralSystemTranslator
{
Windows::Foundation::Collections::IVectorView<hstring> Languages() const;
hstring ResolvedLanguage() const;
hstring NumeralSystem() const;
void NumeralSystem(hstring_view value) const;
hstring TranslateNumerals(hstring_view value) const;
};
template <typename D>
struct WINRT_EBO impl_INumeralSystemTranslatorFactory
{
Windows::Globalization::NumberFormatting::NumeralSystemTranslator Create(iterable<hstring> languages) const;
};
template <typename D>
struct WINRT_EBO impl_IPercentFormatterFactory
{
Windows::Globalization::NumberFormatting::PercentFormatter CreatePercentFormatter(iterable<hstring> languages, hstring_view geographicRegion) const;
};
template <typename D>
struct WINRT_EBO impl_IPermilleFormatterFactory
{
Windows::Globalization::NumberFormatting::PermilleFormatter CreatePermilleFormatter(iterable<hstring> languages, hstring_view geographicRegion) const;
};
template <typename D>
struct WINRT_EBO impl_ISignedZeroOption
{
bool IsZeroSigned() const;
void IsZeroSigned(bool value) const;
};
template <typename D>
struct WINRT_EBO impl_ISignificantDigitsNumberRounder
{
Windows::Globalization::NumberFormatting::RoundingAlgorithm RoundingAlgorithm() const;
void RoundingAlgorithm(Windows::Globalization::NumberFormatting::RoundingAlgorithm value) const;
uint32_t SignificantDigits() const;
void SignificantDigits(uint32_t value) const;
};
template <typename D>
struct WINRT_EBO impl_ISignificantDigitsOption
{
int32_t SignificantDigits() const;
void SignificantDigits(int32_t value) const;
};
}
namespace impl {
template <> struct traits<Windows::Globalization::NumberFormatting::ICurrencyFormatter>
{
using abi = ABI::Windows::Globalization::NumberFormatting::ICurrencyFormatter;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_ICurrencyFormatter<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::ICurrencyFormatter2>
{
using abi = ABI::Windows::Globalization::NumberFormatting::ICurrencyFormatter2;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_ICurrencyFormatter2<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::ICurrencyFormatterFactory>
{
using abi = ABI::Windows::Globalization::NumberFormatting::ICurrencyFormatterFactory;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_ICurrencyFormatterFactory<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::IDecimalFormatterFactory>
{
using abi = ABI::Windows::Globalization::NumberFormatting::IDecimalFormatterFactory;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_IDecimalFormatterFactory<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::IIncrementNumberRounder>
{
using abi = ABI::Windows::Globalization::NumberFormatting::IIncrementNumberRounder;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_IIncrementNumberRounder<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::INumberFormatter>
{
using abi = ABI::Windows::Globalization::NumberFormatting::INumberFormatter;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_INumberFormatter<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::INumberFormatter2>
{
using abi = ABI::Windows::Globalization::NumberFormatting::INumberFormatter2;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_INumberFormatter2<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::INumberFormatterOptions>
{
using abi = ABI::Windows::Globalization::NumberFormatting::INumberFormatterOptions;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_INumberFormatterOptions<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::INumberParser>
{
using abi = ABI::Windows::Globalization::NumberFormatting::INumberParser;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_INumberParser<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::INumberRounder>
{
using abi = ABI::Windows::Globalization::NumberFormatting::INumberRounder;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_INumberRounder<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::INumberRounderOption>
{
using abi = ABI::Windows::Globalization::NumberFormatting::INumberRounderOption;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_INumberRounderOption<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::INumeralSystemTranslator>
{
using abi = ABI::Windows::Globalization::NumberFormatting::INumeralSystemTranslator;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_INumeralSystemTranslator<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::INumeralSystemTranslatorFactory>
{
using abi = ABI::Windows::Globalization::NumberFormatting::INumeralSystemTranslatorFactory;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_INumeralSystemTranslatorFactory<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::IPercentFormatterFactory>
{
using abi = ABI::Windows::Globalization::NumberFormatting::IPercentFormatterFactory;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_IPercentFormatterFactory<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::IPermilleFormatterFactory>
{
using abi = ABI::Windows::Globalization::NumberFormatting::IPermilleFormatterFactory;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_IPermilleFormatterFactory<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::ISignedZeroOption>
{
using abi = ABI::Windows::Globalization::NumberFormatting::ISignedZeroOption;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_ISignedZeroOption<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::ISignificantDigitsNumberRounder>
{
using abi = ABI::Windows::Globalization::NumberFormatting::ISignificantDigitsNumberRounder;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_ISignificantDigitsNumberRounder<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::ISignificantDigitsOption>
{
using abi = ABI::Windows::Globalization::NumberFormatting::ISignificantDigitsOption;
template <typename D> using consume = Windows::Globalization::NumberFormatting::impl_ISignificantDigitsOption<D>;
};
template <> struct traits<Windows::Globalization::NumberFormatting::CurrencyFormatter>
{
using abi = ABI::Windows::Globalization::NumberFormatting::CurrencyFormatter;
static constexpr const wchar_t * name() noexcept { return L"Windows.Globalization.NumberFormatting.CurrencyFormatter"; }
};
template <> struct traits<Windows::Globalization::NumberFormatting::DecimalFormatter>
{
using abi = ABI::Windows::Globalization::NumberFormatting::DecimalFormatter;
static constexpr const wchar_t * name() noexcept { return L"Windows.Globalization.NumberFormatting.DecimalFormatter"; }
};
template <> struct traits<Windows::Globalization::NumberFormatting::IncrementNumberRounder>
{
using abi = ABI::Windows::Globalization::NumberFormatting::IncrementNumberRounder;
static constexpr const wchar_t * name() noexcept { return L"Windows.Globalization.NumberFormatting.IncrementNumberRounder"; }
};
template <> struct traits<Windows::Globalization::NumberFormatting::NumeralSystemTranslator>
{
using abi = ABI::Windows::Globalization::NumberFormatting::NumeralSystemTranslator;
static constexpr const wchar_t * name() noexcept { return L"Windows.Globalization.NumberFormatting.NumeralSystemTranslator"; }
};
template <> struct traits<Windows::Globalization::NumberFormatting::PercentFormatter>
{
using abi = ABI::Windows::Globalization::NumberFormatting::PercentFormatter;
static constexpr const wchar_t * name() noexcept { return L"Windows.Globalization.NumberFormatting.PercentFormatter"; }
};
template <> struct traits<Windows::Globalization::NumberFormatting::PermilleFormatter>
{
using abi = ABI::Windows::Globalization::NumberFormatting::PermilleFormatter;
static constexpr const wchar_t * name() noexcept { return L"Windows.Globalization.NumberFormatting.PermilleFormatter"; }
};
template <> struct traits<Windows::Globalization::NumberFormatting::SignificantDigitsNumberRounder>
{
using abi = ABI::Windows::Globalization::NumberFormatting::SignificantDigitsNumberRounder;
static constexpr const wchar_t * name() noexcept { return L"Windows.Globalization.NumberFormatting.SignificantDigitsNumberRounder"; }
};
}
}
|
#ifndef NEW_PROJECT_2_PLAYER_HPP
#define NEW_PROJECT_2_PLAYER_HPP
#include <vector>
#include "definitions.hpp"
#include "soldier.hpp"
#include "mistborn.hpp"
#include "misting.hpp"
class Player {
public:
Player();
~Player() = default;
void clear_beings_vector();
// get
short int get_hp() const;
unsigned short get_money() const;
void set_money(unsigned short money);
// set
void set_hp(short hp);
// get army
std::vector<Soldier> get_soldiers() const;
std::vector<Misting> get_mistings() const;
std::vector<Mistborn> get_mistborns() const;
// get resources
std::vector<Metal> get_metals() const;
// set army
void add_soldier(const Soldier &soldier);
void add_misting(const Misting &misting);
void add_mistborn(const Mistborn &mistborn);
// set resources
void add_metal(const Metal &metal);
void update_hp();
void set_metals(); // TODO (nmerk): for each type of being set metal
Player &operator=(const Player &other);
// name
void set_player_name(sf::String &name, const unsigned int x, const unsigned int y);
sf::Text get_player_name();
// avatar
sf::Sprite get_avatar_sprite();
void set_avatar_sprite(const unsigned int chosen_pic_num);
void set_avatar_position(const unsigned int x, const unsigned int y);
private:
unsigned short hp_;
unsigned short money_;
std::vector<Soldier> soldiers_;
std::vector<Mistborn> mistborns_;
std::vector<Misting> mistings_;
std::vector<Metal> metals_;
sf::Font player_name_font_;
sf::Text player_name_;
sf::Texture avatar_texture_;
sf::Sprite avatar_sprite_;
};
#endif // NEW_PROJECT_2_PLAYER_HPP
|
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#include <iostream>
using namespace std;
#include "application.h"
extern Application *getApp();
Application *app = 0;
void keyboardDownFunc( unsigned char key, int x, int y )
{
app -> onKeyboardDown(key);
}
void keyboardUpFunc(unsigned char key, int x, int y )
{
app -> onKeyboardUp(key);
}
void mousePressFunc( int button, int state, int x, int y )
{
app -> onMousePress( button, state, x, y);
}
void mouseMoveFunc( int x, int y )
{
app -> onMouseMove(x, y);
}
#ifdef __APPLE__
bool mojaveWorkAround = true;
#endif
void displayFunc()
{
#ifdef __APPLE__
if(mojaveWorkAround)
{
glutReshapeWindow(0.8 * app->getWidth(), 0.8 * app->getHeight());
mojaveWorkAround = false;
}
#endif
app -> onDisplay();
glFlush();
glutSwapBuffers();
}
void updateFunc( void )
{
app -> onUpdate();
glutPostRedisplay();
}
void reshapeFunc(GLsizei w, GLsizei h )
{
app -> onResize((int)w, (int)h);
}
void createWindow()
{
app = getApp();
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH );
glutInitWindowSize( app->getWidth(), app->getHeight() );
glutInitWindowPosition(0,0);
glutCreateWindow( app->getTitle());
}
void setupCallBacks()
{
glutDisplayFunc( displayFunc );
glutReshapeFunc( reshapeFunc );
glutKeyboardFunc( keyboardDownFunc );
glutKeyboardUpFunc(keyboardUpFunc);
glutMouseFunc( mousePressFunc );
glutMotionFunc( mouseMoveFunc );
glutIdleFunc( updateFunc );
}
void initGraphics()
{
app -> initGraphics();
}
void quit()
{
app->onExit();
delete app;
app = 0;
}
void printOpenGL()
{
const GLubyte* vender = glGetString(GL_VENDOR);
const GLubyte* renderer = glGetString(GL_RENDERER);
const GLubyte* OpenGLVersion =glGetString(GL_VERSION);
const GLubyte* gluVersion=gluGetString(GLU_VERSION);
printf("OpenGL vender:%s\n", vender);
printf("Renderer:%s\n", renderer);
printf("OpenGL version:%s\n",OpenGLVersion );
printf("GLU工 version:%s\n", gluVersion);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
createWindow();
setupCallBacks();
initGraphics();
printOpenGL();
glutMainLoop();
quit();
return 0;
}
|
#include <iostream>
#include "module.h"
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian");
int n;
cout << "Введите размерность массива: ";
cin >> n; // размер массива
int *ptrarray = new int[n]; // выделение памяти для дим.массива
dinamic_array(n, ptrarray);
cout << " " << endl;
print_dinamic_array(n, ptrarray);
cout << " " << endl;
int f=max_dinamic_array(n,ptrarray);
cout << " " << endl;
cout << "Номер максимального элемента - " << f << endl;;
cout << " " << endl;
int m = multiply_dinamic_array(n, ptrarray);
cout << "Произведение элементов массива - " << m << endl;;
cout << " " << endl;
transform_dinamic_array(n, ptrarray);
cout << " " << endl;
delete[] ptrarray; // высвобождение памяти дим.массива
cout << "-------------------------------------------" << endl;
int o;
cout << "Введите размерность массива: ";
cin >> o; // размер массива
float array[20];
cout << " " << endl;
static_array(o, array);
cout << " " << endl;
print_static_array(o, array);
cout << " " << endl;
int h = number_zero_static_array(o, array);
cout << h << endl;
cout << " " << endl;
float ss = sum_static_array(o, array);
cout << ss << endl;
cout << " " << endl;
transform_static_array(o, array);
cout << " " << endl;
system("pause");
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mtree.h"
void InitializeTree(Tree * ptree)
{
ptree->root = NULL;
ptree->treecount = 0;
}
//是否树为空
bool IsTreeEmpty(const Tree * ptree)
{
if (ptree->treecount == 0)
return true;
return false;
}
//是否树为满
bool IsTreeFull(const Tree * ptree)
{
if (ptree->treecount == 0)
return false;
TNode * ptemp;
ptemp = (TNode *)malloc(sizeof(TNode));
if (ptemp == NULL)
{
free(ptemp);
return true;
}
free(ptemp);
return false;
}
//返回树的大小
int TreeSize(const Tree * ptree)
{
return ptree->treecount;
}
//返回比较的大小
static int cmpTreeItem(const TItem *item1, const TItem *item2)
{
if (strcmp(item1->name, item2->name) == 0)
{
if (item1->value == item2->value)
return 0;
else if (item1->value > item2->value)
return 1;
else if (item1->value < item2->value)
return -1;
}
else
return strcmp(item1->name, item2->name);
}
//查找项
TFind FindItemTree(const TItem *item, const Tree * ptree)
{
TFind Fthis;
Fthis.parent = NULL;
Fthis.self = ptree->root;
if (ptree->treecount == 0)
{
return Fthis;
}
while(Fthis.self!=NULL)
{
if (cmpTreeItem(item, &(Fthis.self->item)) > 0)
{
if (Fthis.self!= NULL)
{
Fthis.parent = Fthis.self;
Fthis.self = Fthis.self->right;
}
}
else if (cmpTreeItem(item, &(Fthis.self->item)) < 0)
{
if (Fthis.self!= NULL)
{
Fthis.parent = Fthis.self;
Fthis.self = Fthis.self->left;
}
}
else
break;
}
return Fthis;
}
//添加项
bool AddItemTree(const TItem *item, Tree * ptree)
{
if (IsTreeFull(ptree))
{
printf("full\n");
return false;
}
if (FindItemTree(item, ptree).self!=NULL)
{
printf("the same\n");
return false;
}
TNode * ptemp;
TNode *ptest;
ptemp = (TNode *)malloc(sizeof(TNode));
if (ptemp == NULL)
return false;
else
{
ptemp->item = *item;
ptemp->left = NULL;
ptemp->right = NULL;
}
ptree->treecount++;
ptest = ptree->root;
if (ptree->root == NULL)
{
ptree->root = ptemp;
}
else
{
while (1)
{
if (cmpTreeItem(item, &(ptest->item)) < 0)
{
if (ptest->left == NULL)
{
ptest->left = ptemp;
break;
}
else
{
ptest = ptest->left;
}
}
else if (cmpTreeItem(item, &(ptest->item)) > 0)
{
if (ptest->right == NULL)
{
ptest->right = ptemp;
break;
}
else
{
ptest = ptest->right;
}
}
}
}
return true;
}
//删除节点
static void DelTNode(TNode **pnode)
{
TNode * ptemp;
if ((*pnode)->left == NULL)
{
ptemp = *pnode;
*pnode = (*pnode)->right;
free(ptemp);
}
else if ((*pnode)->right == NULL)
{
ptemp = *pnode;
*pnode = (*pnode)->left;
free(ptemp);
}
else
{
for (ptemp = (*pnode)->left; ptemp->right != NULL; ptemp = ptemp->right)
continue;
ptemp->right = (*pnode)->right;
ptemp = *pnode;
*pnode = (*pnode)->left;
free(ptemp);
}
}
//删除项
bool DelItemTree(const TItem *item, Tree * ptree)
{
if (IsTreeEmpty(ptree))
{
return false;
}
TFind fthis = FindItemTree(item, ptree);
if (fthis.self==NULL)
{
return false;
}
if (fthis.parent == NULL)
{
DelTNode(&ptree->root);
}
else if (fthis.parent->left == fthis.self)
DelTNode(&fthis.parent->left);
else
DelTNode(&fthis.parent->right);
ptree->treecount--;
return true;
}
//本树输出函数
void TreePrintf(TItem *item)
{
printf("%s is %d\n", item->name, item->value);
}
static void InOrder( TNode * pnode, void(*pfun)(TItem * item))
{
if (pnode != NULL)
{
InOrder(pnode->left, pfun);
(*pfun)(&(*pnode).item);
InOrder(pnode->right, pfun);
}
}
//遍历树
void TraverseTree(Tree * ptree, void(*pfun)(TItem * item))
{
if (ptree != NULL)
InOrder(ptree->root, pfun);
}
static void DelNode(TNode * pnode)
{
TNode * ptemp;
if (pnode != NULL)
{
ptemp = pnode->right;
DelNode(pnode->left);
free(pnode);
DelNode(ptemp);
}
}
//清空树
void CleanTree(Tree * ptree)
{
if (ptree != NULL)
DelNode(ptree->root);
ptree->treecount = 0;
ptree->root = NULL;
}
|
// Complete the findMergeNode function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode* next;
* };
*
*/
int findMergeNode(SinglyLinkedListNode* head1, SinglyLinkedListNode* head2) {
SinglyLinkedListNode* itr1 = head1;
SinglyLinkedListNode* itr2 = head2;
bool LS1Adv = true;
while(itr1 != itr2)
{
while(itr1 != itr2)
{
if(itr2->next != NULL)
itr2 = itr2->next;
else
break;
if(itr1 == itr2)
return itr1->data;
}
if (itr1->next != NULL)
{
itr1 = itr1->next;
itr2 = head2;
}
}
return itr1->data;
}
|
#pragma once
#ifndef MUSICPLAYER_H
#define MUSICPLAYER_H
#include <string>
#include <QWidget>
#include <QMediaPlayer>
#include <QMediaPlaylist>
#include <QPushButton>
#include <QToolButton>
#include <QLabel>
#include <QSlider>
#include <QStyle>
#include <QBoxLayout>
#include <QGridLayout>
#include "PlaylistElementGUI.h"
#include "SoundLoader.h"
#include "MediaControls.h"
#include "PlaylistData.h"
class MusicPlayer: public QWidget {
Q_OBJECT
private:
QMediaPlayer* player = nullptr;
MediaControls* media_controls = nullptr;
QPushButton* add_track = nullptr;
QPushButton* remove_track = nullptr;
PlaylistData track_info_data;
QMediaPlaylist* played_songs = nullptr;
PlaylistElementGUI* track_info = nullptr;
void setPlayIcon();
void setPauseIcon();
void setForwardIcon();
void setBackwardIcon();
void buildLayout();
void connections();
void setCustomStyle();
public:
MusicPlayer(QWidget* parent = nullptr);
MusicPlayer(PlaylistElement& track_data, QWidget* parent=nullptr);
void setTrack(PlaylistElement& track_data);
void setPlaylist(PlaylistData playlist);
void setPlaylistTrack(PlaylistElement data);
signals:
void addTrackToPlaylist(PlaylistElement track_data);
void removeTrackFromPlaylist(PlaylistElement track_data);
public slots:
void addTrack();
void removeTrack();
void setNextTrack();
void setPreviousTrack();
};
#endif
|
#include "qartnetreply.h"
QArtNetReply::QArtNetReply(QObject *parent)
: QObject(parent)
{
// Fill with defaults
memset(&m_reply, 0, sizeof(artnet_reply_t));
memcpy(m_reply.id, ARTNET_STRING, ARTNET_STRING_SIZE);
m_reply.opCode = htols(ARTNET_REPLY);
m_reply.port = htols(ARTNET_UDP_PORT);
m_reply.verH = (ARTNET_VERSION >> 8) & 0xff;
m_reply.ver = (ARTNET_VERSION & 0xff);
setSubnet(0); // todo
setOEM(OEM);
setUbea(0);
setStatus(STATUS_INDICATOR_NORMAL | STATUS_PORTAUTH_NETWORK);
setEstaman(ESTAMAN);
setShortName("QArtnet Node");
setLongName("QT QArtNetNode C++ Library");
setNodeReport("OK");
setNumPorts(0);
setStatus2(STATUS2_BROWSER_OK | STATUS2_DHCP | STATUS2_DHCP_CAPABLE | STATUS2_15BIT_PORT);
}
QArtNetReply::QArtNetReply(QObject *parent, QByteArray datagram)
: QObject(parent)
{
memset(&m_reply, 0, sizeof(artnet_reply_t));
memcpy(m_reply.id,
datagram.left(ARTNET_STRING_SIZE).toStdString().c_str(),
ARTNET_STRING_SIZE);
}
void QArtNetReply::setSubnet(uint16_t subnet)
{
}
void QArtNetReply::setOEM(uint16_t oem)
{
}
void QArtNetReply::setUbea(uint16_t ubea)
{
}
void QArtNetReply::setStatus(uint8_t status)
{
}
void QArtNetReply::setEstaman(uint16_t estaman)
{
}
void QArtNetReply::setShortName(QString sname)
{
}
void QArtNetReply::setLongName(QString lname)
{
}
void QArtNetReply::setNodeReport(QString report)
{
}
void QArtNetReply::setNumPorts(uint8_t ports)
{
}
void QArtNetReply::setStatus2(uint8_t status)
{
}
void QArtNetReply::setPortType(uint8_t port, uint8_t type)
{
}
void QArtNetReply::setGoodInput(uint8_t port, uint8_t status)
{
}
void QArtNetReply::setGoodOutput(uint8_t port, uint8_t status)
{
}
void QArtNetReply::setSwin(uint8_t port, uint8_t sw)
{
}
void QArtNetReply::setSwout(uint8_t port, uint8_t sw)
{
}
|
#include "SFML/Graphics.hpp"
#include "Engine/RiDGame.h"
#include "Engine/ConfigurationLoader.h"
int main()
{
RiD::RiDGame window(RiD::ConfigurationLoader::getIntData("video settings", "screenWidth"), RiD::ConfigurationLoader::getIntData("video settings", "screenHeight"), RiD::ConfigurationLoader::getStringData("video settings", "screenTitle"));
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "base.h"
WINRT_WARNING_PUSH
#include "internal/Windows.Devices.Pwm.Provider.3.h"
#include "internal/Windows.Foundation.3.h"
#include "internal/Windows.Devices.Pwm.3.h"
#include "Windows.Devices.h"
#include "Windows.Foundation.h"
WINRT_EXPORT namespace winrt {
namespace impl {
template <typename D>
struct produce<D, Windows::Devices::Pwm::IPwmController> : produce_base<D, Windows::Devices::Pwm::IPwmController>
{
HRESULT __stdcall get_PinCount(int32_t * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().PinCount());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_ActualFrequency(double * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().ActualFrequency());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetDesiredFrequency(double desiredFrequency, double * result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().SetDesiredFrequency(desiredFrequency));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_MinFrequency(double * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().MinFrequency());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_MaxFrequency(double * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().MaxFrequency());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_OpenPin(int32_t pinNumber, impl::abi_arg_out<Windows::Devices::Pwm::IPwmPin> pin) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*pin = detach_abi(this->shim().OpenPin(pinNumber));
return S_OK;
}
catch (...)
{
*pin = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Pwm::IPwmControllerStatics> : produce_base<D, Windows::Devices::Pwm::IPwmControllerStatics>
{
HRESULT __stdcall abi_GetControllersAsync(impl::abi_arg_in<Windows::Devices::Pwm::Provider::IPwmProvider> provider, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::PwmController>>> operation) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*operation = detach_abi(this->shim().GetControllersAsync(*reinterpret_cast<const Windows::Devices::Pwm::Provider::IPwmProvider *>(&provider)));
return S_OK;
}
catch (...)
{
*operation = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Pwm::IPwmControllerStatics2> : produce_base<D, Windows::Devices::Pwm::IPwmControllerStatics2>
{
HRESULT __stdcall abi_GetDefaultAsync(impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Devices::Pwm::PwmController>> operation) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*operation = detach_abi(this->shim().GetDefaultAsync());
return S_OK;
}
catch (...)
{
*operation = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Pwm::IPwmControllerStatics3> : produce_base<D, Windows::Devices::Pwm::IPwmControllerStatics3>
{
HRESULT __stdcall abi_GetDeviceSelector(impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().GetDeviceSelector());
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetDeviceSelectorFromFriendlyName(impl::abi_arg_in<hstring> friendlyName, impl::abi_arg_out<hstring> result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().GetDeviceSelector(*reinterpret_cast<const hstring *>(&friendlyName)));
return S_OK;
}
catch (...)
{
*result = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_FromIdAsync(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Devices::Pwm::PwmController>> operation) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*operation = detach_abi(this->shim().FromIdAsync(*reinterpret_cast<const hstring *>(&deviceId)));
return S_OK;
}
catch (...)
{
*operation = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Pwm::IPwmPin> : produce_base<D, Windows::Devices::Pwm::IPwmPin>
{
HRESULT __stdcall get_Controller(impl::abi_arg_out<Windows::Devices::Pwm::IPwmController> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Controller());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetActiveDutyCyclePercentage(double * result) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_abi(this->shim().GetActiveDutyCyclePercentage());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetActiveDutyCyclePercentage(double dutyCyclePercentage) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetActiveDutyCyclePercentage(dutyCyclePercentage);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Polarity(Windows::Devices::Pwm::PwmPulsePolarity * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Polarity());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall put_Polarity(Windows::Devices::Pwm::PwmPulsePolarity value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Polarity(value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_Start() noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Start();
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_Stop() noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Stop();
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsStarted(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsStarted());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
}
namespace Windows::Devices::Pwm {
template <typename D> int32_t impl_IPwmController<D>::PinCount() const
{
int32_t value {};
check_hresult(WINRT_SHIM(IPwmController)->get_PinCount(&value));
return value;
}
template <typename D> double impl_IPwmController<D>::ActualFrequency() const
{
double value {};
check_hresult(WINRT_SHIM(IPwmController)->get_ActualFrequency(&value));
return value;
}
template <typename D> double impl_IPwmController<D>::SetDesiredFrequency(double desiredFrequency) const
{
double result {};
check_hresult(WINRT_SHIM(IPwmController)->abi_SetDesiredFrequency(desiredFrequency, &result));
return result;
}
template <typename D> double impl_IPwmController<D>::MinFrequency() const
{
double value {};
check_hresult(WINRT_SHIM(IPwmController)->get_MinFrequency(&value));
return value;
}
template <typename D> double impl_IPwmController<D>::MaxFrequency() const
{
double value {};
check_hresult(WINRT_SHIM(IPwmController)->get_MaxFrequency(&value));
return value;
}
template <typename D> Windows::Devices::Pwm::PwmPin impl_IPwmController<D>::OpenPin(int32_t pinNumber) const
{
Windows::Devices::Pwm::PwmPin pin { nullptr };
check_hresult(WINRT_SHIM(IPwmController)->abi_OpenPin(pinNumber, put_abi(pin)));
return pin;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::PwmController>> impl_IPwmControllerStatics<D>::GetControllersAsync(const Windows::Devices::Pwm::Provider::IPwmProvider & provider) const
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::PwmController>> operation;
check_hresult(WINRT_SHIM(IPwmControllerStatics)->abi_GetControllersAsync(get_abi(provider), put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Devices::Pwm::PwmController> impl_IPwmControllerStatics2<D>::GetDefaultAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Devices::Pwm::PwmController> operation;
check_hresult(WINRT_SHIM(IPwmControllerStatics2)->abi_GetDefaultAsync(put_abi(operation)));
return operation;
}
template <typename D> hstring impl_IPwmControllerStatics3<D>::GetDeviceSelector() const
{
hstring result;
check_hresult(WINRT_SHIM(IPwmControllerStatics3)->abi_GetDeviceSelector(put_abi(result)));
return result;
}
template <typename D> hstring impl_IPwmControllerStatics3<D>::GetDeviceSelector(hstring_view friendlyName) const
{
hstring result;
check_hresult(WINRT_SHIM(IPwmControllerStatics3)->abi_GetDeviceSelectorFromFriendlyName(get_abi(friendlyName), put_abi(result)));
return result;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Devices::Pwm::PwmController> impl_IPwmControllerStatics3<D>::FromIdAsync(hstring_view deviceId) const
{
Windows::Foundation::IAsyncOperation<Windows::Devices::Pwm::PwmController> operation;
check_hresult(WINRT_SHIM(IPwmControllerStatics3)->abi_FromIdAsync(get_abi(deviceId), put_abi(operation)));
return operation;
}
template <typename D> Windows::Devices::Pwm::PwmController impl_IPwmPin<D>::Controller() const
{
Windows::Devices::Pwm::PwmController value { nullptr };
check_hresult(WINRT_SHIM(IPwmPin)->get_Controller(put_abi(value)));
return value;
}
template <typename D> double impl_IPwmPin<D>::GetActiveDutyCyclePercentage() const
{
double result {};
check_hresult(WINRT_SHIM(IPwmPin)->abi_GetActiveDutyCyclePercentage(&result));
return result;
}
template <typename D> void impl_IPwmPin<D>::SetActiveDutyCyclePercentage(double dutyCyclePercentage) const
{
check_hresult(WINRT_SHIM(IPwmPin)->abi_SetActiveDutyCyclePercentage(dutyCyclePercentage));
}
template <typename D> Windows::Devices::Pwm::PwmPulsePolarity impl_IPwmPin<D>::Polarity() const
{
Windows::Devices::Pwm::PwmPulsePolarity value {};
check_hresult(WINRT_SHIM(IPwmPin)->get_Polarity(&value));
return value;
}
template <typename D> void impl_IPwmPin<D>::Polarity(Windows::Devices::Pwm::PwmPulsePolarity value) const
{
check_hresult(WINRT_SHIM(IPwmPin)->put_Polarity(value));
}
template <typename D> void impl_IPwmPin<D>::Start() const
{
check_hresult(WINRT_SHIM(IPwmPin)->abi_Start());
}
template <typename D> void impl_IPwmPin<D>::Stop() const
{
check_hresult(WINRT_SHIM(IPwmPin)->abi_Stop());
}
template <typename D> bool impl_IPwmPin<D>::IsStarted() const
{
bool value {};
check_hresult(WINRT_SHIM(IPwmPin)->get_IsStarted(&value));
return value;
}
inline Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Devices::Pwm::PwmController>> PwmController::GetControllersAsync(const Windows::Devices::Pwm::Provider::IPwmProvider & provider)
{
return get_activation_factory<PwmController, IPwmControllerStatics>().GetControllersAsync(provider);
}
inline Windows::Foundation::IAsyncOperation<Windows::Devices::Pwm::PwmController> PwmController::GetDefaultAsync()
{
return get_activation_factory<PwmController, IPwmControllerStatics2>().GetDefaultAsync();
}
inline hstring PwmController::GetDeviceSelector()
{
return get_activation_factory<PwmController, IPwmControllerStatics3>().GetDeviceSelector();
}
inline hstring PwmController::GetDeviceSelector(hstring_view friendlyName)
{
return get_activation_factory<PwmController, IPwmControllerStatics3>().GetDeviceSelector(friendlyName);
}
inline Windows::Foundation::IAsyncOperation<Windows::Devices::Pwm::PwmController> PwmController::FromIdAsync(hstring_view deviceId)
{
return get_activation_factory<PwmController, IPwmControllerStatics3>().FromIdAsync(deviceId);
}
}
}
template<>
struct std::hash<winrt::Windows::Devices::Pwm::IPwmController>
{
size_t operator()(const winrt::Windows::Devices::Pwm::IPwmController & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Pwm::IPwmControllerStatics>
{
size_t operator()(const winrt::Windows::Devices::Pwm::IPwmControllerStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Pwm::IPwmControllerStatics2>
{
size_t operator()(const winrt::Windows::Devices::Pwm::IPwmControllerStatics2 & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Pwm::IPwmControllerStatics3>
{
size_t operator()(const winrt::Windows::Devices::Pwm::IPwmControllerStatics3 & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Pwm::IPwmPin>
{
size_t operator()(const winrt::Windows::Devices::Pwm::IPwmPin & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Pwm::PwmController>
{
size_t operator()(const winrt::Windows::Devices::Pwm::PwmController & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Pwm::PwmPin>
{
size_t operator()(const winrt::Windows::Devices::Pwm::PwmPin & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
WINRT_WARNING_POP
|
#ifndef ESCADA_H
#define ESCADA_H
#include "Obstaculo.h"
class Escada : public Obstaculo
{
protected:
int direction;
public:
Escada();
virtual ~Escada();
void Set_obst(float pos_x, float pos_y, BITMAP* buffer, BITMAP* bmp);
void Print();
private:
};
#endif // ESCADA_H
|
#include "PlayerMesh.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <glm/ext.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
PlayerMesh::PlayerMesh(vector<Vertex> vertices, vector<GLuint> indices, unordered_map<std::uint32_t, vector<Texture>> texturesMap, MaterialNoTex materialNoTex, Shader *shader, bool hasBones = false) : SGeode()
{
this->vertices = vertices;
this->indices = indices;
this->texturesMap = texturesMap;
this->materialNoTex = materialNoTex;
this->shader = shader;
this->hasBones = hasBones;
this->setupMesh();
this->setupUniformLoc();
}
PlayerMesh::~PlayerMesh()
{
}
void PlayerMesh::draw(DrawData& data)
{
if (!shader->isInitilized()) {
cerr << "Shader not initialized" << endl;
exit(-1);
}
shader->bind();
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(data.matrix));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(data.view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(data.projection));
glUniform1i(hasTexLoc, this->texturesMap[data.playerId].size() > 0);
glUniform1i(hasBonesLoc, this->hasBones);
if (this->texturesMap[data.playerId].size() > 0) {
// Bind appropriate textures
GLuint diffuseNr = 1;
GLuint specularNr = 1;
for (GLuint i = 0; i < this->texturesMap[data.playerId].size(); i++)
{
glActiveTexture(GL_TEXTURE0 + i); // Active proper texture unit before binding
// Retrieve texture number (the N in diffuse_textureN)
stringstream ss;
string number;
string name = this->texturesMap[data.playerId][i].type;
if (name == "texture_diffuse")
ss << diffuseNr++; // Transfer GLuint to stream
else if (name == "texture_specular")
ss << specularNr++; // Transfer GLuint to stream
number = ss.str();
// Now set the sampler to the correct texture unit
glUniform1i(glGetUniformLocation(shader->getPid(), (name + number).c_str()), i);
// And finally bind the texture
glBindTexture(GL_TEXTURE_2D, this->texturesMap[data.playerId][i].id);
// Also set each mesh's shininess property to a default value (if you want you could extend this to another mesh property and possibly change this value)
glUniform1f(glGetUniformLocation(shader->getPid(), "material.shininess"), 16.0f);
}
}
else {
glUniform3fv(ambient, 1, glm::value_ptr(this->materialNoTex.ambient));
glUniform3fv(diffuse, 1, glm::value_ptr(this->materialNoTex.diffuse));
glUniform3fv(specular, 1, glm::value_ptr(this->materialNoTex.specular)); // Specular doesn't have full effect on this object's material
glUniform1f(shininess, 16.0f);
}
// Draw mesh
glBindVertexArray(this->VAO);
glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// Always good practice to set everything back to defaults once configured.
for (GLuint i = 0; i < this->texturesMap[data.playerId].size(); i++)
{
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, 0);
}
shader->unbind();
}
void PlayerMesh::update(UpdateData& data)
{
//
}
// Sets bone transformation matrices
void PlayerMesh::setBoneMatrix(GLint index, aiMatrix4x4 matrix)
{
glm::mat4 mat = glm::transpose(glm::make_mat4(&matrix.a1));
glUniformMatrix4fv(boneLocs[index], 1, GL_FALSE, glm::value_ptr(mat));
}
void PlayerMesh::setupMesh() {
// Create buffers/arrays
glGenVertexArrays(1, &this->VAO);
glGenBuffers(1, &this->VBO);
glGenBuffers(1, &this->EBO);
glBindVertexArray(this->VAO);
// Load data into vertex buffers
glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(Vertex), &this->vertices[0], GL_STATIC_DRAW);
// Set the vertex attribute pointers
// Vertex Positions
glEnableVertexAttribArray(POSITION_LOCATION);
glVertexAttribPointer(POSITION_LOCATION, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)0);
// Vertex Normals
glEnableVertexAttribArray(NORMAL_LOCATION);
glVertexAttribPointer(NORMAL_LOCATION, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, Normal));
// Vertex Texture Coords
glEnableVertexAttribArray(TEX_COORD_LOCATION);
glVertexAttribPointer(TEX_COORD_LOCATION, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, TexCoords));
if (this->hasBones) {
glEnableVertexAttribArray(BONE_ID_LOCATION);
glVertexAttribIPointer(BONE_ID_LOCATION, 4, GL_INT, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, BoneIds));
glEnableVertexAttribArray(BONE_WEIGHT_LOCATION);
glVertexAttribPointer(BONE_WEIGHT_LOCATION, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, Weights));
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0], GL_STATIC_DRAW);
glBindVertexArray(0);
}
void PlayerMesh::setupUniformLoc() {
if (!shader->isInitilized()) {
cerr << "Shader not initialized" << endl;
exit(-1);
}
shader->bind();
modelLoc = glGetUniformLocation(shader->getPid(), "model");
viewLoc = glGetUniformLocation(shader->getPid(), "view");
projLoc = glGetUniformLocation(shader->getPid(), "projection");
hasTexLoc = glGetUniformLocation(shader->getPid(), "hasTexture");
hasBonesLoc = glGetUniformLocation(shader->getPid(), "hasBones");
if (this->hasBones) {
for (size_t i = 0; i < MAX_BONES; i++) {
string tmp = "bones[" + to_string(i) + "]";
boneLocs.push_back(glGetUniformLocation(shader->getPid(), tmp.c_str()));
}
}
ambient = glGetUniformLocation(shader->getPid(), "materialNoTex.ambient");
diffuse = glGetUniformLocation(shader->getPid(), "materialNoTex.diffuse");
specular = glGetUniformLocation(shader->getPid(), "materialNoTex.specular");
shininess = glGetUniformLocation(shader->getPid(), "materialNoTex.shininess");
shader->unbind();
}
|
#include <Arduino.h>
#define MAX_SIZE 16
// c character to encrypt, i lowest key value, j highest key value
uint8_t charEncrypt(int c, int i, int j){
uint8_t osec = j;
uint8_t sec = osec<<4;
uint8_t one_res = (sec | i);
uint8_t one_enc = one_res + c;
return one_enc;
}
uint8_t charDecrypt(int c, int i, int j) {
uint8_t osec = j;
uint8_t sec = osec<<4;
uint8_t one_res = (sec | i);
uint8_t one_enc = 0;
if (c > one_res){
one_enc = c - one_res;
} else {
one_enc = one_res - c;
}
return one_enc;
}
uint8_t * encrypt(char text[], uint8_t key[], uint8_t text_size, uint8_t key_size){
static uint8_t *buff;
buff = malloc(MAX_SIZE * sizeof(uint8_t));
uint8_t init = 0;
uint8_t key_pair [2];
for (uint8_t i = 0; i < text_size - 1; i++){
if(init > (key_size + 1)){ // 0 < 6
init = 0; // 0 -> reset init
}
uint8_t c = (int) text[i];
key_pair[0] = key[init];
key_pair[1] = key[init + 1];
init++;
uint8_t res = charEncrypt(c, key_pair[0], key_pair[1]);
buff[i + 1] = res;
}
return buff;
}
uint8_t * decrypt(uint8_t encrypted[], uint8_t key[], uint8_t text_size, uint8_t key_size){
static uint8_t *buff;
buff = malloc(MAX_SIZE * sizeof(uint8_t));
uint8_t init = 0;
uint8_t key_pair [2];
for (uint8_t i = 0; i < text_size - 1; i++){
if(init > (key_size + 1)){ // 0 < 6
init = 0; // 0 -> reset init
}
key_pair[0] = key[init];
key_pair[1] = key[init + 1];
init++;
uint8_t res = charDecrypt(encrypted[i + 1], key_pair[0], key_pair[1]);
//Serial.print(res);
//Serial.println();
buff[i] = res;
}
return buff;
}
void setup() {
Serial.begin(115200);
char text[] = "HELLO WORLD";
uint8_t key[] = {0x5, 0x2, 0x2, 0x8, 0x4, 0x6, 0x5};
uint8_t *buff_encrypt;
uint8_t *buff_decrypt;
buff_encrypt = encrypt(text, key, sizeof(text),sizeof(key));
Serial.println("Encrypting...");
for (uint8_t i = 0; i < sizeof(text) -1; i++){
Serial.print(*(buff_encrypt + i));
Serial.print(",");
}
Serial.println();
buff_decrypt = decrypt(buff_encrypt, key, sizeof(text), sizeof(key));
Serial.println("Decrypting...");
for (uint8_t j = 0; j < sizeof(text) - 1; j++){
Serial.print(*(buff_decrypt + j));
Serial.print(",");
}
Serial.println();
}
void loop() {
// put your main code here, to run repeatedly:
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <conio.h>
using namespace std;
bool MatchFirstChar(const string &str) //谓词函数
{ return 'S' == str[0];}
int main(){
const int VECTOR_SIZE=8;
string names[]={"She","Sells","Sea","Shells","by","the","Sea","Shores"};
//产生容纳字符串的向量容器对象
vector<string>NamesVect(names,names+VECTOR_SIZE);
//定义迭代器对象,[start,end)定义了一个左开右闭区间
vector<string>::iterator start,end;
start=NamesVect.begin();
end=NamesVect.end();
//利用迭代器在[start,end)区间遍历向量容器,输出容器元素
cout<<"NamesVect{";
for(vector<string>::iterator it=start;it !=end; it++)
cout<<*it<<" ";
cout<<"}\n"<<endl;
//调用count_if计数向量容器中使用MatchFirstChar);
int result = count_if(start,end,MatchFirstChar); //计算以's'开头的字符串
cout<<"个数="<<result<<endl;
getch();
return 0;
}
|
// Including necessary libraries
#include "Dice.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// Constructor
Dice::Dice() {
// Initializes totalRolls
container;
totalRolls = new int(0);
// Initializes value and valuePercentage
value = new int[6];
valuePercentage = new double[6];
for (int i = 0; i < 6; i++) {
value[i] = 0;
}
}
Dice::~Dice() {
// Delete pointers
delete container;
delete totalRolls;
delete[]value;
delete[]valuePercentage;
// setting pointers to NULL
container = NULL;
totalRolls = NULL;
value = NULL;
valuePercentage = NULL;
}
// Implementing all the methods
void Dice::rollDice(int* maxRoll, int* numOfArmies, const int numDiceChosen) {
int numDice = *numOfArmies;
if (*maxRoll == 3) { // attacker mode defender will never get here as we pass 2 as a parameter
if (numDice > 3)
numDice = 3;
else if (numDice == 3)
numDice = 2;
else if (numDice == 2)
numDice = 1;
}
if (*maxRoll == 2) { // defender mode
if (numDice >= 2)
numDice = 2;
else if (numDice == 1)
numDice = 1;
}
// Initializing the total roll
numOfRolls = new int(numDiceChosen);
*totalRolls += *numOfRolls;
// Initializing the container
container = new int[*numOfRolls];
// For loop that rolls the dice "numOfRolls" times
for (int i = 0; i < *numOfRolls; i++) {
container[i] = (rand() % NUM_OF_VALUES) + 1;
}
// Sorts the container array from highest to lowest
sortContainer();
showValues();
valueTracker();
percentageTracker();
//showPercentages();
cout << " " << endl;
}
// Sorting method
void Dice::sortContainer() {
// Temporary variable to do swapping
int temp;
// Sorting the container
for (int i = 0; i < *numOfRolls - 1; i++) {
for (int j = i + 1; j < *numOfRolls; j++) {
if (container[i] < container[j]) {
temp = container[i];
container[i] = container[j];
container[j] = temp;
}
}
}
}
// Shows how many times each value was rolled
void Dice::valueTracker() {
// For loop to increment the value that is rolled
for (int i = 0; i < *numOfRolls; i++) {
switch (container[i])
{
case 1:
value[0] = value[0] + 1;
break;
case 2: // code to be executed if n = 2;
value[1] = value[1] + 1;
break;
case 3:
value[2] = value[2] + 1;
break;
case 4: // code to be executed if n = 2;
value[3] = value[3] + 1;
break;
case 5:
value[4] = value[4] + 1;
break;
case 6:
value[5] = value[5] + 1;
break;
}
}
/*
// For loop that displays number of times each value was rolled
for(int i = 0; i < NUM_OF_VALUES; i++) {
cout << i+1;
cout << " has been rolled ";
cout << value[i];
cout << " times " << endl;
}
*/
}
// Tracks the percentage of the values rolled
void Dice::percentageTracker() {
// Calculates the percentage of each value rolled
for (int i = 0; i < NUM_OF_VALUES; i++) {
valuePercentage[i] = (value[i] / (double)*totalRolls) * 100;
}
}
// Displays the percentage of each value rolled
void Dice::showPercentages() {
for (int i = 0; i < NUM_OF_VALUES; i++) {
cout << "The percentage of ";
cout << i + 1;
cout << " rolled: ";
cout << valuePercentage[i] << endl;
}
}
// Shows the values rolled
void Dice::showValues() {
for (int i = 0; i < *numOfRolls; i++) {
cout << "The value are : ";
cout << container[i] << endl;
}
}
|
#ifdef _WIN32
#include <windows.h>
#include "../Core/VLogger.h"
struct STestAsset
{
int n = 123;
STestAsset()
{
printf("%s\n", __FUNCTION__);
}
~STestAsset()
{
printf("%s\n", __FUNCTION__);
}
void Print()
{
printf("%s %d\n", __FUNCTION__, n);
}
};
struct SGameObject
{
STestAsset* Asset = nullptr;
void Print()
{
Asset->Print();
}
};
void VCreateAssets()
{
}
void VUpdateGame()
{
STestAsset ass0;
SGameObject go0;
go0.Asset = &ass0;
SGameObject go1;
go0.Print();
go1.Print();
}
void VTest_Guard()
{
return;
__try
{
VUpdateGame();
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
printf("\nError Occurred\n");
system("pause");
}
}
#endif // _DEBUG
|
#include <iostream>
#include <vector>
using namespace std;
#include "solution.h"
int main() {
vector<int> chips1 = {1, 2, 3};
vector<int> chips2 = {2, 2, 2, 3, 3};
Solution sol;
cout << sol.minCostToMoveChips(chips1) << endl;
cout << sol.minCostToMoveChips(chips2) << endl;
return 0;
}
|
#include "Ship.hpp"
Ship::Ship( Type type, ResourceManager< Texture::ID, sf::Texture >& textureManager )
: m_type( type )
, m_sprite( textureManager.getResource( toTextureID( type ) ) )
, m_laserSystem( 25 )
, m_prevPosition( 0.0f, 0.0f )
, m_rect()
, m_health( 0 )
, m_alive( true )
{
sf::FloatRect bounds = m_sprite.getLocalBounds();
m_sprite.setOrigin( bounds.width / 2, bounds.height / 2 );
}
void Ship::updateCurrent( sf::Time dt, sf::View& view )
{
if ( m_type == Type::Player )
{
m_laserSystem.setEmitter( getPosition().x, getPosition().y - ( m_sprite.getTexture() -> getSize().y / 2 ) );
}
else if ( m_type == Type::Enemy )
{
m_laserSystem.setEmitter( getPosition().x, getPosition().y + ( m_sprite.getTexture() -> getSize().y / 2 ) );
}
m_laserSystem.update( dt, view );
m_prevPosition = getPosition();
move( m_velocity * dt.asSeconds() );
if ( getPosition().x <= 0 + ( m_sprite.getTexture() -> getSize().x / 2 ) )
{
setPosition( m_prevPosition );
}
if ( getPosition().x + ( m_sprite.getTexture() -> getSize().x / 2 ) > Util::V_Width )
{
setPosition( m_prevPosition );
}
if ( getPosition().y + ( m_sprite.getTexture() -> getSize().y / 2 ) > ( view.getCenter().y + ( Util::V_Height / 2 ) ) )
{
setPosition( m_prevPosition );
}
m_rect.left = getPosition().x - ( m_sprite.getTexture() -> getSize().x / 2 );
m_rect.top = getPosition().y - ( m_sprite.getTexture() -> getSize().y / 2 );
m_rect.width = m_sprite.getTexture() -> getSize().x;
m_rect.height = m_sprite.getTexture() -> getSize().y;
if ( m_type == Type::Enemy )
{
if ( getPosition().y > ( view.getCenter().y - ( Util::V_Height / 2 ) ) - ( this -> getSprite().getTextureRect().height / 2 ) &&
getPosition().y - this -> getSprite().getTexture() -> getSize().y / 2 < view.getCenter().y + Util::V_Height / 2 )
{
m_visible = true;
}
else
{
m_visible = false;
}
}
else if ( m_type == Type::Player )
{
m_visible = true;
}
}
void Ship::drawCurrent( sf::RenderTarget& target, sf::RenderStates states ) const
{
if ( m_type == Type::Player )
{
target.draw( m_sprite, states );
for ( int i = 0; i < m_laserSystem.getNumParticles(); i++ )
{
if ( m_laserSystem.getParticles()[ i ].isAlive() )
{
target.draw( m_laserSystem.getParticles()[ i ].getSprite() );
}
}
}
else if ( m_type == Type::Enemy && m_visible == true )
{
target.draw( m_sprite, states );
}
for ( int i = 0; i < m_laserSystem.getNumParticles(); i++ )
{
if ( m_laserSystem.getParticles()[ i ].isAlive() )
{
target.draw( m_laserSystem.getParticles()[ i ].getSprite() );
}
}
}
Texture::ID Ship::toTextureID( Type type )
{
switch ( type )
{
case Type::Player:
{
return Texture::Player;
}
break;
case Type::Enemy:
{
return Texture::Enemy;
}
break;
}
}
void Ship::fire( sf::Sound& sound )
{
float shootSpeed = -1000;
if ( m_type == Type::Enemy )
{
shootSpeed = 250;
}
for ( int i = 0; i < m_laserSystem.getNumParticles(); i++ )
{
if ( m_laserSystem.getParticles()[ i ].isAlive() == false )
{
m_laserSystem.addElapsed( m_laserSystem.getClock().restart() );
if ( m_laserSystem.getElapsed() >= m_laserSystem.getDelay() )
{
m_laserSystem.getParticles()[ i ].setAlive( true );
m_laserSystem.getParticles()[ i ].setVelocity( 0.0f, shootSpeed );
m_laserSystem.subElapsed( m_laserSystem.getElapsed() );
sound.play();
}
}
}
}
|
/***********************************************************************
created: 30/5/2013
author: Timotei Dolean
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifndef _Sample_Menu_Navigation_h_
#define _Sample_Menu_Navigation_h_
#include "Sample.h"
#include "NavigationStrategies.h"
class MenuNavigationSample : public Sample
{
public:
MenuNavigationSample();
bool initialise(CEGUI::GUIContext* gui_context) override;
void deinitialise() override;
private:
CEGUI::Window* d_root;
CEGUI::Window* d_logWidget1;
CEGUI::Window* d_logWidget2;
CEGUI::ListWidget* d_classesList;
MatrixNavigator* d_matrixWindowNavigator;
LinearNavigator* d_linearWindowNavigator;
void initialiseClasses(CEGUI::ListWidget* classes_listwidget);
bool handleSelectButtonClicked(const CEGUI::EventArgs& e);
bool handleNumberButtonClicked(const CEGUI::EventArgs& e);
bool handleTabSelectionChanged(const CEGUI::EventArgs& e);
};
#endif // end of guard _Sample_Menu_Navigation_h_
|
/*
* Localization.hpp
*
* Created on: 2018/12/28
* Author: 裕汰
*/
#ifndef LOCALIZATION_LOCALIZATION_HPP_
#define LOCALIZATION_LOCALIZATION_HPP_
#include <RazarIMU/MPU9250.hpp>
#include "CAN/CAN.hpp"
#include "encoder/RotaryEncoder.hpp"
#define Xencoder 0
#define Yencoder 1
class Localization //自己位置の情報が詰まったクラス can
{
protected:
float diameter=0.048;//接地エンコーダの直径
uint16_t pulse=2048;//エンコーダの1回転のパルス数
float ShiftY=0.094;
float ShiftX=0.094;
double XX = 0; //Present value(x axis)
double YY = 0; //Present value(y axis)
double theta = 0;
float initX=0.48;
float initY=0.48;
long count[2]={0,};
float point[2]={0,};
long b_count[2]={0,};
double ENCR_velocity =0.00; //velocity of the ENCR
double ENCL_velocity =0.00; //velocity of the ENCL
double robot_velocity = 0;
double robot_omega = 0;
const double pi=3.14159265358979323846264338;
public:
Gyro *gyro;
Encoder *enX,*enY;
virtual float GetX();
virtual float GetY();
virtual float GetYaw();
virtual void Setloca();
void SetDiamater(float d);
void SetPulse(unsigned short p);
void SetShiftX(float x);
void SetShiftY(float y);
void SetInitPos(float x,float y);
Localization(Gyro *g,Encoder *encoX,Encoder *encoY):gyro(g),enX(encoX),enY(encoY)
{
}
virtual void countintegral();//微小距離ベクトルの積分 絶対位置を出す
};
class Localization_2wd:public Localization
{
long kitaihensa=0;
float Toled=0.293;//タイヤ間の距離
float diameter=0.10200;
//angular velocity of the robot
float delta=0.005;
public:
using Localization::Localization;
virtual float GetX();
virtual float GetY();
virtual float GetYaw();
virtual void countintegral();
};
class LocalizationCAN //送信に特化させたクラス
{
CanBus *locacan;
Localization *loca;
unsigned char msg[8];
unsigned char msg2[4];
float diameter=0;
short pulse=0;
float ShiftY=0;
float ShiftX=0;
void UnitData(int start,int end,float *d,unsigned char *fifodata);
void UnitData(int start,int end, short *d,unsigned char *fifodata);
void Convfloat(int selct,float data);
unsigned long task=0;
int tx_led=0;
bool TXok=false;
float initX=0;
float initY=0;
public:
LocalizationCAN(CanBus *canbus,Localization *_loca):locacan(canbus),loca(_loca)
{
}
void Sendloca();
};
#endif /* LOCALIZATION_LOCALIZATION_HPP_ */
|
/*
Sample Battleship AI in C++
BattleshipAI.h
*/
#ifndef BATTLESHIP_AI
#define BATTLESHIP_AI
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include "GameBoard.h"
using namespace std;
class BattleshipAI
{
private:
//GameBoard op_field;
//GameBoard my_field;
enum State {
Config,
Idle,
Prep,
Search,
Engage
};
State state;
string channel;
string referee;
string nick;
string move();
public:
BattleshipAI();
//~BattleshipAI();
string handler(string input);
static vector<string> parse(string);
};
#include "BattleshipAI.cpp"
#endif
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const uint32_t MOD = 4294967291;
const uint32_t BASE = 53;
void print(vector<string> &t) {
for (const string &s : t) {
cout << s << " ";
}
cout << "\n";
}
class hashSet {
uint32_t cnt;
uint32_t sz;
vector<list<pair<string, unordered_set<string> > > > table;
vector<list<pair<string, unordered_set<string> > > > newTable;
public:
hashSet() {
sz = 10;
table.resize(sz);
cnt = 0;
}
uint32_t getHash(string s) {
uint32_t hash = 0;
for (char &i : s) {
hash = ((hash * BASE) % MOD + (uint32_t) i) % MOD;
}
return hash % sz;
}
void expand() {
if (cnt * 3 > ((uint32_t)sz * 4)) {
sz *= 2;
newTable.clear();
newTable.resize(sz);
for (const list<pair<string, unordered_set<string> > > &L : table) {
for (const pair<string, unordered_set<string>> &elem : L) {
uint32_t key = getHash(elem.first);
newTable[key].push_back(elem);
}
}
table.swap(newTable);
}
}
void insert(const string &x, string &y) {
expand();
int t = getHash(x);
for (auto &p : table[t]) {
if (p.first == x) {
p.second.insert(y);
return;
}
}
table[t].push_front({x, unordered_set<string>()});
table[t].begin()->second.insert(y);
cnt++;
}
void erase(const string &x) {
int t = getHash(x);
for (auto it = table[t].begin(); it != table[t].end(); it++) {
if ((*it).first == x) {
table[t].erase(it);
cnt--;
return;
}
}
}
void erasePair(const string &x, string &y) {
int t = getHash(x);
for (auto &p : table[t]) {
if (p.first == x) {
p.second.erase(y);
return;
}
}
}
void get(const string &x, vector<string> &v) {
int t = getHash(x);
for (auto &p : table[t]) {
if (p.first == x) {
for (const string &s : p.second)
v.push_back(s);
}
}
}
};
int main() {
// freopen("file.in", "r", stdin);
freopen("multimap.in", "r", stdin);
freopen("multimap.out", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
hashSet H;
string key, val;
string act, ans = "";
vector<string> curr;
while (cin >> act) {
if (act == "put") {
cin >> key >> val;
H.insert(key, val);
} else if (act == "delete") {
cin >> key >> val;
H.erasePair(key, val);
} else if (act == "deleteall") {
cin >> key;
H.erase(key);
} else if (act == "get") {
cin >> key;
curr.clear();
H.get(key, curr);
cout << curr.size() << " ";
print(curr);
}
}
cout << ans << endl;
return 0;
}
|
#include "Screens.hpp"
#define SCREEN_HEIGHT 240
#define SCREEN_WIDTH 320
Screens::Screens(QWidget * p)
{
parent = p;
const char * const vlc_args[] = {
"--extraintf=logger",
"--verbose=2",
"--no-audio"
};
screen[LEFT]=new QFrame(parent);
screen[RIGHT]=new QFrame(parent);
screenMixer = new QLabel(parent);
for(int pos = LEFT; pos<=RIGHT; ++pos) {
vlcInstance[pos] = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);
mediaPlayer[pos] = libvlc_media_player_new (vlcInstance[pos]);
}
screenMixer->setMinimumHeight(SCREEN_HEIGHT);
screenMixer->setMaximumHeight(SCREEN_HEIGHT);
screenMixer->setMinimumWidth(SCREEN_WIDTH);
screenMixer->setMaximumWidth(SCREEN_WIDTH);
screenMixer->resize(SCREEN_WIDTH, SCREEN_HEIGHT);
for(int pos = LEFT; pos<=RIGHT; ++pos) {
screen[pos]->setMinimumHeight(SCREEN_HEIGHT);
screen[pos]->setMaximumHeight(SCREEN_HEIGHT);
screen[pos]->setMinimumWidth(SCREEN_WIDTH);
screen[pos]->setMaximumWidth(SCREEN_WIDTH);
screen[pos]->resize(SCREEN_WIDTH, SCREEN_HEIGHT);
}
imageMixer = QImage(screen[LEFT]->size(), QImage::Format_ARGB32_Premultiplied);
painter = new QPainter(&imageMixer);
painter->setOpacity(0.5);
painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
}
void Screens::play(QString sourceLeft, QString sourceRight) {
QString source[2] = { sourceLeft, sourceRight };
for(int pos = LEFT; pos<=RIGHT; ++pos) {
media[pos] = libvlc_media_new_path(vlcInstance[pos], source[pos].toAscii());
libvlc_media_player_set_media (mediaPlayer[pos], media[pos]);
libvlc_media_player_set_xwindow (mediaPlayer[pos], screen[pos]->winId() );
libvlc_media_player_play (mediaPlayer[pos]);
}
}
void Screens::grabWindows(){
pixmap[LEFT] = QPixmap::grabWindow(screen[LEFT]->winId());
pixmap[RIGHT] = QPixmap::grabWindow(screen[RIGHT]->winId());
}
void Screens::mix(int value){
painter->drawImage(- value,0,pixmap[LEFT].toImage());
painter->drawImage( value,0,pixmap[RIGHT].toImage());
screenMixer->setPixmap(QPixmap::fromImage(imageMixer));
}
QLabel * Screens::getScreenMixerWidget(){
return screenMixer;
}
void Screens::resize(){
screenMixer->resize(screen[LEFT]->size());
}
QWidget * Screens::getScreenWidget(Positions pos){
return screen[pos];
}
Screens::~Screens()
{
painter->end();
delete(painter);
for(int pos = LEFT; pos<=RIGHT; ++pos) {
libvlc_media_player_stop (mediaPlayer[pos]);
libvlc_media_player_release (mediaPlayer[pos]);
libvlc_release (vlcInstance[pos]);
}
delete(screenMixer);
for(int pos = LEFT; pos<=RIGHT; ++pos) {
delete(screen[pos]);
}
}
|
#include "Global.h"
#include <QCoreApplication>
#include <QApplication>
#include <QFileInfo>
#include <QDir>
QString Global::Authority = "2";
QString Global::DisplayName = QString();
QString Global::Database = "bookdata";
QString Global::Hostname = "localhost";
QString Global::Username = "root";
QString Global::Passwd = "";
QString Global::PathImage = QString();
QString Global::PathMask = QString();
QString Global::PathResult = QString();
QString Global::ExtMask = QString();
QString Global::ExtResult = QString();
QString Global::NewName = QString();
QString Global::MoliId = QString();
QtAwesome* Global::Awesome = 0;
QColor Global::LabelledColor = QColor(0, 150, 0);
QColor Global::UnLabelledColor = QColor(125, 125, 125);
QSettings* Global::settings = 0;
bool Global::Init = false;
void Global::initialize()
{
if(Global::Init) return;
QCoreApplication* app = QApplication::instance();
QString strConfigFile = QFileInfo(app->applicationFilePath()).baseName() + ".ini";
if(!QFile::exists(strConfigFile))
{
qFatal("配置文件不存在:\r\n%s", qPrintable(strConfigFile));
}
Global::Awesome = new QtAwesome();
Global::Awesome->initFontAwesome();
Global::settings = new QSettings(strConfigFile, QSettings::IniFormat);
settings->setIniCodec("UTF8");
Global::Database = Global::settings->value("MYSQL/databasename", Global::Database).toString();
Global::Hostname = Global::settings->value("MYSQL/hostname", Global::Hostname).toString();
Global::Username = Global::settings->value("MYSQL/username", Global::Username).toString();
Global::Passwd = Global::settings->value("MYSQL/passwd", Global::Passwd).toString();
Global::PathImage = Global::settings->value("IMAGE/pathImage",Global::PathImage).toString();
Global::PathMask = Global::settings->value("IMAGE/pathMask", Global::PathMask).toString();
Global::PathResult = Global::settings->value("IMAGE/pathResult", Global::PathResult).toString();
QDir dirMask(Global::PathMask);
QDir dirResult(Global::PathResult);
if(!dirMask.exists()) dirMask.mkdir(Global::PathMask);
if(!dirResult.exists()) dirResult.mkdir(Global::PathResult);
Global::ExtMask = Global::settings->value("IMAGE/extMask", Global::ExtMask).toString();
Global::ExtResult = Global::settings->value("IMAGE/extResult", Global::ExtResult).toString();
Global::Init = true;
}
bool Global::createConnection(QSqlDatabase &db)
{
if(QSqlDatabase::contains("qt_sql_default_connection"))
db = QSqlDatabase::database("qt_sql_default_connection");
else
db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(Global::Hostname);
db.setDatabaseName(Global::Database);
db.setUserName(Global::Username);
db.setPassword(Global::Passwd);
if(!db.open())
{
return false;
}
return true;
}
|
// Binary Search Tree ADT
// Created by A. Student
// Modified by: Maksym Sagadin
#ifndef _BINARY_SEARCH_TREE
#define _BINARY_SEARCH_TREE
#include <iostream>
#include "BinaryTree.h"
template<class ItemType>
class BinarySearchTree : public BinaryTree<ItemType>
{
private:
// internal insert node: insert newNode in nodePtr subtree
BinaryNode<ItemType>* _insert(BinaryNode<ItemType>* nodePtr, BinaryNode<ItemType>* newNode, int compare(ItemType left, ItemType right));
// internal remove node: locate and delete target node under nodePtr subtree
BinaryNode<ItemType>* _remove(BinaryNode<ItemType>* nodePtr, const ItemType target, bool & success, int compare(ItemType left, ItemType right));
// delete target node from tree, called by internal remove node
BinaryNode<ItemType>* deleteNode(BinaryNode<ItemType>* targetNodePtr);
// remove the leftmost node in the left subtree of nodePtr
BinaryNode<ItemType>* removeLeftmostNode(BinaryNode<ItemType>* nodePtr, ItemType & successor);
// search for target node
BinaryNode<ItemType>* findNode(const ItemType & target, int compare(ItemType left, ItemType right)) const;
public:
// insert a node at the correct location
bool insert( ItemType & newEntry, int compare(ItemType left, ItemType right));
// remove a node if found
bool remove(ItemType & anEntry, int compare(ItemType left, ItemType right));
// find a target node
bool getEntry(const ItemType & target, ItemType & returnedItem, int compare(ItemType left, ItemType right)) const;
// find the smallest node
bool getSmallest(ItemType & smallest) const;
// find the largest node
bool getLargest(ItemType & largest) const;
};
///////////////////////// public function definitions ///////////////////////////
//Inserting items within a tree
template<class ItemType>
bool BinarySearchTree<ItemType>::insert( ItemType & newEntry, int compare(ItemType left, ItemType right)) {
BinaryNode<ItemType>* newNodePtr = new BinaryNode<ItemType>(newEntry);
this->rootPtr = _insert(this->rootPtr, newNodePtr, compare);
return true;
}
//Removing items within a tree
template<class ItemType>
bool BinarySearchTree<ItemType>::remove(ItemType & target, int compare(ItemType left, ItemType right)) {
bool isSuccessful = false;
this->rootPtr = _remove(this->rootPtr, target, isSuccessful, compare);
return isSuccessful;
}
//Searches for an item within a tree by passed value and updates a passed value
template<class ItemType>
bool BinarySearchTree<ItemType>::getEntry(const ItemType& target, ItemType & returnedItem, int compare(ItemType left, ItemType right)) const
{
BinaryNode<ItemType> *nodePtr = NULL;
nodePtr = findNode(target, compare);
if (nodePtr == NULL)
return false;
else {
returnedItem = nodePtr->getItem();
return true;
}
}
//Getting smallest node within a tree
template<class ItemType>
bool BinarySearchTree<ItemType>::getSmallest(ItemType & smallest) const
{
BinaryNode<ItemType>* nodePtr = findSmallest(this->rootPtr);
if (nodePtr == 0)
return false;
else
{
smallest = nodePtr->getItem();
return true;
}
}
//Getting largest node within a tree
template<class ItemType>
bool BinarySearchTree<ItemType>::getLargest(ItemType & largest) const
{
BinaryNode<ItemType>* nodePtr = findLargest(this->rootPtr);
if (nodePtr == 0)
return false;
else
{
largest = nodePtr->getItem();
return true;
}
}
//////////////////////////// private functions ////////////////////////////////////////////
//Implementation of the delete operation
template<class ItemType>
BinaryNode<ItemType>* BinarySearchTree<ItemType>::_insert(BinaryNode<ItemType>* nodePtr,
BinaryNode<ItemType>* newNodePtr, int compare(ItemType left, ItemType right))
{
if (nodePtr == 0)
{
newNodePtr->setLeftPtr(NULL);
newNodePtr->setRightPtr(NULL);
return newNodePtr;
}
if (compare(newNodePtr->getItem(), nodePtr->getItem()) == -1)
nodePtr->setLeftPtr(_insert(nodePtr->getLeftPtr(), newNodePtr, compare));
else
nodePtr->setRightPtr(_insert(nodePtr->getRightPtr(), newNodePtr, compare));
return nodePtr;
}
//Implementation of the remove operation
template<class ItemType>
BinaryNode<ItemType>* BinarySearchTree<ItemType>::_remove(BinaryNode<ItemType>* nodePtr, const ItemType target, bool & success, int compare(ItemType left, ItemType right)) {
if (nodePtr == 0) {
success = false;
return 0;
}
if (compare(nodePtr->getItem(), target) == -1)
nodePtr->setRightPtr(_remove(nodePtr->getRightPtr(), target, success, compare));
else if (compare(nodePtr->getItem(), target) == 1)
nodePtr->setLeftPtr(_remove(nodePtr->getLeftPtr(), target, success, compare));
else {
nodePtr = deleteNode(nodePtr);
success = true;
}
return nodePtr;
}
//Implementation of the delete operation
template<class ItemType>
BinaryNode<ItemType>* BinarySearchTree<ItemType>::deleteNode(BinaryNode<ItemType>* nodePtr)
{
if (nodePtr->isLeaf())
{
delete nodePtr;
nodePtr = 0;
return nodePtr;
}
else if (nodePtr->getLeftPtr() == 0)
{
BinaryNode<ItemType>* nodeToConnectPtr = nodePtr->getRightPtr();
delete nodePtr;
nodePtr = 0;
return nodeToConnectPtr;
}
else if (nodePtr->getRightPtr() == 0)
{
BinaryNode<ItemType>* nodeToConnectPtr = nodePtr->getLeftPtr();
delete nodePtr;
nodePtr = 0;
return nodeToConnectPtr;
}
else
{
ItemType newNodeValue;
nodePtr->setRightPtr(removeLeftmostNode(nodePtr->getRightPtr(), newNodeValue));
nodePtr->setItem(newNodeValue);
return nodePtr;
}
}
//Implementation to remove the left leaf
template<class ItemType>
BinaryNode<ItemType>* BinarySearchTree<ItemType>::removeLeftmostNode(BinaryNode<ItemType>* nodePtr,
ItemType & successor)
{
if (nodePtr->getLeftPtr() == 0)
{
successor = nodePtr->getItem();
return deleteNode(nodePtr);
}
else
{
nodePtr->setLeftPtr(removeLeftmostNode(nodePtr->getLeftPtr(), successor));
return nodePtr;
}
}
//Implementation of the search operation
template<class ItemType>
BinaryNode<ItemType>* BinarySearchTree<ItemType>::findNode(const ItemType &target, int compare(ItemType left, ItemType right)) const
{
BinaryNode<ItemType> *pCurr = this->rootPtr;
while (pCurr != 0) {
if (compare(pCurr->getItem(), target) == 0)
return pCurr;
if (compare(pCurr->getItem(), target) == 1)
pCurr = pCurr->getLeftPtr();
else
pCurr = pCurr->getRightPtr();
}
return 0;
}
#endif
|
#include <iostream>
using namespace std;
// Function that converts decimal to binary
void decToBinary(int n)
{
// Size of an integer is assumed to be 8 bits
for (int i = 7; i >= 0; i--) {
int k = n >> i;
if (k & 1)
cout << "1";
else
cout << "0";
}
}
// fahrenheit to celcius LUT generation
int main()
{
int lowerTemp = 0;
int higherTemp = 100;
int fahTemp = 0;
for(int i = lowerTemp; i <= higherTemp; i++){
// for fahrenheit
fahTemp = ((i * 9) / 5) + 32;
decToBinary(fahTemp);
cout << endl;
}
return 0;
}
|
#include<iostream>
#include<string>
using namespace std;
void func() {
string num1, num2;
while (cin >> num1 && cin >> num2) {
int sum = 0;
for (int i = 0;i < num1.length();i++) {
for (int j = 0;j < num2.length();j++) {
sum += (num1[i] - '0') * (num2[j] - '0');
}
}
cout << sum << endl;
}
}
int main() {
func();
return 0;
}
|
#pragma once
#include <iostream>
#include <string>
class Logger {
inline static void show(const std::string& msg) {
std::cout << msg << "\n";
}
public:
inline static void error(const std::string& msg) {
show("ERR: " + msg);
}
inline static void info(const std::string& msg) {
show("INF: " + msg);
}
inline static void debug(const std::string& msg) {
show("DBG: " + msg);
}
inline static void warning(const std::string& msg) {
show("WRN: " + msg);
}
};
|
#include "stdafx.h"
#include "Point.h"
int Point::size() const
{
return 2;
}
const double & Point::operator[](int index) const
{
if (index == 0) {
return m_x;
}
if (index == 1) {
return m_y;
}
}
const double & Point::distance(Point & other) const
{
auto d_x = std::pow((this->m_x - other.m_x), 2);
auto d_y = std::pow((this->m_y - other.m_y), 2);
return std::sqrt(d_x + d_y);
}
Point::~Point()
{
}
std::ostream & operator<<(std::ostream & os, const Point & point)
{
os << "(" << point[0] << "," << point[1] << ")";
return os;
}
|
#include"head.h"
int seqsearch(int data[], int length, int obj)
{
int i = 0;
while (i < length && data[i] != obj) i++; // 主要耗时在条件判断上。
i = (i < length) ? i : -1; // 如果没有发现待查元素,返回-1.
return i;
}
int seqsearch_2(int data[], int length, int obj)
{
int i = 0;
int* new_data = new int[length+1];
for (; i < length; i++) new_data[i] = data[i]; new_data[length] = obj; // 在数组末尾设置监视哨。
i = 0;
while (new_data[i] != obj) i++; // 减少判断运算。
i = (i < length) ? i : -1;
return i;
}
|
#include <bits/stdc++.h>
using namespace std;
struct Edge
{
int v, cost[2];
};
int N, M, source, des, shortest[2]; //source表示起点,des表示终点,shortest存储最短路径的长度(下标为0)和最快路径的时间(下标为1)
vector<Edge> graph[505]; //图的邻接表
int dis[505], past[505], num[505]; //存储到各点的最短距离、各点的父节点、还有一个辅助数组num,求最短路径时存储时间,求最快路径时存储当前路径上结点个数
bool visit[505]; //是否已访问
vector<int> path[2]; //下标为0存储最短路径,下标为1存储最快路径
void Dijkstra(int index)
{ //Dijkstra算法,index==0时表示求的是最短路径;index==1时表示求的是最快路径
while (!visit[des])
{ //还没有访问到终点
int v = -1, MIN = INT_MAX;
for (int i = 0; i < N; ++i) //求出目前距离最短的未访问结点
if (!visit[i] && MIN > dis[i])
{
MIN = dis[i];
v = i;
}
if (v == -1) //不是连通图,直接返回
return;
visit[v] = true; //结点v已访问
for (Edge &e : graph[v]) //遍历v能到达的结点
if (!visit[e.v] && dis[e.v] > dis[v] + e.cost[index])
{ //距离更短
dis[e.v] = dis[v] + e.cost[index]; //更新距离
past[e.v] = v; //更新父节点
if (index == 0) //求最短路径
num[e.v] = num[v] + e.cost[1]; //更新到达当前结点时间
else if (index == 1) //求最快路径
num[e.v] = num[v] + 1; //更新路径上结点个数
}
else if (dis[e.v] == dis[v] + e.cost[index]) //距离相等
if (index == 0 && num[e.v] > num[v] + e.cost[1])
{ //求最短路径且时间更短
past[e.v] = v; //更新父节点
num[e.v] = num[v] + e.cost[1]; //更新到达当前结点时间
}
else if (index == 1 && num[e.v] > num[v] + 1)
{ //求最快路径且路径上结点数更少
past[e.v] = v; //更新父节点
num[e.v] = num[v] + 1; //更新路径上结点个数
}
}
shortest[index] = dis[des]; //得出最短路径或最快路径的到达终点时的值
}
void DFS(int v, int index)
{ //DFS算法求出路径,index==0时表示求的是最短路径;index==1时表示求的是最快路径
if (v == source)
{ //到达起点
path[index].push_back(v); //将起点压入路径中
return; //返回
}
DFS(past[v], index); //递归遍历
path[index].push_back(v); //将当前点压入路径中
}
bool cmp()
{ //比较两个路径是否完全一致
if (path[0].size() != path[1].size())
return false;
for (int i = 0; i < path[0].size(); ++i)
if (path[0][i] != path[1][i])
return false;
return true;
}
void output(int index)
{ //输出路径
for (int i = 0; i < path[index].size(); ++i)
printf("%s%d", i > 0 ? " -> " : "", path[index][i]);
printf("\n");
}
int main()
{
scanf("%d%d", &N, &M);
while (M--)
{
int a, b, c, d, e;
scanf("%d%d%d%d%d", &a, &b, &c, &d, &e);
graph[a].push_back({b, {d, e}});
if (c == 0)
graph[b].push_back({a, {d, e}});
}
scanf("%d%d", &source, &des);
for (int i = 0; i < 2; ++i)
{ //用两次Dijkstra+DFS算法
fill(visit, visit + N, false);
fill(dis, dis + N, INT_MAX);
fill(num, num + N, INT_MAX);
dis[source] = 0;
num[source] = 0;
Dijkstra(i);
DFS(des, i);
}
if (cmp())
{
printf("Distance = %d; Time = %d: ", shortest[0], shortest[1]);
output(0);
}
else
{
printf("Distance = %d: ", shortest[0]);
output(0);
printf("Time = %d: ", shortest[1]);
output(1);
}
return 0;
}
|
#ifndef _TNA_ENGINE_VIEWPORT_H_
#define _TNA_ENGINE_VIEWPORT_H_
#include <furious/components.h>
#include "../math/vector.h"
namespace tna
{
struct viewport_t
{
FURIOUS_COMPONENT(viewport_t);
uint32_t m_width = 900;
uint32_t m_height = 1440;
float m_near = 0.1f;
float m_far = 1000.0f;
float m_field = 60.0f;
};
} /* tna */
#endif /* ifndef _TNA_FRUSTRUM_H_ */
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_INT = std::numeric_limits<int>::max();
const int MIN_INT = std::numeric_limits<int>::min();
const int INF = 1000000000;
const int NEG_INF = -1000000000;
#define max(a,b)(a>b?a:b)
#define min(a,b)(a<b?a:b)
#define MEM(arr,val)memset(arr,val, sizeof arr)
#define PI acos(0)*2.0
#define eps 1.0e-9
#define are_equal(a,b)fabs(a-b)<eps
#define LS(b)(b& (-b)) // Least significant bit
#define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians
typedef long long ll;
typedef pair<int,int> ii;
typedef pair<int,char> ic;
typedef pair<long,char> lc;
typedef vector<int> vi;
typedef vector<ii> vii;
int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);}
int lcm(int a,int b){return a*(b/gcd(a,b));}
string line;
int n;
int find(){
for (int i = 0; i < n; i++){
int a = line[i]-'0';
if (a % 8 == 0)
return a;
for (int j = i+1; j < n; j++){
int b = line[j]-'0';
if (b % 8 == 0)
return b;
int num = a * 10 + b;
if (num % 8 == 0)
return num;
for (int k = j+1; k < n; k++){
int c = line[k]-'0';
int num = a * 100 + b * 10 + c;
if (num % 8 == 0)
return num;
num = a * 10 + c;
if (num % 8 == 0)
return num;
num = b * 10 + c;
if (num % 8 == 0)
return num;
num = c;
if (num % 8 == 0)
return num;
}
}
}
return -1;
}
int main(){
getline(cin, line);
n = line.size();
int ans = find();
if (ans == -1)
cout << "NO" << endl;
else cout << "YES\n" << ans << endl;
return 0;
}
|
class Solution {
public:
int hammingDistance(int x, int y) { 布赖恩·克尼根算法,简而言之就是:一个数和这个数减1进行相与,结果就是消去最右边的1.这样一步步消去,看能消几次,代表有几个1.
int distance = 0;
int res = x ^ y; // 先进行异或,得到不同位置为1的数
while (res) { // 计算1的个数,用算法
res &= (res - 1);
distance++;
}
return distance;
}
};
// reference https://leetcode-cn.com/problems/hamming-distance/solution/yi-ming-ju-chi-by-leetcode/
|
#include "_aimbot.h"
cAimbot g_Aimbot;
Vector cAimbot::vCalcBoneOffset( int iIndex )
{
int boneTarger = 0;
float screenDist = 1000.f;
Vector vBoneOrigin , vBoneScreen , vF , vR , vU , vOut;
vOut = Vector( 0 , 0 , 0 );
AngleVectors( g_Player[iIndex].EyeAngles , vF , vR , vU );
IClientEntity* Ent = g_Player[iIndex].pEntity;
if ( !g_Player[iIndex].bAlive )
return vOut;
int Bone = cvar.weapon_settings[cvar.wpn].aim_bone;
if ( cvar.weapon_settings[cvar.wpn].aim_silent && g_Local.iShotsFired < 1 )
{
GetBonePosition( Ent , vBoneOrigin , 6 );
vOut = vBoneOrigin + vF + vR + vU;
}
else
{
if ( Bone >= 1 && Bone <= 6 && cvar.weapon_settings[cvar.wpn].aim_smart <= 0 )
{
GetBonePosition( Ent , vBoneOrigin , Bone );
vOut = vBoneOrigin + vF + vR + vU;
}
else if ( cvar.weapon_settings[cvar.wpn].aim_smart )
{
Vector vBoneArray[7];
for ( int i = 1; i <= 6; i++ )
{
if ( GetBonePosition( Ent , vBoneOrigin , i ) && WorldToScreen( vBoneOrigin , vBoneScreen ) )
{
vBoneArray[i] = vBoneOrigin;
Vector vDest;
vDest.x = float( g_Screen.iWidth / 2 );
vDest.y = float( g_Screen.iHeight / 2 );
float fDist = CalcDistPlayerScreen( vDest.AsVector2D() , vBoneScreen.AsVector2D() );
if ( fDist < screenDist )
{
screenDist = fDist;
boneTarger = i;
}
}
else
{
vBoneArray[i] = Vector( 0 , 0 , 0 );
}
}
if ( boneTarger && vBoneArray[boneTarger].IsValid() )
vOut = vBoneArray[boneTarger] + vF + vR + vU;
}
}
return vOut;
}
int cAimbot::GetPlayerFov( int iIndex )
{
int iFovVal = 0;
if ( cvar.weapon_settings[cvar.wpn].aim_silent && g_Local.iShotsFired < 1 )
iFovVal = cvar.weapon_settings[cvar.wpn].aim_silent_fov;
else
iFovVal = cvar.weapon_settings[cvar.wpn].aim_fov;
int base_fov = pow( 60 + iFovVal , 2 ) * 90;
int iFov = (int)( base_fov / ( g_Player[iIndex].fDistance * g_Local.iFOV ) );
return iFov;
}
bool cAimbot::CheckFov( Vector vScreen , int iFov )
{
Vector vDest;
vDest.x = float( g_Screen.iWidth / 2 );
vDest.y = float( g_Screen.iHeight / 2 );
float fScrPos[2] =
{
nt_fabs( vDest.x - vScreen.x ),
nt_fabs( vDest.y - vScreen.y )
};
return ( fScrPos[0] <= (float)iFov && fScrPos[1] <= (float)iFov );
}
void cAimbot::AngleNormalize( float* angles )
{
if( angles[0] > 89.0f && angles[0] <= 180.0f )
angles[0] = 89.0f;
if( angles[0] > 180.f )
angles[0] -= 360.f;
if( angles[0] < -89.0f )
angles[0] = -89.0f;
if( angles[1] > 180.f )
angles[1] -= 360.f;
if( angles[1] < -180.f )
angles[1] += 360.f;
if( angles[2] != 0.0f )
angles[2] = 0.0f;
}
void cAimbot::SmoothAimAngles( Vector MyViewAngles , Vector AimAngles , Vector &OutAngles , float Smoothing )
{
VectorSubtract( AimAngles , MyViewAngles , OutAngles );
AngleNormalize( OutAngles.Base() );
OutAngles.x = OutAngles.x / Smoothing + MyViewAngles.x;
OutAngles.y = OutAngles.y / Smoothing + MyViewAngles.y;
AngleNormalize( OutAngles.Base() );
}
void cAimbot::UpdateTarget()
{
float squareDist = 9999.9f;
float center_screen[2];
center_screen[0] = g_Screen.iWidth / 2;
center_screen[1] = g_Screen.iHeight / 2;
for( int i = 0; i < 32; i++ )
{
if( g_Local.iIndex == g_Player[i].iIndex || !g_Local.bAlive || !g_Player[i].bVisible || !g_Player[i].pEntity )
{
continue;
}
if( !g_Player[i].bAlive || g_Player[i].iTeam == g_Local.iTeam || !g_Player[i].vAimOrigin.IsValid() || !g_Player[i].bAimFov )
{
continue;
}
Vector vScreenPlayer;
if( WorldToScreen( g_Player[i].vAimOrigin , vScreenPlayer ) )
{
float screen_dist = CalcDistPlayerScreen( center_screen , vScreenPlayer.AsVector2D() );
if( screen_dist < squareDist )
{
squareDist = screen_dist;
iTargetID = i;
}
}
}
}
void cAimbot::AimSet( CUserCmd* cmd , Vector vSmoothAngles )
{
if ( !dwShotTime )
dwShotTime = GetTickCount();
cmd->viewangles = vSmoothAngles;
if ( cvar.weapon_settings[cvar.wpn].aim_delay )
{
if ( dwShotTime + cvar.weapon_settings[cvar.wpn].aim_delay >= GetTickCount() )
{
cmd->buttons &= ~IN_ATTACK;
}
}
}
void cAimbot::AimUpd( CUserCmd* cmd )
{
QAngle qAimAngles;
Vector vAimAngles , vSmoothAngles;
if ( !g_Player[iTargetID].vAimOrigin.IsValid() )
return;
if ( !g_Player[iTargetID].vOldOrigin.IsValid() && cvar.weapon_settings[cvar.wpn].aim_smart && bAimType == 2 && !( cmd->buttons & IN_ATTACK ) )
{
g_Player[iTargetID].vOldOrigin = g_Player[iTargetID].vAimOrigin;
}
if ( cvar.weapon_settings[cvar.wpn].aim_smart && !cvar.weapon_settings[cvar.wpn].aim_silent )
{
if ( g_Player[iTargetID].vOldOrigin.IsValid() && bAimType == 2 )
{
VectorAnglesNew( ( g_Player[iTargetID].vOldOrigin - g_Local.vEyeOrigin ).Base() , qAimAngles.Base() );
}
else
{
VectorAnglesNew( ( g_Player[iTargetID].vAimOrigin - g_Local.vEyeOrigin ).Base() , qAimAngles.Base() );
}
}
else
{
VectorAnglesNew( ( g_Player[iTargetID].vAimOrigin - g_Local.vEyeOrigin ).Base() , qAimAngles.Base() );
}
if ( ( cvar.weapon_settings[cvar.wpn].aim_rcsx || cvar.weapon_settings[cvar.wpn].aim_rcsy ) && g_Local.iShotsFired > 0 )
{
Vector vAimPunch = g_Local.pEntity->GetAimPunch();
if ( cvar.weapon_settings[cvar.wpn].aim_rcsx )
qAimAngles.x -= vAimPunch.x * ( cvar.weapon_settings[cvar.wpn].aim_rcsx * 0.2 );
if ( cvar.weapon_settings[cvar.wpn].aim_rcsy )
qAimAngles.y -= vAimPunch.y * ( cvar.weapon_settings[cvar.wpn].aim_rcsy * 0.2 );
}
vAimAngles.x = qAimAngles.x;
vAimAngles.y = qAimAngles.y;
AngleNormalize( vAimAngles.Base() );
if ( cvar.weapon_settings[cvar.wpn].aim_smooth && !cvar.weapon_settings[cvar.wpn].aim_silent )
SmoothAimAngles( cmd->viewangles , vAimAngles , vSmoothAngles , cvar.weapon_settings[cvar.wpn].aim_smooth );
else
vSmoothAngles = vAimAngles;
AngleNormalize( vSmoothAngles.Base() );
AimSet( cmd , vSmoothAngles );
}
void cAimbot::Update( CUserCmd* cmd )
{
bAttack = ( cmd->buttons & IN_ATTACK );
if ( !bAttack )
{
dwShotTime = 0;
iTargetID = 0;
}
UpdateTarget();
}
void cAimbot::Aimbot( CUserCmd* cmd )
{
Update( cmd );
bAimType = 0;
bAimEnable = true;
if ( g_Local.weapon.type == WEAPON_TYPE_SHOTGUN )
bAimType = 1; // mouse1 + fov
else if ( g_Local.weapon.type == WEAPON_TYPE_PISTOL || g_Local.weapon.type == WEAPON_TYPE_SNIPER ) // fov + mouse1
{
bAimType = 2;
if ( g_Local.iShotsFired == 1 )
bAimEnable = false;
}
if ( iTargetID && bAimType && g_Local.iClip1 && bAimEnable )
{
switch ( bAimType )
{
case 1:
if ( bAttack && g_Player[iTargetID].bAimFov )
bAimAttack2 = true;
else
bAimAttack2 = false;
break;
case 2:
if ( g_Player[iTargetID].bAimFov && !bAttack )
bAimAttack1 = true;
else if ( !g_Player[iTargetID].bAimFov && !bAttack )
bAimAttack1 = false;
else if ( !g_Player[iTargetID].bAimFov && bAttack )
bAimAttack1 = false;
if ( bAimAttack1 && g_Player[iTargetID].bAimFov )
bAimAttack2 = true;
else
bAimAttack2 = false;
break;
default:
bAimAttack1 = false;
bAimAttack2 = false;
break;
}
if ( bAimAttack2 && bAttack )
{
AimUpd( cmd );
}
}
}
|
#ifndef LTUI_DATA_H
#define LTUI_DATA_H
#include "../src/ledger_entry_file_repository.hpp"
#endif
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.UI.Xaml.Resources.1.h"
WINRT_EXPORT namespace winrt {
namespace Windows::UI::Xaml::Resources {
struct ICustomXamlResourceLoader :
Windows::Foundation::IInspectable,
impl::consume<ICustomXamlResourceLoader>
{
ICustomXamlResourceLoader(std::nullptr_t = nullptr) noexcept {}
};
struct ICustomXamlResourceLoaderFactory :
Windows::Foundation::IInspectable,
impl::consume<ICustomXamlResourceLoaderFactory>
{
ICustomXamlResourceLoaderFactory(std::nullptr_t = nullptr) noexcept {}
};
struct ICustomXamlResourceLoaderOverrides :
Windows::Foundation::IInspectable,
impl::consume<ICustomXamlResourceLoaderOverrides>
{
ICustomXamlResourceLoaderOverrides(std::nullptr_t = nullptr) noexcept {}
};
struct ICustomXamlResourceLoaderStatics :
Windows::Foundation::IInspectable,
impl::consume<ICustomXamlResourceLoaderStatics>
{
ICustomXamlResourceLoaderStatics(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
#include "IndexedFaceSet.hpp"
#include <cassert>
#include <iostream>
// VRML'97
//
// IndexedFaceSet {
// eventIn MFInt32 set_colorIndex
// eventIn MFInt32 set_coordIndex
// eventIn MFInt32 set_normalIndex
// eventIn MFInt32 set_texCoordIndex
// exposedField SFNode color NULL
// exposedField SFNode coord NULL
// exposedField SFNode normal NULL
// exposedField SFNode texCoord NULL
// field SFBool ccw TRUE
// field MFInt32 colorIndex [] # [-1,)
// field SFBool colorPerVertex TRUE
// field SFBool convex TRUE
// field MFInt32 coordIndex [] # [-1,)
// field SFFloat creaseAngle 0 # [ 0,)
// field MFInt32 normalIndex [] # [-1,)
// field SFBool normalPerVertex TRUE
// field SFBool solid TRUE
// field MFInt32 texCoordIndex [] # [-1,)
// }
// TODO ...
// Refactor your IfsViewer code
IndexedFaceSet::IndexedFaceSet() {
/* remember to properly initialize all the class variables which do
not have a default constructor */
_ccw=true;
_colorPerVertex=true;
_convex=true;
_creaseAngle=0;
_normalPerVertex=true;
_solid=true;
}
IndexedFaceSet::~IndexedFaceSet() {
}
void IndexedFaceSet::clear() {
_ccw=true;
_colorPerVertex=true;
_convex=true;
_creaseAngle=0;
_normalPerVertex=true;
_solid=true;
_coord.clear();
_coordIndex.clear();
_normal.clear();
_normalIndex.clear();
_color.clear();
_colorIndex.clear();
_texCoord.clear();
_texCoordIndex.clear();
}
bool& IndexedFaceSet::getCcw() {return _ccw;}
bool& IndexedFaceSet::getConvex() {return _convex;}
float& IndexedFaceSet::getCreaseangle() {return _creaseAngle;}
bool& IndexedFaceSet::getSolid() {return _solid;}
bool& IndexedFaceSet::getNormalPerVertex() {return _normalPerVertex;}
bool& IndexedFaceSet::getColorPerVertex() {return _colorPerVertex;}
vector<float>& IndexedFaceSet::getCoord() { return _coord; }
vector<int>& IndexedFaceSet::getCoordIndex() { return _coordIndex;}
vector<float>& IndexedFaceSet::getNormal() {return _normal;}
vector<int>& IndexedFaceSet::getNormalIndex() {return _normalIndex;}
vector<float>& IndexedFaceSet::getColor() {return _color;}
vector<int>& IndexedFaceSet::getColorIndex() {return _colorIndex;}
vector<float>& IndexedFaceSet::getTexCoord() {return _texCoord;}
vector<int>& IndexedFaceSet::getTexCoordIndex() {return _texCoordIndex;}
int IndexedFaceSet::getNumberOfFaces() {
int count=0;
for (int i=0; i<_coordIndex.size(); i++) {
if (_coordIndex.at(i)==-1) {
count++;
}
}
cout << "Faces -1 count for coord index is: " << count << endl;
return count;
}
int IndexedFaceSet::getNumberOfCorners() {
/*int count=0;
for (int i=0; i<_texCoordIndex.size(); i++) {
if (_texCoordIndex.at(i)==-1) {
count++;
}
}
cout << "Corners -1 count for texcoord index is: " << count << endl;
return count;
*/
}
int IndexedFaceSet::getNumberOfCoord() {return _coord.size()/3;}
int IndexedFaceSet::getNumberOfNormal() {return _normal.size()/3;}
int IndexedFaceSet::getNumberOfColor() {return _color.size();}
int IndexedFaceSet::getNumberOfTexCoord() {return _texCoord.size()/3;}
void IndexedFaceSet::setNormalPerVertex(bool value) {_normalPerVertex=value;}
void IndexedFaceSet::setColorPerVertex(bool value) {_colorPerVertex=value;}
void IndexedFaceSet::removeTexCoord() {_texCoord.clear();}
// TODO
IndexedFaceSet::Binding IndexedFaceSet::getNormalBinding() {
if(_normal.size()==0) {
// NO_NORMALS
return PB_NONE;
}
else if(_normalPerVertex==false) {
if(_normalIndex.size()>0) {
//NORMAL_PER_FACE_INDEXED;
return PB_PER_FACE_INDEXED;
assert(_normalIndex.size()==getNumberOfFaces());
}
else {
//NORMAL_PER_FACE;
return PB_PER_FACE;
assert(_normal.size()/3==getNumberOfFaces());
}
}
else { // if(normalPerVertex==TRUE) {
if(_normalIndex.size()>0) {
//NORMAL_PER_CORNER;
return PB_PER_CORNER;
assert(_normalIndex.size()==_coordIndex.size());
}
else {
//NORMAL_PER_VERTEX;
return PB_PER_VERTEX;
assert(_normal.size()/3==_coord.size()/3);
}
}
return PB_NONE;
}
IndexedFaceSet::Binding IndexedFaceSet::getCoordBinding() {
if(_coord.size()==0) {
// NO_NORMALS
return PB_NONE;
}
else if(_normalPerVertex==false) {
if(_normalIndex.size()>0) {
//NORMAL_PER_FACE_INDEXED;
return PB_PER_FACE_INDEXED;
assert(_normalIndex.size()==getNumberOfFaces());
}
else {
//NORMAL_PER_FACE;
return PB_PER_FACE;
assert(_normal.size()/3==getNumberOfFaces());
}
}
else { // if(normalPerVertex==TRUE) {
if(_coordIndex.size()>0) {
//Coord_PER_CORNER;
return PB_PER_CORNER;
assert(_normalIndex.size()==_coordIndex.size());
}
else {
//NORMAL_PER_VERTEX;
return PB_PER_VERTEX;
assert(_normal.size()/3==_coord.size()/3);
}
}
return PB_NONE;
}
// TODO
IndexedFaceSet::Binding IndexedFaceSet::getColorBinding() {
if(_color.size()==0){
return PB_NONE;
}
else if(_colorPerVertex==false) {
if(_colorIndex.size()>0) {
return PB_PER_FACE_INDEXED;
assert(_colorIndex.size()==getNumberOfFaces());
}
else {
return PB_PER_FACE;
assert(_color.size()/3==getNumberOfFaces());
}
}
else { // if(colorPerVertex==TRUE) {
if(_colorIndex.size()>0) {
return PB_PER_CORNER;
assert(_colorIndex.size()==_coordIndex.size());
}
else {
return PB_PER_VERTEX;
assert(_color.size()/3==_coord.size()/3);
}
}
return PB_NONE;
}
// TODO
IndexedFaceSet::Binding IndexedFaceSet::getTexCoordBinding() {
if(_texCoord.size()==0) {
return PB_NONE;
}
else if(_texCoordIndex.size()>0) {
return PB_PER_CORNER;
assert(_texCoordIndex.size()==_coordIndex.size());
}
else {
return PB_PER_VERTEX;
assert(_texCoord.size()/3==_coord.size()/3);
}
return PB_NONE;
}
|
#include "include/ray.h"
#include "include/plane.h"
#include "include/tuple.h"
#include "include/transform.h"
#include "gtest/gtest.h"
class PlaneFixture : public ::testing::Test {
protected:
virtual void SetUp()
{
ray = new raytracer::Ray();
xs = new std::vector<raytracer::Intersection>();
transformation = new raytracer::Transform();
translate = new raytracer::Transform();
rotate = new raytracer::Transform();
scale = new raytracer::Transform();
normal = new raytracer::Tuple();
n1 = new raytracer::Tuple();
n2 = new raytracer::Tuple();
n3 = new raytracer::Tuple();
material = new raytracer::Material();
}
virtual void TearDown() {
delete ray;
delete xs;
delete transformation;
delete translate;
delete rotate;
delete scale;
delete normal;
delete n1;
delete n2;
delete n3;
delete material;
}
raytracer::Ray * ray;
std::shared_ptr<raytracer::Shape> plane = std::make_shared<raytracer::Plane>();
std::vector<raytracer::Intersection> * xs;
raytracer::Transform * transformation;
raytracer::Transform * translate;
raytracer::Transform * rotate;
raytracer::Transform * scale;
raytracer::Tuple * normal;
raytracer::Tuple * n1;
raytracer::Tuple * n2;
raytracer::Tuple * n3;
raytracer::Material * material;
};
TEST_F(PlaneFixture, NormalPlaneIsConstantEverywhere) {
* n1 = plane->getNormal(raytracer::createPoint(0, 0, 0));
* n2 = plane->getNormal(raytracer::createPoint(10, 0, -10));
* n3 = plane->getNormal(raytracer::createPoint(-5, 0, 150));
EXPECT_EQ(* n1, raytracer::createVector(0, 1, 0));
EXPECT_EQ(* n2, raytracer::createVector(0, 1, 0));
ASSERT_EQ(* n3, raytracer::createVector(0, 1, 0));
}
TEST_F(PlaneFixture, IntersectRayParallelToPlane) {
* ray = raytracer::Ray(raytracer::createPoint(0, 10, 0), raytracer::createVector(0, 0, 1));
plane->intersect(* ray, * xs);
ASSERT_EQ(xs->size(), 0);
}
TEST_F(PlaneFixture, IntersectRayCoplanar) {
* ray = raytracer::Ray(raytracer::createPoint(0, 0, 0), raytracer::createVector(0, 0, 1));
plane->intersect(* ray, * xs);
ASSERT_EQ(xs->size(), 0);
}
TEST_F(PlaneFixture, RayIntersectingPlaneFromAbove) {
* ray = raytracer::Ray(raytracer::createPoint(0, 1, 0), raytracer::createVector(0, -1, 0));
plane->intersect(* ray, * xs);
EXPECT_EQ(xs->size(),1);
EXPECT_EQ(xs[0][0].getDistance(), 1);
ASSERT_EQ(xs[0][0].getObject(), plane);
}
TEST_F(PlaneFixture, RayIntersectingPlaneFromBelow) {
* ray = raytracer::Ray(raytracer::createPoint(0, -1, 0), raytracer::createVector(0, 1, 0));
plane->intersect(* ray, * xs);
EXPECT_EQ(xs->size(),1);
EXPECT_EQ(xs[0][0].getDistance(), 1);
ASSERT_EQ(xs[0][0].getObject(), plane);
}
|
#include <iostream>
#include <utility>
int main()
{
std::pair<char, int> pair{ 'A', 123 };
std::cout << pair.first << '\n' << pair.second << '\n' << std::get<0>(pair) << '\n' << std::get<1>(pair) << '\n';
return 0;
}
|
// Created by yuanzhongji on 2013/08
#ifndef _TIP_DIALOG_H__
#define _TIP_DIALOG_H__
#include "cocos2d.h"
#include "LBLibraryBase.h"
#include "LBModalDialogLayer.h"
#include "WJLayerJson1x.h"
using namespace cocos2d;
using namespace std;
class TipDialog;
typedef std::function<void (TipDialog *dialog)> TipClickCallback;
class TipDialog : public LBModalDialog
{
private:
TipClickCallback m_okSelector;
TipClickCallback m_closeSelector;
void onDelayPushCallBackIntoStack();
protected:
bool m_adsIsVisible;
virtual void initButtonEvent();
virtual void onClickClose(Node *node, WJTouchEvent *event);
virtual void onClickOkButton(Node *node, WJTouchEvent *event);
void doEventClickClose();
void doEventClickOk();
void closeMySelf(WJSprite *sprite);
public:
CC_SYNTHESIZE(WJLayerJson*, m_layerJson, LayerJson);
public:
TipDialog();
static TipDialog* create(const char * jsonFile);
virtual bool init(const char * jsonFile);
virtual bool initFromJsonFile(const char *jsonFileName);
virtual void onEnterTransitionDidFinish();
virtual void onEnter();
// 关闭后的回调
void setOnCloseCallBack(const TipClickCallback &selector );
// 点击ok后的回调
void setOnOkCallBack(const TipClickCallback &selector );
};
#endif // _TIP_DIALOG_H__
|
// This file has been generated by Py++.
#ifndef NamedAreaIterator_hpp__pyplusplus_wrapper
#define NamedAreaIterator_hpp__pyplusplus_wrapper
void register_NamedAreaIterator_class();
#endif//NamedAreaIterator_hpp__pyplusplus_wrapper
|
/*=========================================================================
Program: ShapeWorks: Particle-based Shape Correspondence & Visualization
Module: $RCSfile: CS6350.h,v $
Date: $Date: 2014/03/24 01:17:40 $
Version: $Revision: 1.2 $
Author: $Author: shireen $
Copyright (c) 2009 Scientific Computing and Imaging Institute.
See ShapeWorksLicense.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __utils_h
#define __utils_h
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <sstream> // std::istringstream
#include <itkMath.h>
#include <cmath>
#include <algorithm> // std::sort
#define _USE_MATH_DEFINES
#include <math.h>
#include <vector>
namespace utils
{
#define twopi_inv 0.5/M_PI
#define twopi 2.0*M_PI
#define RANDU ((double) rand()/RAND_MAX)
#define RANDN2(mu, sigma) (mu + (rand()%2 ? -1.0 : 1.0)*sigma*pow(-log(0.99999*RANDU), 0.5))
#define RANDN RANDN2(0, 1.0)
std::string num2str(int num)
{
std::string Result; // string which will contain the result
std::ostringstream convert; // stream used for the conversion
convert << num; // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str(); // set 'Result' to the contents of the stream
return Result;
}
std::string num2str(float num)
{
std::string Result; // string which will contain the result
std::ostringstream convert; // stream used for the conversion
convert << num; // insert the textual representation of 'Number' in the characters in the stream
Result = convert.str(); // set 'Result' to the contents of the stream
return Result;
}
// ------------------- string manipulation ------------------------------------
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
struct MatchPathSeparator
{
bool operator()( char ch ) const
{
return ch == '\\' || ch == '/';
}
};
#else
struct MatchPathSeparator
{
bool operator()( char ch ) const
{
return ch == '/';
}
};
#endif
std::string removeExtension( std::string const& filename )
{
std::string::const_reverse_iterator
pivot
= std::find( filename.rbegin(), filename.rend(), '.' );
return pivot == filename.rend()
? filename
: std::string( filename.begin(), pivot.base() - 1 );
}
std::string getPath( std::string const& filename )
{
std::string::const_reverse_iterator
pivot
= std::find( filename.rbegin(), filename.rend(), '/' );
return pivot == filename.rend()
? filename
: std::string( filename.begin(), pivot.base() - 1 );
}
std::string getFilename( std::string const& pathname )
{
return std::string(
std::find_if( pathname.rbegin(), pathname.rend(),
MatchPathSeparator() ).base(),
pathname.end() );
}
// ------------------- coordinates transformations -----------------------------
void spherical2cartesian(const double inPoint[3], double outPoint[3])
{
double r = inPoint[0];
double sinphi = sin(inPoint[1]);
double cosphi = cos(inPoint[1]);
double sintheta = sin(inPoint[2]);
double costheta = cos(inPoint[2]);
outPoint[0] = r*sinphi*costheta;
outPoint[1] = r*sinphi*sintheta;
outPoint[2] = r*cosphi;
}
void cartesian2spherical(const double inPoint[3], double outPoint[3])
{
double x = inPoint[0];
double y = inPoint[1];
double z = inPoint[2];
double RR = x*x + y*y;
double r = sqrt(RR + z*z);
outPoint[0] = r;
if (r == 0)
outPoint[1] = 0;
else
outPoint[1] = acos(z/r);
if (RR == 0)
outPoint[2] = 0;
else
{
// Change range to [0, 2*Pi], otherwise the same as atan2(y, x)
outPoint[2] = double(itk::Math::pi) + atan2(-y, -x);
}
}
/**
* Given a set of theta measurements, pick the "average" (approximately).
*
* More formally, given a set of orientations, we wish to identify a
* "reference theta" such that the sum of the squared differences
* between each theta and the reference theta is minimized. This can
* be visualized: each theta (including the reference theta) can be
* mapped onto the unit circle): we wish to minimize the distance
* between the reference point and every other points by traveling
* along the circumference of the unit circle.
*
* APPROXIMATE CHORD SOLUTION
* --------------
* This is hard, however, so instead of computing the distance along the
* circumference, we compute the distance along the chord.
*
* This method is by ebolson@umich.edu, inspired by a similar problem
* in Horn's "closed-form solution of absolute orientation using unit
* quaternions".
*
* Let a be the set of input points, and R(a_i) represent a rotation
* of point a_i around the origin:
*
* R(x) = [ cos(theta)*a_x - sin(theta)*a_y,] [ sin(theta)*a_x + cos(theta)*a_y ]
*
* The error is:
*
* X^2 = SUM ( R(a_i) - [1 0]' )' * (R(a_i) - [1 0]')
*
* = SUM R'R - 2[1 0]R(a) + [1 0][1 0]'
*
* Note that R'R is constant, because R and R' are orthogonal. (R'R =
* I). Dropping constant terms:
*
* X^2 = SUM 2[1 0]R(a)
*
* Differentiating with respect to theta:
*
* dX^2/dtheta = SUM cos(theta)a_x - sin(theta)a_y = 0
*
* Collecting cos and sin terms:
*
* cos(theta) SUM a_x = sin(theta) SUM a_y
*
* e.g.,:
*
* theta = atan2( SUM a_y , SUM a_x )
*
* EXACT SOLUTION
* ----------------
* This solution runs in O(n log n).
*
* Let us suppose that all of the input angles are mapped to [-PI,
* PI].
* All the input points can be shifted to be within PI degrees of the
* reference angle by adding a multiple of 2PI degrees. If all the
* input angles are constrained to [-PI, PI], then we can find a
* reference angle [-PI, 2PI] such that all input points are within PI
* degrees by either adding 0 or exactly 2PI to individual input points.
*
* More so, the input points that we must add 2PI to are the M points
* with the smallest theta, but we do not know M. This is necessary
* when the correct reference angle is large: the smallest points will
* be more than PI degrees away, so they need to be moved to the right
* side of the reference angle.
*
* If we knew M, computing the reference angle is easy: it is simply
* the average of the (possibly shifted) input points. Let x[i] be the
* input point [-PI,PI] and y[i] be the possibly shifted version of
* that point, y[i] = x[i] + 2PI if i < M, otherwise y[i] = x[i].
*
* r = reference angle = (1 / N) * SUM_i y[i]
* error = SUM_i (y[i] - r)^2
*
* We simply search over each value of M (from 0 to N), and recompute
* the error. Both the reference angle and error can be written in
* terms of the first and second moments of y[i], which gives us the
* following strategy:
*
* 1) Compute A1 and A2, the first and second moments of y[i],
* assuming M = 0. (This is just the first and second moments of
* x[i]). This involves iterating over each of the input points.
*
* 2) Considering the points in x[i] in sorted order, update A1 and A2
* such that they reflect y[i] = x[i] + 2PI. Compute the new reference
* theta and error after every point (an O(1) operation) and report
* the theta whose error was the smallest.
*
* Total run time is O(N log N) due to the sort operation. The other
* two passes are O(N). Memory usage is O(N), since all points must be
* stored so they can be sorted.
*
* SUMMARY
* -------
*
* method runtime memory notes
* --------------------------------------------------------
* brute O(2PI*N / eps) O(N) worst-case error is eps/2
* exact O(N log N) O(N)
* chord O(N) O(1) minimizes squared chord length, not squared arc length.
*
* Real-world performance: the exact method is typically faster than
* the chord method, presumably because of the high cost of computing
* trigonometric functions used in the Chord method. This advantage
* decreases with larger number of points (due to the super-linear
* cost of sorting), but even at 50000 points, the optimal method is
* (a bit) faster than the chord method.
*
*
* Reference: Olson, Edwin. "On computing the average orientation of vectors and lines."
* In Robotics and Automation (ICRA), 2011 IEEE International Conference on, pp. 3869-3874. IEEE, 2011.
*
* Code is written in C++ from author's java implmentation by Shireen Elhabian - SCI institute, University of Utah
**/
// only good for positive numbers.
double mod2pi_pos(double vin)
{
double q = vin * twopi_inv + 0.5;
int qi = (int) q;
return vin - qi*twopi;
}
// Ensure that v is [-PI, PI]
double mod2pi(double vin)
{
double v;
if (vin < 0)
v = -1.0*mod2pi_pos(-1.0*vin);
else
v = mod2pi_pos(vin);
// Validation test:
// if (v < -Math.PI || v > Math.PI)
// System.out.printf("%10.3f -> %10.3f\n", vin, v);
return v;
}
/* Returns a value of v wrapped such that ref and v differ by no
* more +/-PI
*/
double mod2pi(double ref, double v)
{
return ref + mod2pi(v-ref);
}
/* For a given theta, compute the MSE. A simple O(N) method used for testing. */
double computeMSE(std::vector<double> thetas, double theta)
{
double sqerr = 0;
for(std::vector<double>::iterator it = thetas.begin(); it != thetas.end(); ++it)
{
double err = mod2pi((*it) - theta);
sqerr += (err * err);
}
return (sqerr / ((double)thetas.size()));
}
/* Trying every theta (with a step size of dtheta), find the theta that results in the smallest MSE.
*/
double averageThetaBruteForce(std::vector<double> thetas, double dtheta)
{
double bestmse = 1e10;
double besttheta = 0;
for (double theta = 0; theta < 2 * M_PI; theta += dtheta)
{
double mse = computeMSE(thetas, theta);
if (mse < bestmse) {
bestmse = mse;
besttheta = theta;
}
}
return mod2pi(besttheta);
}
// the chord method
double averageThetaChord(std::vector<double> thetas)
{
double M = 0, N = 0;
for(std::vector<double>::iterator it = thetas.begin(); it != thetas.end(); ++it)
{
double x0 = cos(*it);
double y0 = sin(*it);
M += y0;
N += x0;
}
return atan2(M, N);
}
// the exact method
double averageThetaArc(std::vector<double> thetas)
{
std::vector<double> x;
for(std::vector<double>::iterator it = thetas.begin(); it != thetas.end(); ++it)
x.push_back(mod2pi(*it)); // map to [-PI, PI]
std::sort (x.begin(), x.end()); // ascending numerical order.
// compute first and second moments without adding 2PI
double A1 = 0, A2 = 0;
int sz = (int) x.size();
for (int i = 0; i < sz; i++)
{
A1 += x[i];
A2 += x[i]*x[i];
}
// now, go back through again, converting elements one-by-one
// into their +2PI versions, recomputing the error and picking
// the best one.
// initialize with case where all points are the non-2PI
// version.
double bestError = 1e10;
double bestTheta = -1;
// note: i=-1 iteration tests case where none are flipped.
for (int i = -1; i < sz; i++)
{
if (i >= 0) {
// flip the i'th component into the +2PI version
A1 += 2*M_PI;
// A2 += (x[i] + 2*Math.PI)^2 - x[i]*x[i]
A2 += 4*M_PI*x[i] + 4*M_PI*M_PI;
}
double theta = A1 / ((double)x.size());
double error = A2 - 2*A1*theta + ((double)x.size())*theta*theta;
if (error < bestError) {
bestError = error;
bestTheta = theta;
}
}
return mod2pi(bestTheta);
}
/* Prateep */
// f(x) = (1-x)^2 / (1+x)^2
double f(double ctheta)
{
const double epsilon = 1.0e-10;
double num = (1.0f * (1-ctheta)) * (1.0f * (1-ctheta));
double den = (1 + ctheta + epsilon) * (1 + ctheta + epsilon);
return num / den;
}
// f'(x) = -(4 * (1-x)) / (1+x)^3
double fprime(double ctheta)
{
const double epsilon = 1.0e-10;
double num = (1.0f - ctheta);
double den = (1 + ctheta + epsilon);
return (-4.0f*num) / (den * den * den);
}
} // end namespace utils
#endif
|
// For more information visit: http://wiki.openpilot.org/display/Doc/Serial+Bluetooth+Telemetry
#include <SoftwareSerial.h>
// --- START CONFIGURATION ---
char* name = "BT_Turnigy_Beetle"; // Name for Bluetooth Device. (alphanumeric, 20 char max, no spaces)
int pin = 1234; // Pairing Code for Module, 4 digits only.. (0000-9999)
int led = 13; // Pin of Blinking LED, default should be fine.
SoftwareSerial bt(3, 2); // Pins for RX, TX on Arduino Side.
char* testMsg = "OpenPilot FUCK YEAH!!"; //
// --- END CONFIGURATION ---
int wait = 1000; // How long to wait between commands (1s), dont change this.
char* response = "OKOKlinvorV1.5OKsetPINOKsetnameOK115200"; // Expected response from BT module after programming is done.
void setup()
{
pinMode(led, OUTPUT);
Serial.begin(115200); // Speed of Debug Console
Serial.println("Configuring bluetooth module for use with OpenPilot, please wait.");
bt.begin(115200); // Speed of your bluetooth module, 9600 is default from factory.
digitalWrite(led, HIGH); // Turn on LED to signal programming has started
delay(wait);
bt.print("AT");
delay(wait);
bt.print("AT+VERSION");
delay(wait);
// Serial.print("Setting PIN: "); // Set PIN
// Serial.println(pin);
// bt.print("AT+PIN");
// bt.print(pin);
// delay(wait);
Serial.print("Setting NAME: "); // Set NAME
Serial.println(name);
bt.print("AT+NAME");
bt.print(name);
delay(wait);
// Serial.println("Setting BAUD: 57600"); // Set baudrate to 57600
// bt.print("AT+BAUD7");
// delay(wait);
if (verifyresults()) { // Check configuration
Serial.println("Configuration verified, entering test mode..");
Serial.println("To do another module plug it in and then hit reset");
testloop(); // Start Test Loop
}
digitalWrite(led, LOW); // Turn off LED to show failure.
Serial.println("Entering Command mode, you can now attempt a manual configuration");
}
void loop() // If verification fails lets bridge the serial ports so programming can be done manually.
{
if (bt.available())
Serial.write(bt.read()); // Pipe Bluetooth to Debug Console
if (Serial.available())
bt.write(Serial.read()); // Pipe Debug Console to Bluetooth
}
int verifyresults() { // This function grabs the response from the BT Module and compares it for validity.
int makeSerialStringPosition;
int inByte;
char serialReadString[50];
inByte = bt.read();
makeSerialStringPosition=0;
if (inByte > 0) { // If we see data (inByte > 0)
delay(100); // Allow serial data time to collect
while (makeSerialStringPosition < 38){ // Stop reading once the string should be gathered (37 chars long)
serialReadString[makeSerialStringPosition] = inByte; // Save the data in a character array
makeSerialStringPosition++; // Increment position in array
inByte = bt.read(); // Read next byte
}
serialReadString[38] = (char) 0; // Null the last character
if(strncmp(serialReadString,response,37) == 0) { // Compare results
return(1); // Results Match, return true..
}
Serial.print("VERIFICATION FAILED!!!, EXPECTED: "); // Debug Messages
Serial.println(response);
Serial.print("VERIFICATION FAILED!!!, RETURNED: "); // Debug Messages
Serial.println(serialReadString);
return(0); // Results FAILED, return false..
} else { // In case we haven't received anything back from module
Serial.println("VERIFICATION FAILED!!!, No answer from the BT module "); // Debug Messages
Serial.println("Check your connections and/or baud rate");
return(0); // Results FAILED, return false..
}
}
void testloop() { // This function is ran when programming is complete.
bt.end();
bt.begin(115200); // Reconnect @ 57600 BAUD.
while(1) { // Begin Endless Loop.
bt.println(testMsg); // Send this string out the BT Module.
digitalWrite(led, LOW); // Flash the LED on and off to signal programing is complete.
delay(250);
digitalWrite(led, HIGH);
delay(250);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.