text
stringlengths 8
6.88M
|
|---|
#include <bits/stdc++.h>
using namespace std;
list <int> table[1000];
int hnum=997;
int main ()
{
ifstream inFile;
inFile.open("hash.in.txt");
int n;
inFile >> n ;
for (int i=0;i<n;i++)
{
int in;
inFile >> in;
int key=in % hnum;
table[key].push_back(in);
}
inFile.close();
cout << "Hash Table" << endl << "Scanning Query" << endl;
while (1)
{
cout << "(1) Insert (2) Find (3) Delete (4) Show All (5) Testing, Warning Laptop will somewhat lag (0) Exit" << endl;
int query;
cin >> query;
if (query==1)
{
int in;
cin >> in;
int key=in % hnum;
table[key].push_back(in);
}
if (query==2)
{
clock_t time;
time = clock();
int in;
cin >> in;
int count=0;
int key=in % hnum;
list<int>::iterator it;
it=table[key].begin();
while (*it!=in && it!=table[key].end())
{
it++;
count ++;
}
if (*it==in)
{
cout << in << " Found on key : " << key << " on index number " << count << endl;
}
if (it==table[key].end())
{
cout << in << " not found :(" << endl;
}
time = clock()-time;
double tle = ((double) time)/ CLOCKS_PER_SEC ;
printf("Search done in %lf seconds\n",tle);
}
if (query==3)
{
int in;
cin >> in;
int key=in % hnum;
list<int>::iterator it;
it=table[key].begin();
while (*it!=in && it!=table[key].end())
{
it++;
}
if(it==table[key].end())
{
cout << in << " Not Found" << endl;
}
else
table[key].erase(it);
}
if (query==4)
{
for (int i=0;i<1000;i++)
{
list<int>::iterator it2;
if (!table[i].empty())
{
it2=table[i].begin();
while (it2!=table[i].end())
{
if (it2==table[i].begin())
{
cout << *it2;
}
else
cout << " --> " << *it2;
it2++;
}
cout << endl;
}
}
}
if (query==5)
{
clock_t time2;
time2 = clock();
double total=0;
int hundcount=0;
for (int testing=0;testing<1000;testing++)
{
clock_t time;
time = clock();
if (testing % 100 == 0)
{
cout<< "Searching from " << testing*1000+1 << " to " << testing*1000+100000<<endl;
}
for (int i=testing*1000+1;i<=testing*1000+1000;i++)
{
int in;
in=i;
int count=0;
int key=in % hnum;
list<int>::iterator it;
it=table[key].begin();
while (*it!=in && it!=table[key].end())
{
it++;
count ++;
}
if (*it==in)
{
// cout << in << " Found on key : " << key << " on index number " << count << endl;
}
if (it==table[key].end())
{
// cout << in << " not found :(" << endl;
}
}
time = clock()-time;
double tle = ((double) time)/ CLOCKS_PER_SEC ;
total+=tle;
if (testing%100==0 && testing!=0)
{
hundcount++;
printf("%d searches done in %lf seconds\n",hundcount*100000,total);
}
}
time2 = clock()-time2;
double tle2 = ((double) time2)/ CLOCKS_PER_SEC ;
printf("Total time taken is %lf seconds\n",tle2);
}
if (query==0)
{
return 0;
}
}
}
|
// 其实就是求逆序对的数量
#include <cstdio>
const int maxn = 500010;
int a[maxn], b[maxn];
long long num;
void Merge(int a[], int start, int mid, int end)
{
int i = start, j = mid + 1, k = start;
while (i <= mid && j <= end)
{
if (a[i] <= a[j])
{
b[k++] = a[i++];
}
else
{
// j++是错误的位置,k++是正确的位置,所以要移动j-k次
num += j - k;
b[k++] = a[j++];
}
}
while (i <= mid)
{
b[k++] = a[i++];
}
while (j <= end)
{
b[k++] = a[j++];
}
for (int i = start; i <= end; i++)
{
a[i] = b[i];
}
}
void MergeSort(int a[], int start, int end)
{
if (start < end)
{
int mid = (start + end) / 2;
MergeSort(a, start, mid);
MergeSort(a, mid + 1, end);
Merge(a, start, mid, end);
}
}
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
if (n == 0)
break;
num = 0;
for (int i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
MergeSort(a, 0, n - 1);
printf("%lld\n", num);
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
int main()
{
ll m,n,i,j,k;
cin>>k;
while(k--)
{
ll a,b,x,y, ans, ans1=0, ans2=0;
cin>>n>>m>>a>>b;
if(a>b)
{
ll tmp=min(n, a+m);
ll baki=n-(a+m);
if(baki<0)
{
ll tmp1=max(1LL, b-abs(baki) );
ans=abs(tmp1-tmp);
}
else ans=abs(tmp-b);
}
else
{
ll tmp=min(n, b+m);
ll baki=n-(b+m);
if(baki<0)
{
ll tmp1=max(1LL, a- abs(baki) );
ans=abs(tmp1-tmp);
}
else ans=abs(tmp-a);
}
cout<<ans<<endl;
}
}
|
/*******************************************************************************
* Cristian Alexandrescu *
* 2163013577ba2bc237f22b3f4d006856 *
* 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 *
* bc9a53289baf23d369484f5343ed5d6c *
*******************************************************************************/
/* Problem 12895 - Armstrong Number */
#include <iostream>
#include <string>
#include <algorithm>
int main() {
const int MAX_DIGITS = 11;
unsigned int arrPowers[MAX_DIGITS][10] = {{0, 1, 1, 1, 1, 1, 1, 1, 1, 1}};
for (int nLoopPower = 1; nLoopPower < MAX_DIGITS; nLoopPower++)
for (int nLoopDigit = 0; nLoopDigit < 10; nLoopDigit++)
arrPowers[nLoopPower][nLoopDigit] = nLoopDigit * arrPowers[nLoopPower - 1][nLoopDigit];
int nNoCases;
for (std::cin >> nNoCases; nNoCases--; ) {
unsigned int nNumber;
std::cin >> nNumber;
std::string oNumber = std::to_string((long long)nNumber);
unsigned int nSum = 0;
std::for_each(oNumber.begin(), oNumber.end(), [&nSum, &arrPowers, &oNumber](char &c) { nSum += arrPowers[oNumber.size()][c - '0']; });
if (nSum == nNumber)
std::cout << "Armstrong" << std::endl;
else
std::cout << "Not Armstrong" << std::endl;
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
std::ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t; cin >> t;
long long int n, k, aux;
std::vector< long long int> v;
std::vector<int> dist;
while(t--){
long long int sum = 0;
cin >> n >> k;
for(int i=0;i<n;i++){
cin >> aux;
v.push_back(aux);
}
int menor = 1000000000;
int ind;
for(int i=0; i+k < n; i++){
//cout << "to olhando do " << v[i] << " até o " << v[k+i] << " dist: " << v[k+i]-v[i] << endl;
if(v[k+i] - v[i] < menor){
menor = v[k+i] - v[i];
ind = v[i];
}
}
cout << ind + menor/2 << endl;
v.clear();
}
}
|
#include "MangConTro.h"
//bool MangConTro::Full(MangConTroDauSach value)
//{
// return (value.soLuongSach == MAXDAUSACH ? true : false);
//}
void MangConTro::insert(ConTroDauSach data)
{
mangConTro.data[mangConTro.soLuongSach++] = data;
int index;
for (index = 0;index < mangConTro.soLuongSach
&& mangConTro.data[index]->tenSach < data->tenSach;index++);
ConTroDauSach temp;
for (int i = mangConTro.soLuongSach - 1;i > index;i--) {
temp = mangConTro.data[i - 1];
mangConTro.data[i - 1] = mangConTro.data[i];
mangConTro.data[i] = temp;
}
}
void MangConTro::del(int index)
{
if (index < mangConTro.soLuongSach) {
ConTroDauSach temp = mangConTro.data[index];
for (int i = index + 1;i < mangConTro.soLuongSach;i++)
mangConTro.data[i - 1] = mangConTro.data[i];
mangConTro.data[mangConTro.soLuongSach - 1] = NULL;
mangConTro.soLuongSach--;
delete temp;
}
}
int MangConTro::search(string tenSach)
{
for (int i = 0;i < mangConTro.soLuongSach;i++) {
if (tenSach == mangConTro.data[i]->tenSach)
return i;
}
return -1;
}
MangConTroDauSach MangConTro::get()
{
return mangConTro;
}
void MangConTro::set(MangConTroDauSach value)
{
}
MangConTro::MangConTro()
{
}
MangConTro::~MangConTro()
{
}
|
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) scanf("%lld", &n)
#define scf(n) scanf("%lf", &n)
#define pfl(x) printf("%lld\n",x)
#define md 10000007
#define pb push_back
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define N 100006
ll a[N];
int main()
{
ll m,n,t,b,c,d,i,j,k,x,y,z,l,q,r;
ll cnt=0,ans=0;
scl(n);
scl(k);
char s;
fr(i,n)
{
cin>>s;
a[s-'A']++;
}
sort(a,a+26);
for(i=25;i>=0;i--)
{
d=min(a[i], k);
ans+=d*d;
k-=d;
}
pfl(ans);
return 0;
}
|
//
// Created by troels on 8/10/16.
//
#ifndef VMMEF_ADCITERATOR_H
#define VMMEF_ADCITERATOR_H
#include <iterator>
#include <cassert>
#include <arpa/inet.h>
class ADCiterator : public std::iterator<std::random_access_iterator_tag, uint16_t >
{
private:
const uint16_t *p;
public:
typedef std::iterator<std::random_access_iterator_tag, uint16_t >::difference_type difference_type;
// Constructors
ADCiterator(const uint16_t* x) :p(x) {assert ((uintptr_t)p % 2 == 0);}
ADCiterator(const uint32_t* x) :p((const uint16_t*)x) {}
ADCiterator(const ADCiterator& mit) : p(mit.p) {}
// Manipulators
inline ADCiterator& operator++() {++p;return *this;}
inline ADCiterator& operator--() {--p;return *this;}
inline ADCiterator operator++(int) {ADCiterator tmp(*this); ++p; return tmp;}
inline ADCiterator operator--(int) {ADCiterator tmp(*this); --p; return tmp;}
inline ADCiterator& operator+=(difference_type i) {p += i; return *this;}
inline ADCiterator& operator-=(difference_type i) {p -= i; return *this;}
// Iterator arithmatic
inline difference_type operator-(const ADCiterator& other) const {return p-other.p;}
inline ADCiterator operator+(difference_type i) const {return ADCiterator(p+i);}
inline ADCiterator operator-(difference_type i) const {return ADCiterator(p-i);}
// Comparison
inline bool operator==(const ADCiterator& other) const {return p == other.p;}
inline bool operator!=(const ADCiterator& other) const {return p != other.p;}
inline bool operator>(const ADCiterator& other) const {return p > other.p;}
inline bool operator<(const ADCiterator& other) const {return p < other.p;}
inline bool operator>=(const ADCiterator& other) const {return p >= other.p;}
inline bool operator<=(const ADCiterator& other) const {return p <= other.p;}
// Value operators
inline uint16_t operator*() const {return ((uintptr_t)p % sizeof(uint32_t) == 0) ? ntohs(*(p+1)) : ntohs(*(p-1));}
inline uint16_t operator[](difference_type i) const {return *(*this+i);}
};
#endif //VMMEF_ADCITERATOR_H
|
#ifndef IMPLISTREC_H
#define IMPLISTREC_H
/// @file ImpListRec.h
/// @brief ImpListRec のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2012 Yusuke Matsunaga
/// All rights reserved.
#include "ImpRec.h"
#include "ImpVal.h"
BEGIN_NAMESPACE_YM_NETWORKS
//////////////////////////////////////////////////////////////////////
/// @class ImpListRec ImpListRec.h "ImpListRec.h"
/// @brief 結果を imp_list に格納する ImpRec
//////////////////////////////////////////////////////////////////////
class ImpListRec :
public ImpRec
{
public:
/// @brief コンストラクタ
/// @param[in] imp_list 含意結果を格納するリスト
ImpListRec(vector<ImpVal>& imp_list);
/// @brief デストラクタ
virtual
~ImpListRec();
public:
/// @brief 含意結果を記録する仮想関数
/// @param[in] src_node 含意元のノード
/// @param[in] src_val 含意元の値
/// @param[in] dst_node 含意先のノード
/// @param[in[ dst_val 含意先の値
virtual
void
record(ImpNode* src_node,
ymuint src_val,
ImpNode* dst_node,
ymuint dst_val);
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// 含意結果を格納するリスト
vector<ImpVal>& mImpList;
};
END_NAMESPACE_YM_NETWORKS
#endif // IMPLISTREC_H
|
/*
* Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
//-----------------------------------------------------------------------------
#include "event.h"
//-----------------------------------------------------------------------------
namespace dcl {
namespace single {
//-----------------------------------------------------------------------------
event::~event()
{
opencl_.clReleaseEvent( id_ );
}
//-----------------------------------------------------------------------------
void event::wait()
{
cl_int error_code = opencl_.clWaitForEvents( 1, &id_ );
if( error_code != CL_SUCCESS )
throw dcl::library_exception( error_code );
}
//-----------------------------------------------------------------------------
void event::load_info()
{
cl_int error_code;
if( local_info_.queued_ == 0 )
{
error_code =
opencl_.clGetEventProfilingInfo( id_, CL_PROFILING_COMMAND_QUEUED,
sizeof(uint64_t), &local_info_.queued_, NULL );
if( error_code != CL_SUCCESS )
throw dcl::library_exception( error_code );
}
if( local_info_.submit_ == 0 )
{
error_code =
opencl_.clGetEventProfilingInfo( id_, CL_PROFILING_COMMAND_SUBMIT,
sizeof(uint64_t), &local_info_.submit_, NULL );
if( error_code != CL_SUCCESS )
throw dcl::library_exception( error_code );
}
if( local_info_.start_ == 0 )
{
error_code =
opencl_.clGetEventProfilingInfo( id_, CL_PROFILING_COMMAND_START,
sizeof(uint64_t), &local_info_.start_, NULL );
if( error_code != CL_SUCCESS )
throw dcl::library_exception( error_code );
}
if( local_info_.end_ == 0 )
{
error_code =
opencl_.clGetEventProfilingInfo( id_, CL_PROFILING_COMMAND_END,
sizeof(uint64_t), &local_info_.end_, NULL );
if( error_code != CL_SUCCESS )
throw dcl::library_exception( error_code );
}
}
//-----------------------------------------------------------------------------
}} // namespace dcl::single
//-----------------------------------------------------------------------------
|
/* DOCUMENTATION BY CHANDAN KUMAR 01/03/2015
INTERFACE 4 WIRE RESISTIVE TOUCH SCREEN WITH ARDUINO
________________
| |
| |
| TOUCH |
| |
| |
| SCREEN |
| (YL1083) |
| |
| |
________________
||||||||
__ __ __ __
|X1| |Y1| |X2| |Y2|
|| || || ||
A0 A1 A2 A3
FOR Y-AXIS:
X1 GND
X2 +5V
MAKE Y1 AND Y2 AS INPUT MEANS HIGH IMPEDANCE
NOW READ ANALOG VALUE ON Y2
FOR X-AXIS:
Y1 GND
Y2 +5V
MAKE X1 AND X2 AS INPUT MEANS HIGH IMPEDANCE
NOW READ ANALOG VALUE ON Y2
*/
const int X1 = A0, Y1 = A1, X2 = A2, Y2 = A3, button = 6;
boolean touch();
int x_cord = 0, y_cord = 0, val = 0, count = -1, arr[11], k = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
while (touch() > 0)
{
Serial.print("Y: ");
Serial.print(x_cord);
Serial.print(" X: ");
Serial.println(y_cord);
delay(500);
//
// if (x_cord > 0 && x_cord < 345 && y_cord > 0 && y_cord < 200) // 1
// {
// Serial.println(1);
// }
//
// if (x_cord > 350 && x_cord < 643 && y_cord > 0 && y_cord < 200) // 2
// {
// Serial.println(2);
// }
//
// if (x_cord > 650 && x_cord < 1000 && y_cord > 0 && y_cord < 200) // 3
// {
// Serial.println(3);
// }
//
// if (x_cord > 0 && x_cord < 345 && y_cord > 210 && y_cord < 473) // 4
// {
// Serial.println(4);
// }
//
// if (x_cord > 350 && x_cord < 643 && y_cord > 210 && y_cord < 473) // 5
// {
// Serial.println(5);
// }
//
// if (x_cord > 650 && x_cord < 1000 && y_cord > 210 && y_cord < 473) // 6
// {
// Serial.println(6);
// }
//
// if (x_cord > 0 && x_cord < 345 && y_cord > 480 && y_cord < 750) // 7
// {
// Serial.println(7);
// }
//
// if (x_cord > 350 && x_cord < 643 && y_cord > 480 && y_cord < 750) // 8
// {
// Serial.println(8);
// }
//
// if (x_cord > 650 && x_cord < 1000 && y_cord > 480 && y_cord < 750) // 9
// {
// Serial.println(9);
// }
//
//
// if (x_cord > 345 && x_cord < 650 && y_cord > 800 && y_cord < 1000) // 0
// {
// Serial.println(0);
// }
//
// if (x_cord > 0 && x_cord < 345 && y_cord > 800 && y_cord < 1000) // *
// {
// Serial.println('*');
// }
//
// if (x_cord > 650 && x_cord < 1000 && y_cord > 800 && y_cord < 1000) // #
// {
// Serial.println('#');
// }
}
}
boolean touch()
{
boolean touch1 = false;
pinMode(X1, OUTPUT);
pinMode(X2, OUTPUT);
digitalWrite(X1, LOW);
digitalWrite(X2, HIGH);
pinMode(Y1, INPUT);
pinMode(Y2, INPUT);
delay(10);
y_cord = analogRead(Y2);
pinMode(Y1, OUTPUT);
pinMode(Y2, OUTPUT);
digitalWrite(Y1, LOW);
digitalWrite(Y2, HIGH);
pinMode(X1, INPUT);
pinMode(X2, INPUT);
delay(10);
x_cord = analogRead(X2);
if (x_cord > 0 && x_cord < 1000 && y_cord > 0 && y_cord < 1000)
touch1 = true;
return touch1;
}
|
//Nurul Anissa binti Huzaini
//A17DW4087
#include <iostream>
using namespace std;
enum minggu {sun,mon,tue,wed,thu,fri,sat};
main(void)
{
minggu hariIni;
hariIni = sun;
cout << "Sunday is "<<hariIni+1<<" day";
return 0;
}
|
//
// Copyright Jason Rice 2019
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include <nbdl/js.hpp>
#include <boost/hana/equal.hpp>
#include <catch.hpp>
namespace hana = boost::hana;
TEST_CASE("get_element_by_id from document object.", "[js]")
{
nbdl::js::init();
EM_ASM({
// set up fake document object
document = {
getElementById : function(id) {
if (id == 'foo') return 1;
else if (id == 'bar') return 2;
else return 0;
}
}
});
nbdl::js::val foo = nbdl::js::get_element_by_id("foo");
nbdl::js::val bar = nbdl::js::get_element_by_id("bar");
nbdl::js::val foo_expected;
nbdl::js::val bar_expected;
NBDL_JS_TRANSFORM(foo_expected, function(x) { return 1; });
NBDL_JS_TRANSFORM(bar_expected, function(x) { return 2; });
CHECK(hana::equal(foo, foo_expected));
CHECK(hana::equal(bar, bar_expected));
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <algorithm>
#include <list>
using namespace std;
int main()
{
ifstream fin("date.in");
int n,i,j,x;
vector <pair<int,char>>S,man; //grad,eticheta
list <pair<char,char>>E;
fin>>n; S.resize(n);man.resize(n);
for(i=0;i<n;i++)
{
fin>>x; if(x<0||x>=n)
{
cout<<"NU"; return 0;
}
S[i]={x,'A'+i};
}
sort(S.begin(),S.end());
//for(i=0;i<n;i++) cout<<S[i].second<<' '<<S[i].first<<'\n';
while(S[n-1].first >0)
{
int d = S[n-1].first;
char et = S[n-1].second;
S.pop_back();n--;
for(i=1;i<=d;i++)
{
S[n-i].first--;
E.push_back({et,S[n-i].second});
if(S[n-i].first<0)
{
cout<< "NU";return 0;
}
}
merge(S.begin(),S.begin()+n-d , S.begin()+n-d,S.end() , man.begin());
for(i=0;i<n;i++)S[i] = man[i];
}
for(auto p:E)
cout<<p.first-'A'+1<<' '<<p.second-'A'+1<<'\n';
}
|
#include "SoundManager.h"
SoundManager::SoundManager(void)
{
}
SoundManager::~SoundManager(void)
{
}
void SoundManager::addMusic(string file)
{
int namestart = file.find_last_of("/");
int nameend = file.find(".");
++namestart;
if (nameend == -1)
nameend = file.length();
string name = file.substr(namestart, nameend - namestart);
sf::Music* mfile = new sf::Music();
mfile->openFromFile(file);
musicList[name] = mfile;
}
void SoundManager::addMusic(string name, string file)
{
sf::Music* mfile = new sf::Music();
mfile->openFromFile(file);
musicList[name] = mfile;
}
void SoundManager::addSound(string file)
{
int namestart = file.find_last_of("/");
int nameend = file.find(".");
++namestart;
if (nameend == -1)
nameend = file.length();
string name = file.substr(namestart, nameend - namestart);
Sound* sfile = new Sound(file);
soundList[name] = sfile;
}
void SoundManager::addSound(string name, string file)
{
Sound* sfile = new Sound(file);
soundList[name] = sfile;
}
void SoundManager::playSound(string name)
{
soundList[name]->sound.play();
}
void SoundManager::playMusic(string name)
{
musicList[name]->play();
}
bool SoundManager::isPlayed(string name)
{
map<string, sf::Music*>::iterator itrmusic = musicList.find(name);
map<string, Sound*>::iterator itrsound = soundList.find(name);
if (itrmusic != musicList.end())
{
if (itrmusic->second->getStatus() == sf::Music::Playing)
return true;
}
if (itrsound != soundList.end())
{
if (itrsound->second->sound.getStatus() == sf::Music::Playing)
return true;
}
return false;
}
void SoundManager::stopMusic(string name)
{
musicList[name]->stop();
}
void SoundManager::stopSound(string name)
{
soundList[name]->sound.stop();
}
void SoundManager::clear()
{
}
|
#ifndef GBMVARMGR_H
#define GBMVARMGR_H
/// @file GbmVarMgr.h
/// @brief GbmVarMgr のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2013, 2014 Yusuke Matsunaga
/// All rights reserved.
#include "YmTools.h"
#include "GbmLit.h"
#include "RcfNetwork.h"
#include "RcfNode.h"
BEGIN_NAMESPACE_YM
//////////////////////////////////////////////////////////////////////
/// @class GbmVarMgr GbmVarMgr.h "GbmVarMgr.h"
/// @brief GBM の基本処理を行なうクラス
//////////////////////////////////////////////////////////////////////
class GbmVarMgr
{
public:
/// @brief コンストラクタ
GbmVarMgr();
/// @brief デストラクタ
~GbmVarMgr();
public:
//////////////////////////////////////////////////////////////////////
// 外部インターフェイス
//////////////////////////////////////////////////////////////////////
/// @brief debug フラグを立てる
void
debug_on();
/// @brief debug フラグを降ろす
void
debug_off();
/// @brief debug フラグの値を得る.
bool
debug() const;
/// @brief 設定変数を初期化する.
/// @param[in] network 対象のネットワーク
void
init(const RcfNetwork& network);
/// @brief モデルから設定変数の割り当てを取り出す.
/// @param[in] model SAT モデル
/// @param[out] conf_bits 設定変数の割り当て
void
get_conf_bits(const vector<Bool3>& model,
vector<bool>& conf_bits) const;
/// @brief モデルから入力順を取り出す.
/// @param[in] model SAT モデル
/// @param[out] iorder 入力順
/// iorder[pos] に network の pos 番めの入力に対応した
/// 関数の入力番号が入る.
virtual
void
get_iorder(const vector<Bool3>& model,
vector<ymuint>& iorder) const;
protected:
//////////////////////////////////////////////////////////////////////
// 継承クラスから用いられる関数
//////////////////////////////////////////////////////////////////////
/// @brief ノードに対応するリテラルを登録する.
/// @param[in] id ノード番号
/// @param[in] lit リテラル
void
set_node_var(ymuint id,
GbmLit lit);
/// @brief 内部ノードに変数番号を割り当て,CNF式を作る.
/// @param[in] network 対象の LUT ネットワーク
/// @param[in] oval 出力値
/// @return 割り当てが矛盾を起こしたら false を返す.
bool
make_nodes_cnf(const RcfNetwork& network,
ymuint oval);
private:
//////////////////////////////////////////////////////////////////////
// 内部で用いられる関数
//////////////////////////////////////////////////////////////////////
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// ノードIDをキーにしてリテラルを格納する配列
vector<GbmLit> mNodeVarArray;
// 設定変数番号をキーにして論理式上の変数番号を格納する配列
vector<VarId> mConfVarArray;
// debug フラグ
bool mDebug;
};
END_NAMESPACE_YM
#endif // GBMVARMGR_H
|
#include<bits/stdc++.h>
using namespace std;
int solve(string input,string* output)
{
if(input.size()==0)
{
output[0]=" ";
return 1;
}
int sm = solve(input.substr(1),output);
for(int i=0;i<sm;i++)
{
output[i+sm]=input[0] + output[i];
}
return 2*sm;
}
// recursion
void solve1(string input,string output)
{
if(input.size()==0)
{
cout << output << endl;
return ;
}
// ignore
solve1(input.substr(1),output);
// include
solve1(input.substr(1),output+input[0]);
}
int main()
{
string input;
cin >> input;
int n = pow(2,input.length());
string* output = new string[n];
int size = solve(input,output);
for(int i=0;i<size;i++)
{
cout << output[i] << endl;
}
solve1(input,"");
return 0;
}
|
#ifndef TINYENGINE_LTE_INIT_H_
#define TINYENGINE_LTE_INIT_H_
#pragma once
#include <iostream>
#include <signal.h>
#include "LTE_Common.h"
#include "LTE_Error.h"
#include "LTE_Font.h"
#include "LTE_Sound.h"
#include "OpenGL/FTGLFontManager.h"
#include "LTE_Globals.h"
#ifndef _GNU_SOURCE
#define _POSIX_C_SOURCE 2 // POSIX.1, POSIX.2
#define _SVID_SOURCE // SVID, ISO C, POSIX.1, POSIX.2, X/Open
#define _BSD_SOURCE 1 // 4.3 BSD Unix, ISO C, POSIX.1, POSIX.2
#endif
#if _POSIX_C_SOURCE >= 1 || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE)
#ifndef HAVE_SIGACTION
#define HAVE_SIGACTION // sigaction is part of POSIX.1
#endif
#endif
#ifndef HAVE_SIGACTION
#error sigaction is not supported
#endif
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_mixer.h>
#include <SDL/SDL_audio.h>
#include <SDL/SDL_video.h>
#include <SDL/SDL_quit.h>
typedef struct {
struct {
uint16_t aspect_w;
uint16_t aspect_h;
uint16_t width;
uint16_t height;
std::string caption;
} window;
struct {
uint8_t fps;
} game;
struct {
uint32_t frequency;
uint8_t num_channels;
uint16_t chunk_size;
} audio;
struct {
struct {
uint32_t enable_hardware_palette:1;
uint32_t enable_hardware_surface:1;
uint32_t enable_fullscreen:1;
uint32_t enable_multiple_cores:1;
uint32_t force_video_surface:1;
} flags;
} video;
} LTE_Config;
sig_atomic_t LTE_GetDone() { return LTE_GLOBAL_DONE; }
SDL_Surface* LTE_GetScreen() { return LTE_GLOBAL_SCREEN; }
bool LTE_Terminated(void) { return LTE_GLOBAL_DONE == 1; }
void LTE_Terminate() { LTE_GLOBAL_DONE = 1; }
static void LTE_CleanUp(int signal)
{
printf("Received signal %d\n", signal);
switch (signal) {
default: break;
case SIGINT:
if (LTE_Terminated()) {
std::cerr << "Double SIGINT received. Exiting..." << std::endl;
exit(EXIT_FAILURE);
} else {
LTE_Terminate();
}
break;
}
}
static void LTE_InstallSigHandlers(void) {
struct sigaction sa;
sa.sa_handler = <E_CleanUp;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGHUP, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGQUIT, &sa, nullptr);
}
bool LTE_Initialize(const LTE_Config& config) {
LTE_InstallSigHandlers();
// TODO: check return values
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
#ifndef USE_OPENGL
TTF_Init();
#endif
SDL_ShowCursor(SDL_DISABLE);
// Disable key repeat
SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
SDL_WM_SetCaption(config.window.caption.c_str(), NULL);
Mix_OpenAudio(config.audio.frequency, MIX_DEFAULT_FORMAT, config.audio.num_channels, config.audio.chunk_size);
const SDL_VideoInfo *videoInfo = SDL_GetVideoInfo();
if (videoInfo == NULL) {
std::cout << "WARNING: Unable to gather video informations." << std::endl;
}
#ifdef USE_OPENGL
uint32_t videoFlags = SDL_OPENGL;
// Set the minimum requirements for the OpenGL window
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
#else
uint32_t videoFlags = config.video.flags.enable_hardware_surface || (videoInfo != NULL && videoInfo->hw_available) ? SDL_HWSURFACE | SDL_DOUBLEBUF : SDL_SWSURFACE;
if (config.video.flags.enable_multiple_cores) {
videoFlags |= SDL_ASYNCBLIT;
}
if (config.video.flags.force_video_surface) {
videoFlags |= SDL_ANYFORMAT;
}
if (config.video.flags.enable_hardware_palette) {
videoFlags |= SDL_HWPALETTE;
}
#endif
if (config.video.flags.enable_fullscreen) {
videoFlags |= SDL_FULLSCREEN;
}
if (videoInfo->hw_available) {
std::cout << "Total video memory: " << videoInfo->video_mem / 1024 << " MB" << std::endl;
}
int width = videoInfo == NULL ? (config.window.width <= 0 ? videoInfo->current_w : config.window.width) : config.window.width;
int height = videoInfo == NULL ? (config.window.height <= 0 ? videoInfo->current_h : config.window.height) : config.window.height;
LTE_GLOBAL_WINDOW = LTE_Size(width, height);
LTE_GLOBAL_ASPECT = LTE_Size(config.window.aspect_w, config.window.aspect_h);
uint8_t bpp = videoInfo == NULL ? videoInfo->vfmt->BitsPerPixel : 16;
LTE_GLOBAL_SCREEN = SDL_SetVideoMode(width, height, bpp, videoFlags);
if (LTE_GLOBAL_SCREEN == NULL) {
std::cerr << "ERROR: Video initialization failed: " << SDL_GetError() << std::endl;
exit(exit_failed_to_set_video_mode);
}
std::cout << "Video mode: " << LTE_GLOBAL_SCREEN->w << "x" << LTE_GLOBAL_SCREEN->h << " - " << (int)LTE_GLOBAL_SCREEN->format->BitsPerPixel << " bpp" << std::endl;
#ifdef USE_OPENGL
int maxTextureSize;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
printf("GL_MAX_TEXTURE_SIZE = %d\n", maxTextureSize);
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, config.window.width, config.window.height, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
glEnable(GL_POINT_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnable(GL_LINE_SMOOTH);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Do not draw alpha bits when they are 0
glAlphaFunc(GL_NOTEQUAL, 0);
glEnable(GL_ALPHA_TEST);
#endif
return true;
}
void LTE_Shutdown() {
#ifdef USE_OPENGL
FTGLFontManager::instance().cleanup();
#endif
SDL_FreeSurface(LTE_GLOBAL_SCREEN);
Mix_CloseAudio();
#ifndef USE_OPENGL
TTF_Quit();
#endif
IMG_Quit();
SDL_Quit();
}
#endif
|
#ifndef RTGLOBALS
#define RTGLOBALS
#define BLOCK_SIZE_X 16
#define BLOCK_SIZE_Y 16
#define WARP_SIZE 32
#define Z_ORDER_BLOCK_SIZE 16
#define CMP_RESULTS_BLOCK_SIZE 256
#define HRT_RAY_MISS 0xFFFFFFFE
#define HRT_RAY_HIT 0xFFFFFFFF
#define GMAXVARS 64
#define INVALID_TEXTURE 0xFFFFFFFE
#define TEX_POINT_SAM 0x10000000
#define TEX_ALPHASRC_W 0x20000000
#define TEX_CLAMP_U 0x40000000
#define TEX_CLAMP_V 0x80000000
// they are related because data are storen in one int32 variable triAlphaTest
//
#define ALPHA_MATERIAL_MASK 0x00FFFFFF
#define ALPHA_LIGHTMESH_MASK 0xFF000000
#define ALPHA_LIGHTMESH_SHIFT 24
#define ALPHA_OPACITY_TEX_HAPPEND 0x80000000
#define ALPHA_TRANSPARENCY_HAPPEND 0x40000000
#define TEXMATRIX_ID_MASK 0x00FFFFFF // for texture slots - 'color_texMatrixId' and e.t.c
#define TEXSAMPLER_TYPE_MASK 0xFF000000 // for texture slots - 'color_texMatrixId' and e.t.c
#ifndef M_PI
#define M_PI 3.14159265358979323846f
#endif
#ifndef INV_PI
#define INV_PI 0.31830988618379067154f
#endif
#ifndef INV_TWOPI
#define INV_TWOPI 0.15915494309189533577f
#endif
#ifndef INV_FOURPI
#define INV_FOURPI 0.07957747154594766788f
#endif
#ifndef DEG_TO_RAD
#define DEG_TO_RAD (M_PI / 180.f)
#endif
#define GEPSILON 5e-6f
#define DEPSILON 1e-20f
#define DEPSILON2 1e-30f
#define PEPSILON 0.025f
#define PG_SCALE 1000.0f
/**
* These defines are for the QMC remap table to support different mappings in run time.
* for example you may decide to map (0,1) to screen (x,y) and (2,3) to DOF (x,y) or
* you may decide to map (0,1) to screen (x,y) and (2,3,4) to material sampling
* if no mapping presents in the table (id == -1) then pseudo random should be used.
*
*/
#define QMC_VAR_SCR_X 0
#define QMC_VAR_SCR_Y 1
#define QMC_VAR_DOF_X 2
#define QMC_VAR_DOF_Y 3
#define QMC_VAR_SRC_A 4
#define QMC_VAR_MAT_L 5
#define QMC_VAR_MAT_0 6
#define QMC_VAR_MAT_1 7
#define QMC_VAR_LGT_N 8
#define QMC_VAR_LGT_0 9
#define QMC_VAR_LGT_1 10
#define QMC_VAR_LGT_2 11
/**
* Note that unlike QMC, MMLT don't use remap table.
* These offsets are direct offsets in the ramdom vector table (in floats)
*
*/
#define MMLT_HEAD_TOTAL_SIZE 12 //
// [0-3] : LENS; 4 in total
//
#define MMLT_DIM_SCR_X 0
#define MMLT_DIM_SCR_Y 1
#define MMLT_DIM_DOF_X 2
#define MMLT_DIM_DOF_Y 3
// [4-10]: LIGHT; 7 in total
//
#define MMLT_DIM_LGT_X 4
#define MMLT_DIM_LGT_Y 5
#define MMLT_DIM_LGT_Z 6
#define MMLT_DIM_LGT_W 7
#define MMLT_DIM_LGT_X1 8
#define MMLT_DIM_LGT_Y1 9
#define MMLT_DIM_LGT_N 10
// [11] : SPLIT;
//
#define MMLT_DIM_SPLIT 11
#define MMLT_FLOATS_PER_MLAYER 7
#define MMLT_FLOATS_PER_SAMPLE 3
#define MMLT_FLOATS_PER_BOUNCE (MMLT_FLOATS_PER_SAMPLE + MMLT_FLOATS_PER_MLAYER)
#define MMLT_COMPRESSED_F_PERB 6
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define KMLT_HEAD_SIZE 4
#define KMLT_PER_LIGHT 4
#define KMLT_PER_MATERIAL 6
enum MEGATEX_USAGE{ MEGATEX_SHADING = 1,
MEGATEX_SHADING_HDR = 2,
MEGATEX_NORMAL = 3,
MEGATEX_OPACITY = 4,
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef __CUDACC__
#else
#ifdef OCL_COMPILER // OpenCL
#define ALIGN_S(x) __attribute__ ((aligned (x)))
#define __device__
#define IDH_CALL inline
#define ID_CALL inline
IDH_CALL ushort2 make_ushort2(ushort x, ushort y) { ushort2 res; res.x = x; res.y = y; return res; }
IDH_CALL int2 make_int2(int a, int b) { int2 res; res.x = a; res.y = b; return res; }
IDH_CALL int4 make_int4(int a, int b, int c, int d) { int4 res; res.x = a; res.y = b; res.z = c; res.w = d; return res; }
#define GLOBAL_ID_X get_global_id(0)
#define GLOBAL_ID_Y get_global_id(1)
#define LOCAL_ID_X get_local_id(0)
#define LOCAL_ID_Y get_local_id(1)
#define _PACKED __attribute__ ((packed))
#define __device__
//#define SYNCTHREADS barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE)
#define SYNCTHREADS_LOCAL barrier(CLK_LOCAL_MEM_FENCE)
#define SYNCTHREADS_GLOBAL barrier(CLK_GLOBAL_MEM_FENCE)
static inline float maxcomp(float3 v) { return fmax(v.x, fmax(v.y, v.z)); }
#define NULL 0
static inline ushort4 make_ushort4(ushort a, ushort b, ushort c, ushort d)
{
ushort4 res;
res.x = a;
res.y = b;
res.z = c;
res.w = d;
return res;
}
static inline void atomic_addf(volatile __global float *source, const float operand)
{
union {
unsigned int intVal;
float floatVal;
} newVal;
union {
unsigned int intVal;
float floatVal;
} prevVal;
do {
prevVal.floatVal = *source;
newVal.floatVal = prevVal.floatVal + operand;
} while (atomic_cmpxchg((volatile global unsigned int *)source, prevVal.intVal, newVal.intVal) != prevVal.intVal);
}
IDH_CALL float dot3 (const float4 u, const float4 v) { return (u.x*v.x + u.y*v.y + u.z*v.z); }
typedef struct float4x3T
{
float4 row[3];
} float4x3;
typedef struct float4x4T
{
float4 row[4];
} float4x4;
typedef struct float3x3T
{
float3 row[3];
} float3x3;
IDH_CALL float2 make_float2(float a, float b)
{
float2 res;
res.x = a;
res.y = b;
return res;
}
IDH_CALL float3 make_float3(float a, float b, float c)
{
float3 res;
res.x = a;
res.y = b;
res.z = c;
return res;
}
IDH_CALL float4 make_float4(float a, float b, float c, float d)
{
float4 res;
res.x = a;
res.y = b;
res.z = c;
res.w = d;
return res;
}
IDH_CALL float2 to_float2(float4 f4)
{
float2 res;
res.x = f4.x;
res.y = f4.y;
return res;
}
IDH_CALL float3 to_float3(float4 f4)
{
float3 res;
res.x = f4.x;
res.y = f4.y;
res.z = f4.z;
return res;
}
IDH_CALL float4 to_float4(float3 v, float w)
{
float4 res;
res.x = v.x;
res.y = v.y;
res.z = v.z;
res.w = w;
return res;
}
static inline float3 mul4x3(float4x4 m, float3 v)
{
float3 res;
res.x = m.row[0].x*v.x + m.row[0].y*v.y + m.row[0].z*v.z + m.row[0].w;
res.y = m.row[1].x*v.x + m.row[1].y*v.y + m.row[1].z*v.z + m.row[1].w;
res.z = m.row[2].x*v.x + m.row[2].y*v.y + m.row[2].z*v.z + m.row[2].w;
return res;
}
static inline float3 mul3x3(float4x4 m, float3 v)
{
float3 res;
res.x = m.row[0].x*v.x + m.row[0].y*v.y + m.row[0].z*v.z;
res.y = m.row[1].x*v.x + m.row[1].y*v.y + m.row[1].z*v.z;
res.z = m.row[2].x*v.x + m.row[2].y*v.y + m.row[2].z*v.z;
return res;
}
static inline float2 sincos2f(float a_value)
{
float cosVal;
float sinVal = sincos(a_value, &cosVal);
return make_float2(sinVal, cosVal);
}
#else // Common C++
#ifdef WIN32
#define ALIGN_S(x) __declspec(align(x))
#else
#define ALIGN_S(x) __attribute__ ((aligned (x)))
#endif
#undef M_PI
#define M_PI 3.14159265358979323846f
#include "../../HydraAPI/hydra_api/LiteMath.h"
using namespace HydraLiteMath;
#include "../../HydraAPI/hydra_api/HR_HDRImage.h"
typedef HydraRender::HDRImage4f HDRImage4f;
typedef unsigned int uint;
typedef unsigned short ushort;
typedef struct float4x3T
{
float4 row[3];
} float4x3;
typedef struct float3x3T
{
float3 row[3];
} float3x3;
static inline float2 sincos2f(float a_value)
{
return make_float2(sin(a_value), cos(a_value));
}
#define IDH_CALL static inline
#define ID_CALL static inline
#define __global
#define __constant const
#define __private
#define __read_only
typedef int image1d_t;
typedef int image1d_buffer_t;
typedef int image2d_t;
typedef int sampler_t;
const int CLK_NORMALIZED_COORDS_TRUE = 1;
const int CLK_NORMALIZED_COORDS_FALSE = 2;
const int CLK_ADDRESS_CLAMP = 4;
const int CLK_FILTER_NEAREST = 8;
const int CLK_FILTER_LINEAR = 16;
const int CLK_ADDRESS_REPEAT = 32;
#define COMMON_CPLUS_PLUS_CODE 1
static inline int as_int(float x) { return reinterpret_cast<int&> (x); }
static inline float as_float(int x) { return reinterpret_cast<float&>(x); }
#define _PACKED
typedef unsigned short half;
static inline void vstore_half(float data, size_t offset, __global half *p) { p[offset] = 0; }
static inline float sign(float a) { return (a > 0.0f) ? 1.0f : -1.0f; }
static inline int2 make_int2(int a, int b) { int2 res; res.x = a; res.y = b; return res; }
using std::isinf;
#define ENABLE_OPACITY_TEX 1
#define SHADOW_TRACE_COLORED_SHADOWS 1
#define ENABLE_BLINN 1
#include "globals_sys.h"
#endif
#endif
typedef __global const int4* texture2d_t;
#ifndef INFINITY
#define INFINITY (1e38f)
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct MatSampleT
{
float3 color;
float3 direction;
float pdf;
int flags;
} MatSample;
enum FLAG_BITS{HRT_COMPUTE_SHADOWS = 1,
HRT_DISABLE_SHADING = 2,
HRT_DIRECT_LIGHT_MODE = 4,
HRT_UNIFIED_IMAGE_SAMPLING = 8,
HRT_PRODUCTION_IMAGE_SAMPLING = 16, // 256 coherent rays per pixel.
HRT_USE_MIS = 32,
HRT_DUMMY2 = 64, // !!!!!!!! DONT USE THIS FLAG !!!! UNKNOWN BUG, PT DOES NOT CONTRIBUTE TO SCREEN.
HRT_STORE_SUBPIXELS = 128,
HRT_FORWARD_TRACING = 256, /// tracing from light to eye; otherwise from eye to light.
HRT_DRAW_LIGHT_LT = 512,
HRT_3WAY_MIS_WEIGHTS = 1024,
HRT_STORE_RAY_SAMPLES = 8192,
HRT_ENABLE_MMLT = 16384,
HRT_ENABLE_SBPT = 32768,
HRT_INDIRECT_LIGHT_MODE = 65536,
HRT_STUPID_PT_MODE = 65536*8,
HRT_NO_RANDOM_LIGHTS_SELECT = 65536*16,
HRT_DUMMY5 = 65536*32, //
HRT_DUMMY6 = 65536*64, // tracing photons to form spetial photonmap to speed-up direct light sampling
HRT_DUMMY7 = 65536*128,
HRT_DUMMY8 = 65536*256,
HRT_ENABLE_PT_CAUSTICS = 65536*2048,
HRT_USE_BOTH_PHOTON_MAPS = 65536*4096,
HRT_ENABLE_QMC_ONE_SEED = 65536*8192, // !!!!!!!! DONT MOVE THIS FLAG !!!! See random generator implementation
HRT_ENABLE_COHERENT_PT = 65536*16384,
};
enum VARIABLE_NAMES { // int vars
//
HRT_ENABLE_DOF = 0,
HRT_QMC_VARIANT = 1,
HRT_FIRST_BOUNCE_STORE_CACHE = 2,
HRT_ENABLE_MRAYS_COUNTERS = 3,
HRT_DEBUG_OUTPUT = 4,
HRT_MEASURE_RAYS_TYPE = 5,
HRT_BLACK_DIFFUSE_OFFSET = 6,
HRT_STORE_SHADOW_COLOR_W = 7,
HRT_WHITE_DIFFUSE_OFFSET = 8,
HRT_TRACE_DEPTH = 9,
HRT_PHOTONS_STORE_BOUNCE = 10,
HRT_PHOTONS_GARTHER_BOUNCE = 11,
HRT_RAYS_APPENDBUFFER_SIZE = 12,
HRT_DIFFUSE_TRACE_DEPTH = 13,
HRT_DISPLAY_IC_INTERMEDIATE = 14,
HRT_PT_FILTER_TYPE = 15,
HRT_ENABLE_BAKE = 16,
HRT_SILENT_MODE = 17,
HRT_VAR_ENABLE_RR = 18,
HRT_RENDER_LAYER = 19,
HRT_RENDER_LAYER_DEPTH = 20,
HRT_IC_ENABLED = 21,
HRT_IMAP_ENABLED = 22,
HRT_SPHEREMAP_TEXID0 = 23,
HRT_SPHEREMAP_TEXID1 = 24,
HRT_USE_GAMMA_FOR_ENV = 25,
HRT_HRT_SCENE_HAVE_PORTALS = 26,
HRT_SPHEREMAP_TEXMATRIXID0 = 27,
HRT_SPHEREMAP_TEXMATRIXID1 = 28,
HRT_ENABLE_PATH_REGENERATE = 29,
HRT_ENV_PDF_TABLE_ID = 30,
HRT_MLT_MAX_NUMBERS = 31,
HRT_MLT_ITERS_MULT = 32,
HRT_MMLT_BURN_ITERS = 33,
HRT_MMLT_FIRST_BOUNCE = 34,
HRT_SHADOW_MATTE_BACK = 35,
HRT_MAX_SAMPLES_PER_PIXEL = 36,
HRT_CONTRIB_SAMPLES = 37,
HRT_BOX_MODE_ON = 38,
HRT_KMLT_OR_QMC_LGT_BOUNCES = 39,
HRT_KMLT_OR_QMC_MAT_BOUNCES = 40,
};
enum VARIABLE_FLOAT_NAMES{ // float vars
//
HRT_DOF_LENS_RADIUS = 0,
HRT_DOF_FOCAL_PLANE_DIST = 1,
HRT_TILT_ROT_X = 2,
HRT_TRACE_PROCEEDINGS_TRESHOLD = 3,
HRT_TILT_ROT_Y = 4,
HRT_CAUSTIC_POWER_MULT = 5,
HRT_IMAGE_GAMMA = 6,
HRT_TEXINPUT_GAMMA = 7,
HRT_ENV_COLOR_X = 8,
HRT_ENV_COLOR_Y = 9,
HRT_ENV_COLOR_Z = 10,
HRT_ENV_COLOR2_X = 11,
HRT_ENV_COLOR2_Y = 12,
HRT_ENV_COLOR2_Z = 13,
HRT_CAM_FOV = 14,
HRT_PATH_TRACE_ERROR = 15,
HRT_ENV_CLAMPING = 16,
HRT_BSDF_CLAMPING = 17,
HRT_BSPHERE_CENTER_X = 18,
HRT_BSPHERE_CENTER_Y = 19,
HRT_BSPHERE_CENTER_Z = 20,
HRT_BSPHERE_RADIUS = 21,
HRT_GVOXEL_SIZE = 22,
HRT_FOV_X = 23, // viewport parameters
HRT_FOV_Y = 24,
HRT_WIDTH_F = 25,
HRT_HEIGHT_F = 26,
HRT_ABLOW_OFFSET_X = 27,
HRT_ABLOW_OFFSET_Y = 28,
HRT_ABLOW_SCALE_X = 29,
HRT_ABLOW_SCALE_Y = 30,
HRT_MMLT_IMPLICIT_FIXED_PROB = 31,
HRT_MMLT_STEP_SIZE_POWER = 32,
HRT_MMLT_STEP_SIZE_COEFF = 33,
HRT_MLT_SCREEN_SCALE_X = 34,
HRT_MLT_SCREEN_SCALE_Y = 35,
HRT_BACK_TEXINPUT_GAMMA = 36,
};
enum RENDER_LAYER {
LAYER_COLOR = 0,
LAYER_POSITIONS = 1,
LAYER_NORMALS = 2,
LAYER_TEXCOORD = 3,
LAYER_TEXCOLOR_AND_MATERIAL = 4, // material mask
LAYER_INCOMING_PRIMARY = 5, // incoming primary
LAYER_INCOMING_RADIANCE = 6, // incoming secondary
LAYER_COLOR_PRIMARY_AND_REST = 7, // primary + refractions and other bounces
LAYER_COLOR_THE_REST = 8,
LAYER_PRIMARY = 9,
LAYER_SECONDARY = 10
}; // refractions, and other bounces
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IDH_CALL uint ZIndex(ushort x, ushort y, __constant ushort* a_mortonTable256)
{
return (a_mortonTable256[y >> 8] << 17) |
(a_mortonTable256[x >> 8] << 16) |
(a_mortonTable256[y & 0xFF] << 1 ) |
(a_mortonTable256[x & 0xFF] );
}
IDH_CALL ushort ExtractFromZIndex3D(uint zIndex, int stride)
{
uint result = 0;
for (int i = 0; i < 10; i++)
{
int bitBask = 1 << (3 * i + stride);
int bit = (bitBask & zIndex) ? 1 : 0;
result |= (bit << i);
}
return (ushort)result;
}
IDH_CALL ushort ExtractFromZIndex2D(uint zIndex, int stride)
{
uint result = 0;
for (int i = 0; i < 16; i++)
{
int bitBask = 1 << (2 * i + stride);
int bit = (bitBask & zIndex) ? 1 : 0;
result |= (bit << i);
}
return (ushort)result;
}
IDH_CALL ushort ExtractXFromZIndex(uint zIndex)
{
uint result = 0;
for (int i = 0; i<16; i++)
result |= ((1 << (2 * i)) & zIndex) >> i;
return (ushort)result;
}
IDH_CALL ushort ExtractYFromZIndex(uint zIndex)
{
uint result = 0;
for (int i = 0; i<16; i++)
result |= ((1 << (2 * i + 1)) & zIndex) >> i;
return (ushort)(result >> 1);
}
IDH_CALL int blocks(int elems, int threadsPerBlock)
{
if (elems % threadsPerBlock == 0 && elems >= threadsPerBlock)
return elems / threadsPerBlock;
else
return (elems / threadsPerBlock) + 1;
}
IDH_CALL size_t blocksST(size_t elems, int threadsPerBlock)
{
if (elems % threadsPerBlock == 0 && elems >= threadsPerBlock)
return elems / threadsPerBlock;
else
return (elems / threadsPerBlock) + 1;
}
IDH_CALL size_t roundBlocks(size_t elems, int threadsPerBlock)
{
if (elems < threadsPerBlock)
return (size_t)threadsPerBlock;
else
return blocksST(elems, threadsPerBlock) * threadsPerBlock;
}
IDH_CALL uint Index2D(uint x, uint y, int pitch) { return y*pitch + x; }
IDH_CALL uint IndexZBlock2D(int x, int y, int pitch, __constant ushort* a_mortonTable) // window_size[0]
{
uint zOrderX = x % Z_ORDER_BLOCK_SIZE;
uint zOrderY = y % Z_ORDER_BLOCK_SIZE;
uint zIndex = ZIndex(zOrderX, zOrderY, a_mortonTable);
uint wBlocks = pitch / Z_ORDER_BLOCK_SIZE;
uint blockX = x / Z_ORDER_BLOCK_SIZE;
uint blockY = y / Z_ORDER_BLOCK_SIZE;
return (blockX + (blockY)*(wBlocks))*Z_ORDER_BLOCK_SIZE*Z_ORDER_BLOCK_SIZE + zIndex;
}
IDH_CALL ushort2 GetXYFromZBlockIndex(uint a_offset, int w, int h)
{
int blocksSizeX = w / Z_ORDER_BLOCK_SIZE;
//int blocksSizeY = h / Z_ORDER_BLOCK_SIZE;
int blockId = a_offset / (Z_ORDER_BLOCK_SIZE*Z_ORDER_BLOCK_SIZE);
int zIdInBlock = a_offset % (Z_ORDER_BLOCK_SIZE*Z_ORDER_BLOCK_SIZE);
int blockY = blockId / blocksSizeX;
int blockX = blockId - blockY*blocksSizeX;
int localX = (int)ExtractXFromZIndex(zIdInBlock);
int localY = (int)ExtractYFromZIndex(zIdInBlock);
ushort2 res;
res.x = (ushort)(blockX*Z_ORDER_BLOCK_SIZE + localX);
res.y = (ushort)(blockY*Z_ORDER_BLOCK_SIZE + localY);
return res;
}
IDH_CALL uint SpreadBits(int x, int offset)
{
x = (x | (x << 10)) & 0x000F801F;
x = (x | (x << 4)) & 0x00E181C3;
x = (x | (x << 2)) & 0x03248649;
x = (x | (x << 2)) & 0x09249249;
return (uint)(x) << offset;
}
IDH_CALL uint GetMortonNumber(int x, int y, int z)
{
return SpreadBits(x, 0) | SpreadBits(y, 1) | SpreadBits(z, 2);
}
IDH_CALL float3 reflect(float3 dir, float3 normal) { return normalize((normal * dot(dir, normal) * (-2.0f)) + dir); }
///////////////////////////////////////////////////////////////////////////////////////////////////////////
///// a simple tone mapping
IDH_CALL float3 ToneMapping(float3 color) { return make_float3(fmin(color.x, 1.0f), fmin(color.y, 1.0f), fmin(color.z, 1.0f)); }
IDH_CALL float4 ToneMapping4(float4 color) { return make_float4(fmin(color.x, 1.0f), fmin(color.y, 1.0f), fmin(color.z, 1.0f), fmin(color.w, 1.0f)); }
/////////////////////////////////////////////////////////////////////////////////////////////////////////
////
IDH_CALL uint RealColorToUint32_f3(float3 real_color)
{
float r = real_color.x*255.0f;
float g = real_color.y*255.0f;
float b = real_color.z*255.0f;
unsigned char red = (unsigned char)r, green = (unsigned char)g, blue = (unsigned char)b;
return red | (green << 8) | (blue << 16) | 0xFF000000;
}
IDH_CALL uint RealColorToUint32(float4 real_color)
{
float r = real_color.x*255.0f;
float g = real_color.y*255.0f;
float b = real_color.z*255.0f;
float a = real_color.w*255.0f;
unsigned char red = (unsigned char)r;
unsigned char green = (unsigned char)g;
unsigned char blue = (unsigned char)b;
unsigned char alpha = (unsigned char)a;
return red | (green << 8) | (blue << 16) | (alpha << 24);
}
static inline float3 SafeInverse(float3 d)
{
const float ooeps = 1.0e-36f; // Avoid div by zero.
float3 res;
res.x = 1.0f / (fabs(d.x) > ooeps ? d.x : copysign(ooeps, d.x));
res.y = 1.0f / (fabs(d.y) > ooeps ? d.y : copysign(ooeps, d.y));
res.z = 1.0f / (fabs(d.z) > ooeps ? d.z : copysign(ooeps, d.z));
return res;
}
static inline float epsilonOfPos(float3 hitPos) { return fmax(fmax(fabs(hitPos.x), fmax(fabs(hitPos.y), fabs(hitPos.z))), 2.0f*GEPSILON)*GEPSILON; }
static inline float misHeuristicPower1(float p) { return isfinite(p) ? fabs(p) : 0.0f; }
static inline float misHeuristicPower2(float p) { return isfinite(p*p) ? p*p : 0.0f; }
static inline float misWeightHeuristic(float a, float b)
{
const float w = misHeuristicPower1(a) / fmax(misHeuristicPower1(a) + misHeuristicPower1(b), DEPSILON2);
return isfinite(w) ? w : 0.0f;
}
static inline float misWeightHeuristic3(float a, float b, float c)
{
const float w = fabs(a) / fmax(misHeuristicPower1(a) + misHeuristicPower1(b) + misHeuristicPower1(c), DEPSILON2);
if(!isfinite(a))
return 1.0f;
else
return isfinite(w) ? w : 0.0f;
}
/**
\brief offset reflected ray position by epsilon;
\param a_hitPos - world space position on surface
\param a_surfaceNorm - surface normal at a_hitPos
\param a_sampleDir - ray direction in which we are going to trace reflected ray
\return offseted ray position
*/
static inline float3 OffsRayPos(const float3 a_hitPos, const float3 a_surfaceNorm, const float3 a_sampleDir)
{
const float signOfNormal2 = dot(a_sampleDir, a_surfaceNorm) < 0.0f ? -1.0f : 1.0f;
const float offsetEps = epsilonOfPos(a_hitPos);
return a_hitPos + signOfNormal2*offsetEps*a_surfaceNorm;
}
/**
\brief offset reflected ray position by epsilon;
\param a_hitPos - world space position on surface
\param a_surfaceNorm - surface normal at a_hitPos
\param a_sampleDir - ray direction in which we are going to trace reflected ray
\param a_shadowOffsAux - per poly auxilarry shadow offset.
\return offseted ray position
*/
static inline float3 OffsShadowRayPos(const float3 a_hitPos, const float3 a_surfaceNorm, const float3 a_sampleDir, const float a_shadowOffsAux)
{
const float signOfNormal2 = dot(a_sampleDir, a_surfaceNorm) < 0.0f ? -1.0f : 1.0f;
const float offsetEps = epsilonOfPos(a_hitPos);
return a_hitPos + signOfNormal2*(offsetEps + a_shadowOffsAux)*a_surfaceNorm;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static inline float4x4 make_float4x4(__global const float* a_data)
{
float4x4 matrix;
matrix.row[0] = make_float4(a_data[0], a_data[1], a_data[2], a_data[3]);
matrix.row[1] = make_float4(a_data[4], a_data[5], a_data[6], a_data[7]);
matrix.row[2] = make_float4(a_data[8], a_data[9], a_data[10], a_data[11]);
matrix.row[3] = make_float4(a_data[12], a_data[13], a_data[14], a_data[15]);
return matrix;
}
IDH_CALL float4x4 make_matrix_rotationX(float a_angle)
{
float sinx = sin(a_angle);
float cosx = cos(a_angle);
float4x4 matrix;
matrix.row[0] = make_float4(1.0f, 0.0f, 0.0f, 0.0f);
matrix.row[1] = make_float4(0.0f, cosx, sinx, 0.0f);
matrix.row[2] = make_float4(0.0f, -sinx, cosx, 0.0f);
matrix.row[3] = make_float4(0.0f, 0.0f, 0.0f, 1.0f);
return matrix;
}
IDH_CALL float4x4 make_matrix_rotationY(float a_angle)
{
float siny = sin(a_angle);
float cosy = cos(a_angle);
float4x4 matrix;
matrix.row[0] = make_float4(cosy, 0.0f, -siny, 0.0f);
matrix.row[1] = make_float4(0.0f, 1.0f, 0.0f, 0.0f);
matrix.row[2] = make_float4(siny, 0.0f, cosy, 0.0f);
matrix.row[3] = make_float4(0.0f, 0.0f, 0.0f, 1.0f);
return matrix;
}
IDH_CALL float3 mul4x3x3(float4x3 m, float3 v)
{
float3 res;
res.x = m.row[0].x*v.x + m.row[0].y*v.y + m.row[0].z*v.z + m.row[0].w;
res.y = m.row[1].x*v.x + m.row[1].y*v.y + m.row[1].z*v.z + m.row[1].w;
res.z = m.row[2].x*v.x + m.row[2].y*v.y + m.row[2].z*v.z + m.row[2].w;
return res;
}
IDH_CALL float4 mul4x4x4(float4x4 m, float4 v)
{
float4 res;
res.x = m.row[0].x*v.x + m.row[0].y*v.y + m.row[0].z*v.z + m.row[0].w*v.w;
res.y = m.row[1].x*v.x + m.row[1].y*v.y + m.row[1].z*v.z + m.row[1].w*v.w;
res.z = m.row[2].x*v.x + m.row[2].y*v.y + m.row[2].z*v.z + m.row[2].w*v.w;
res.w = m.row[3].x*v.x + m.row[3].y*v.y + m.row[3].z*v.z + m.row[3].w*v.w;
return res;
}
#ifndef COMMON_CPLUS_PLUS_CODE
IDH_CALL float3 mul(float4x4 m, float3 v)
{
float3 res;
res.x = m.row[0].x*v.x + m.row[0].y*v.y + m.row[0].z*v.z + m.row[0].w;
res.y = m.row[1].x*v.x + m.row[1].y*v.y + m.row[1].z*v.z + m.row[1].w;
res.z = m.row[2].x*v.x + m.row[2].y*v.y + m.row[2].z*v.z + m.row[2].w;
return res;
}
#endif
IDH_CALL float3 mul3x4(float4x3 m, float3 v)
{
float3 res;
res.x = m.row[0].x*v.x + m.row[0].y*v.y + m.row[0].z*v.z + m.row[0].w;
res.y = m.row[1].x*v.x + m.row[1].y*v.y + m.row[1].z*v.z + m.row[1].w;
res.z = m.row[2].x*v.x + m.row[2].y*v.y + m.row[2].z*v.z + m.row[2].w;
return res;
}
IDH_CALL float3x3 make_float3x3(float3 a, float3 b, float3 c)
{
float3x3 m;
m.row[0] = a;
m.row[1] = b;
m.row[2] = c;
return m;
}
IDH_CALL float3x3 make_float3x3_by_columns(float3 a, float3 b, float3 c)
{
float3x3 m;
m.row[0].x = a.x;
m.row[1].x = a.y;
m.row[2].x = a.z;
m.row[0].y = b.x;
m.row[1].y = b.y;
m.row[2].y = b.z;
m.row[0].z = c.x;
m.row[1].z = c.y;
m.row[2].z = c.z;
return m;
}
IDH_CALL float3 mul3x3x3(float3x3 m, const float3 v)
{
float3 res;
res.x = m.row[0].x*v.x + m.row[0].y*v.y + m.row[0].z*v.z;
res.y = m.row[1].x*v.x + m.row[1].y*v.y + m.row[1].z*v.z;
res.z = m.row[2].x*v.x + m.row[2].y*v.y + m.row[2].z*v.z;
return res;
}
IDH_CALL float3x3 mul3x3x3x3(float3x3 m1, float3x3 m2)
{
float3 column1 = mul3x3x3(m1, make_float3(m2.row[0].x, m2.row[1].x, m2.row[2].x));
float3 column2 = mul3x3x3(m1, make_float3(m2.row[0].y, m2.row[1].y, m2.row[2].y));
float3 column3 = mul3x3x3(m1, make_float3(m2.row[0].z, m2.row[1].z, m2.row[2].z));
return make_float3x3_by_columns(column1, column2, column3);
}
IDH_CALL float3x3 inverse(float3x3 a)
{
float det = a.row[0].x * (a.row[1].y * a.row[2].z - a.row[1].z * a.row[2].y) -
a.row[0].y * (a.row[1].x * a.row[2].z - a.row[1].z * a.row[2].x) +
a.row[0].z * (a.row[1].x * a.row[2].y - a.row[1].y * a.row[2].x);
float3x3 b;
b.row[0].x = (a.row[1].y * a.row[2].z - a.row[1].z * a.row[2].y);
b.row[0].y = -(a.row[0].y * a.row[2].z - a.row[0].z * a.row[2].y);
b.row[0].z = (a.row[0].y * a.row[1].z - a.row[0].z * a.row[1].y);
b.row[1].x = -(a.row[1].x * a.row[2].z - a.row[1].z * a.row[2].x);
b.row[1].y = (a.row[0].x * a.row[2].z - a.row[0].z * a.row[2].x);
b.row[1].z = -(a.row[0].x * a.row[1].z - a.row[0].z * a.row[1].x);
b.row[2].x = (a.row[1].x * a.row[2].y - a.row[1].y * a.row[2].x);
b.row[2].y = -(a.row[0].x * a.row[2].y - a.row[0].y * a.row[2].x);
b.row[2].z = (a.row[0].x * a.row[1].y - a.row[0].y * a.row[1].x);
float s = 1.0f / det;
b.row[0] *= s;
b.row[1] *= s;
b.row[2] *= s;
return b;
}
#ifndef COMMON_CPLUS_PLUS_CODE
static inline float4x4 inverse4x4(float4x4 m1)
{
float tmp[12]; // temp array for pairs
float4x4 m;
// calculate pairs for first 8 elements (cofactors)
//
tmp[0] = m1.row[2].z * m1.row[3].w;
tmp[1] = m1.row[2].w * m1.row[3].z;
tmp[2] = m1.row[2].y * m1.row[3].w;
tmp[3] = m1.row[2].w * m1.row[3].y;
tmp[4] = m1.row[2].y * m1.row[3].z;
tmp[5] = m1.row[2].z * m1.row[3].y;
tmp[6] = m1.row[2].x * m1.row[3].w;
tmp[7] = m1.row[2].w * m1.row[3].x;
tmp[8] = m1.row[2].x * m1.row[3].z;
tmp[9] = m1.row[2].z * m1.row[3].x;
tmp[10] = m1.row[2].x * m1.row[3].y;
tmp[11] = m1.row[2].y * m1.row[3].x;
// calculate first 8 m1.rowents (cofactors)
//
m.row[0].x = tmp[0] * m1.row[1].y + tmp[3] * m1.row[1].z + tmp[4] * m1.row[1].w;
m.row[0].x -= tmp[1] * m1.row[1].y + tmp[2] * m1.row[1].z + tmp[5] * m1.row[1].w;
m.row[1].x = tmp[1] * m1.row[1].x + tmp[6] * m1.row[1].z + tmp[9] * m1.row[1].w;
m.row[1].x -= tmp[0] * m1.row[1].x + tmp[7] * m1.row[1].z + tmp[8] * m1.row[1].w;
m.row[2].x = tmp[2] * m1.row[1].x + tmp[7] * m1.row[1].y + tmp[10] * m1.row[1].w;
m.row[2].x -= tmp[3] * m1.row[1].x + tmp[6] * m1.row[1].y + tmp[11] * m1.row[1].w;
m.row[3].x = tmp[5] * m1.row[1].x + tmp[8] * m1.row[1].y + tmp[11] * m1.row[1].z;
m.row[3].x -= tmp[4] * m1.row[1].x + tmp[9] * m1.row[1].y + tmp[10] * m1.row[1].z;
m.row[0].y = tmp[1] * m1.row[0].y + tmp[2] * m1.row[0].z + tmp[5] * m1.row[0].w;
m.row[0].y -= tmp[0] * m1.row[0].y + tmp[3] * m1.row[0].z + tmp[4] * m1.row[0].w;
m.row[1].y = tmp[0] * m1.row[0].x + tmp[7] * m1.row[0].z + tmp[8] * m1.row[0].w;
m.row[1].y -= tmp[1] * m1.row[0].x + tmp[6] * m1.row[0].z + tmp[9] * m1.row[0].w;
m.row[2].y = tmp[3] * m1.row[0].x + tmp[6] * m1.row[0].y + tmp[11] * m1.row[0].w;
m.row[2].y -= tmp[2] * m1.row[0].x + tmp[7] * m1.row[0].y + tmp[10] * m1.row[0].w;
m.row[3].y = tmp[4] * m1.row[0].x + tmp[9] * m1.row[0].y + tmp[10] * m1.row[0].z;
m.row[3].y -= tmp[5] * m1.row[0].x + tmp[8] * m1.row[0].y + tmp[11] * m1.row[0].z;
// calculate pairs for second 8 m1.rowents (cofactors)
//
tmp[0] = m1.row[0].z * m1.row[1].w;
tmp[1] = m1.row[0].w * m1.row[1].z;
tmp[2] = m1.row[0].y * m1.row[1].w;
tmp[3] = m1.row[0].w * m1.row[1].y;
tmp[4] = m1.row[0].y * m1.row[1].z;
tmp[5] = m1.row[0].z * m1.row[1].y;
tmp[6] = m1.row[0].x * m1.row[1].w;
tmp[7] = m1.row[0].w * m1.row[1].x;
tmp[8] = m1.row[0].x * m1.row[1].z;
tmp[9] = m1.row[0].z * m1.row[1].x;
tmp[10] = m1.row[0].x * m1.row[1].y;
tmp[11] = m1.row[0].y * m1.row[1].x;
// calculate second 8 m1 (cofactors)
//
m.row[0].z = tmp[0] * m1.row[3].y + tmp[3] * m1.row[3].z + tmp[4] * m1.row[3].w;
m.row[0].z -= tmp[1] * m1.row[3].y + tmp[2] * m1.row[3].z + tmp[5] * m1.row[3].w;
m.row[1].z = tmp[1] * m1.row[3].x + tmp[6] * m1.row[3].z + tmp[9] * m1.row[3].w;
m.row[1].z -= tmp[0] * m1.row[3].x + tmp[7] * m1.row[3].z + tmp[8] * m1.row[3].w;
m.row[2].z = tmp[2] * m1.row[3].x + tmp[7] * m1.row[3].y + tmp[10] * m1.row[3].w;
m.row[2].z -= tmp[3] * m1.row[3].x + tmp[6] * m1.row[3].y + tmp[11] * m1.row[3].w;
m.row[3].z = tmp[5] * m1.row[3].x + tmp[8] * m1.row[3].y + tmp[11] * m1.row[3].z;
m.row[3].z -= tmp[4] * m1.row[3].x + tmp[9] * m1.row[3].y + tmp[10] * m1.row[3].z;
m.row[0].w = tmp[2] * m1.row[2].z + tmp[5] * m1.row[2].w + tmp[1] * m1.row[2].y;
m.row[0].w -= tmp[4] * m1.row[2].w + tmp[0] * m1.row[2].y + tmp[3] * m1.row[2].z;
m.row[1].w = tmp[8] * m1.row[2].w + tmp[0] * m1.row[2].x + tmp[7] * m1.row[2].z;
m.row[1].w -= tmp[6] * m1.row[2].z + tmp[9] * m1.row[2].w + tmp[1] * m1.row[2].x;
m.row[2].w = tmp[6] * m1.row[2].y + tmp[11] * m1.row[2].w + tmp[3] * m1.row[2].x;
m.row[2].w -= tmp[10] * m1.row[2].w + tmp[2] * m1.row[2].x + tmp[7] * m1.row[2].y;
m.row[3].w = tmp[10] * m1.row[2].z + tmp[4] * m1.row[2].x + tmp[9] * m1.row[2].y;
m.row[3].w -= tmp[8] * m1.row[2].y + tmp[11] * m1.row[2].z + tmp[5] * m1.row[2].x;
// calculate matrix inverse
//
float k = 1.0f / (m1.row[0].x * m.row[0].x + m1.row[0].y * m.row[1].x + m1.row[0].z * m.row[2].x + m1.row[0].w * m.row[3].x);
for (int i = 0; i<4; i++)
{
m.row[i].x *= k;
m.row[i].y *= k;
m.row[i].z *= k;
m.row[i].w *= k;
}
return m;
}
// Look At matrix creation
// return the inverse view matrix
//
IDH_CALL float4x4 lookAt(float3 eye, float3 center, float3 up)
{
float3 x, y, z; // basis; will make a rotation matrix
z.x = eye.x - center.x;
z.y = eye.y - center.y;
z.z = eye.z - center.z;
z = normalize(z);
y.x = up.x;
y.y = up.y;
y.z = up.z;
x = cross(y, z); // X vector = Y cross Z
y = cross(z, x); // Recompute Y = Z cross X
// cross product gives area of parallelogram, which is < 1.0 for
// non-perpendicular unit-length vectors; so normalize x, y here
x = normalize(x);
y = normalize(y);
float4x4 M;
M.row[0].x = x.x; M.row[1].x = x.y; M.row[2].x = x.z; M.row[3].x = -x.x * eye.x - x.y * eye.y - x.z*eye.z;
M.row[0].y = y.x; M.row[1].y = y.y; M.row[2].y = y.z; M.row[3].y = -y.x * eye.x - y.y * eye.y - y.z*eye.z;
M.row[0].z = z.x; M.row[1].z = z.y; M.row[2].z = z.z; M.row[3].z = -z.x * eye.x - z.y * eye.y - z.z*eye.z;
M.row[0].w = 0.0; M.row[1].w = 0.0; M.row[2].w = 0.0; M.row[3].w = 1.0;
return M;
}
static inline float4x4 transpose(const float4x4 a_mat)
{
float4x4 res;
res.row[0].x = a_mat.row[0].x;
res.row[0].y = a_mat.row[1].x;
res.row[0].z = a_mat.row[2].x;
res.row[0].w = a_mat.row[3].x;
res.row[1].x = a_mat.row[0].y;
res.row[1].y = a_mat.row[1].y;
res.row[1].z = a_mat.row[2].y;
res.row[1].w = a_mat.row[3].y;
res.row[2].x = a_mat.row[0].z;
res.row[2].y = a_mat.row[1].z;
res.row[2].z = a_mat.row[2].z;
res.row[2].w = a_mat.row[3].z;
res.row[3].x = a_mat.row[0].w;
res.row[3].y = a_mat.row[1].w;
res.row[3].z = a_mat.row[2].w;
res.row[3].w = a_mat.row[3].w;
return res;
}
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
IDH_CALL float3 EyeRayDir(float x, float y, float w, float h, float4x4 a_mViewProjInv) // g_mViewProjInv
{
float4 pos = make_float4( 2.0f * (x + 0.5f) / w - 1.0f,
-2.0f * (y + 0.5f) / h + 1.0f,
0.0f,
1.0f );
pos = mul4x4x4(a_mViewProjInv, pos);
pos /= pos.w;
pos.y *= (-1.0f);
return normalize(to_float3(pos));
}
IDH_CALL void matrix4x4f_mult_ray3(float4x4 a_mWorldViewInv, __private float3* ray_pos, __private float3* ray_dir) // g_mWorldViewInv
{
float3 pos = mul(a_mWorldViewInv, (*ray_pos));
float3 pos2 = mul(a_mWorldViewInv, ((*ray_pos) + 100.0f*(*ray_dir)));
float3 diff = pos2 - pos;
(*ray_pos) = pos;
(*ray_dir) = normalize(diff);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
////
IDH_CALL float3 matrix3x3f_mult_float3(__global const float* M, float3 v)
{
float3 res;
res.x = M[0 * 3 + 0] * v.x + M[0 * 3 + 1] * v.y + M[0 * 3 + 2] * v.z;
res.y = M[1 * 3 + 0] * v.x + M[1 * 3 + 1] * v.y + M[1 * 3 + 2] * v.z;
res.z = M[2 * 3 + 0] * v.x + M[2 * 3 + 1] * v.y + M[2 * 3 + 2] * v.z;
return res;
}
IDH_CALL float DistanceSquared(float3 a, float3 b)
{
float3 diff = b - a;
return dot(diff, diff);
}
IDH_CALL float UniformConePdf(float cosThetaMax) { return 1.0f / (2.0f * M_PI * (1.0f - cosThetaMax)); }
IDH_CALL float3 UniformSampleSphere(float u1, float u2)
{
float z = 1.0f - 2.0f * u1;
float r = sqrt(fmax(0.0f, 1.0f - z*z));
float phi = 2.0f * M_PI * u2;
float x = r * cos(phi);
float y = r * sin(phi);
return make_float3(x, y, z);
}
IDH_CALL float lerp2(float t, float a, float b)
{
return (1.0f - t) * a + t * b;
}
IDH_CALL float3 UniformSampleCone(float u1, float u2, float costhetamax, float3 x, float3 y, float3 z)
{
float costheta = lerp2(u1, costhetamax, 1.0f);
float sintheta = sqrt(1.0f - costheta*costheta);
float phi = u2 * 2.0f * M_PI;
return cos(phi) * sintheta * x + sin(phi) * sintheta * y + costheta * z;
}
IDH_CALL float2 RaySphereIntersect(float3 rayPos, float3 rayDir, float3 sphPos, float radius)
{
float3 k = rayPos - sphPos;
float b = dot(k, rayDir);
float c = dot(k, k) - radius*radius;
float d = b * b - c;
float2 res;
if (d >= 0.0f)
{
float sqrtd = sqrt(d);
float t1 = -b - sqrtd;
float t2 = -b + sqrtd;
res.x = fmin(t1, t2);
res.y = fmax(t1, t2);
}
else
{
res.x = -1e28f;
res.y = -1e28f;
}
return res;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct ObjectListTriangle
{
float4 v1;
float4 v2;
float4 v3;
};
struct ObjectListSphere
{
float3 pos;
float r;
};
struct ObjectList
{
#ifndef OCL_COMPILER
#ifndef __CUDACC__
ObjectList() { m_triangleCount = m_offset = dummy1 = dummy2 = 0; }
inline ObjectListTriangle* GetTriangles() const { return (ObjectListTriangle*)(((char*)this) + sizeof(ObjectList)); }
inline const ObjectListSphere* GetSpheres() const { return (const ObjectListSphere*)((char*)this + sizeof(ObjectList) + m_triangleCount*sizeof(ObjectListTriangle)); }
#endif
#endif
int m_offset;
int m_triangleCount;
int dummy1;
int dummy2;
};
IDH_CALL int GetNumTriangles(struct ObjectList ol) { return ol.m_triangleCount; }
IDH_CALL int GetOffset(struct ObjectList ol) { return ol.m_offset; }
IDH_CALL int GetNumPrimitives(struct ObjectList ol) { return GetNumTriangles(ol); }
struct ALIGN_S(16) Lite_HitT
{
float t;
int primId;
int instId;
int geomId;
};
typedef struct Lite_HitT Lite_Hit;
IDH_CALL Lite_Hit Make_Lite_Hit(float t, int a_treeId)
{
int a_geomId = 0;
Lite_Hit hit;
hit.t = t;
hit.primId = -1;
hit.instId = -1;
hit.geomId = (a_geomId & 0x3FFFFFFF) | ((a_treeId << 30) & 0xC0000000);
return hit;
}
static inline bool HitNone(const Lite_Hit a_hit) { return (a_hit.primId == -1) || !isfinite(a_hit.t); }
static inline bool HitSome(const Lite_Hit a_hit) { return (a_hit.primId != -1) && isfinite(a_hit.t); }
IDH_CALL int IS_LEAF(int a_leftOffsetAndLeaf) { return a_leftOffsetAndLeaf & 0x80000000; }
IDH_CALL int PACK_LEAF_AND_OFFSET(int a_leftOffset, int leaf) { return (a_leftOffset & 0x7fffffff) | (leaf & 0x80000000); }
IDH_CALL int EXTRACT_OFFSET(int a_leftOffsetAndLeaf) { return a_leftOffsetAndLeaf & 0x7fffffff; }
// a know about bit fields, but in CUDA they didn't work
//
struct BVHNodeT
{
#ifndef __CUDACC__
#ifndef OCL_COMPILER
BVHNodeT()
{
m_leftOffsetAndLeaf = 0xffffffff;
m_escapeIndex = 0xffffffff;
m_boxMin = float3(INFINITY, INFINITY, INFINITY);
m_boxMax = float3(-INFINITY, -INFINITY, -INFINITY);
}
inline unsigned int Leaf() const { return (m_leftOffsetAndLeaf & 0x80000000) >> 31; }
inline void SetLeaf(unsigned int a_Leaf) { m_leftOffsetAndLeaf = (m_leftOffsetAndLeaf & 0x7fffffff) | ((a_Leaf) << 31); }
inline void SetLeftOffset(unsigned int in_offset) { m_leftOffsetAndLeaf = (m_leftOffsetAndLeaf & 0x80000000) | (in_offset & 0x7fffffff); }
inline void SetObjectListOffset(unsigned int in_offset)
{
if (Leaf())
SetLeftOffset(in_offset);
}
inline unsigned int GetLeftOffset() const { return m_leftOffsetAndLeaf & 0x7fffffff; }
inline unsigned int GetRightOffset() const { return GetLeftOffset() + 1; }
inline unsigned int GetObjectListOffset() const { return GetLeftOffset(); }
inline void SetInstance(unsigned int a_Leaf) { m_escapeIndex = a_Leaf; }
inline unsigned int Instance() const { return (m_escapeIndex == 1); }
#endif
#endif
float3 m_boxMin;
unsigned int m_leftOffsetAndLeaf;
float3 m_boxMax;
unsigned int m_escapeIndex;
};
typedef struct BVHNodeT BVHNode;
IDH_CALL bool IsValidNode(const BVHNode a_node) { return !((a_node.m_leftOffsetAndLeaf == 0xffffffff) && (a_node.m_escapeIndex == 0xffffffff)); }
struct _PACKED RayFlagsT
{
unsigned char diffuseBounceNum;
unsigned char bounceNum;
unsigned short otherFlags;
};
typedef struct RayFlagsT RayFlags;
enum MATERIAL_EVENT {
RAY_EVENT_S = 1, ///< Indicates Specular reflection or refraction (check for RAY_EVENT_T)
RAY_EVENT_D = 2, ///< Indicates Diffuse reflection or translucent (check for RAY_EVENT_T)
RAY_EVENT_G = 4, ///< Indicates GLossy reflection or refraction (check for RAY_EVENT_T)
RAY_EVENT_T = 8, ///< Indicates Transparensy or reftacrion.
RAY_EVENT_V = 16, ///< Indicates Volume scattering, not used for a while
RAY_EVENT_TOUT = 32, ///< Indicates Transparensy Outside of water or glass or e.t.c. (old RAY_IS_INSIDE_TRANSPARENT_OBJECT = 128)
RAY_EVENT_TNINGLASS = 64,
};
static inline bool isPureSpecular(const MatSample a_sample) { return (a_sample.flags & RAY_EVENT_S) != 0; }
static inline bool isDiffuse (const MatSample a_sample) { return (a_sample.flags & RAY_EVENT_D) != 0; }
static inline bool isGlossy (const MatSample a_sample) { return (a_sample.flags & RAY_EVENT_G) != 0; }
static inline bool isTransparent (const MatSample a_sample) { return (a_sample.flags & RAY_EVENT_T) != 0; }
enum {
RAY_GRAMMAR_DIRECT_LIGHT = 64,
RAY_GRAMMAR_OUT_OF_SCENE = 128,
RAY_DUMMY_FLAG_NOT_USED = 256,
RAY_HIT_SURFACE_FROM_OTHER_SIDE = 2048,
RAY_IS_DEAD = 4096, // set when ray had account environment or died on the surface
RAY_SHADE_FROM_OTHER_SIDE = 8192,
RAY_SHADE_FROM_SKY_LIGHT = 16384,
RAY_WILL_DIE_NEXT_BOUNCE = 32768, // set when ray had account only light on next bounce and then immediately die
};
static inline uint unpackRayFlags(uint a_flags) { return ((a_flags & 0xFFFF0000) >> 16); }
static inline uint packRayFlags(uint a_oldData, uint a_flags) { return (a_oldData & 0x0000FFFF) | (a_flags << 16); }
static inline uint unpackBounceNum(uint a_flags) { return ((a_flags & 0x0000FF00) >> 8); }
static inline uint unpackBounceNumDiff(uint a_flags) { return (a_flags & 0x000000FF); }
static inline uint packBounceNum (uint a_oldData, uint a_bounceNum) { return (a_oldData & 0xFFFF00FF) | (a_bounceNum << 8); }
static inline uint packBounceNumDiff(uint a_oldData, uint a_bounceNum) { return (a_oldData & 0xFFFFFF00) | (a_bounceNum); }
static inline bool rayIsActiveS(RayFlags a_flags) { return (a_flags.otherFlags & (RAY_GRAMMAR_OUT_OF_SCENE | RAY_IS_DEAD)) == 0; }
static inline bool rayIsActiveU(uint a_flags) { return ( ((a_flags & 0xFFFF0000) >> 16) & (RAY_GRAMMAR_OUT_OF_SCENE | RAY_IS_DEAD)) == 0; }
static inline bool isEyeRay(uint a_flags)
{
const uint otherFlags = unpackRayFlags(a_flags);
const bool haveSomeNonSpecularReflections = (otherFlags & RAY_EVENT_D) || (otherFlags & RAY_EVENT_G);
return (unpackBounceNum(a_flags) == 0) || !haveSomeNonSpecularReflections;
// return (unpackBounceNum(a_flags) == 0);
}
/**
\brief This structure is used as transit to pass MIS-weights-important-data from previouce bounce to current (or from current to next).
*/
typedef struct MisDataT
{
float matSamplePdf; ///< previous angle pdf (pdfW) that were used for sampling material.
float cosThetaPrev; ///< previous angle cos; it allow to compute projected angle pdf (pdfWP = pdfW/cosThetaPrev);
int prevMaterialOffset; ///< offset in material buffer to material leaf (elemental brdf) that were sampled on prev bounce; it is needed to disable caustics;
int isSpecular; ///< indicate if bounce was pure specular;
} MisData;
static inline MisData makeInitialMisData()
{
MisData data;
data.matSamplePdf = 1.0f;
data.cosThetaPrev = 1.0f;
data.prevMaterialOffset = -1;
data.isSpecular = 1;
return data;
}
static inline uint encodeNormal(float3 n)
{
short x = (short)(n.x*32767.0f);
short y = (short)(n.y*32767.0f);
ushort sign = (n.z >= 0) ? 0 : 1;
int sx = ((int)(x & 0xfffe) | sign);
int sy = ((int)(y & 0xfffe) << 16);
return (sx | sy);
}
static inline float3 decodeNormal(uint a_data)
{
const float divInv = 1.0f / 32767.0f;
short a_enc_x, a_enc_y;
a_enc_x = (short)(a_data & 0x0000FFFF);
a_enc_y = (short)((int)(a_data & 0xFFFF0000) >> 16);
float sign = (a_enc_x & 0x0001) ? -1.0f : 1.0f;
float x = (short)(a_enc_x & 0xfffe)*divInv;
float y = (short)(a_enc_y & 0xfffe)*divInv;
float z = sign*sqrt(fmax(1.0f - x*x - y*y, 0.0f));
return make_float3(x, y, z);
}
struct ALIGN_S(16) HitPosNormT
{
float pos_x;
float pos_y;
float pos_z;
uint norm_xy;
#ifdef __CUDACC__
__device__ float3 GetNormal() const { return decodeNormal(norm_xy); }
__device__ void SetNormal(float3 a_norm) { norm_xy = encodeNormal(normalize(a_norm)); }
#endif
};
typedef struct HitPosNormT HitPosNorm;
ID_CALL HitPosNorm make_HitPosNorm(float4 a_data)
{
HitPosNorm res;
res.pos_x = a_data.x;
res.pos_y = a_data.y;
res.pos_z = a_data.z;
res.norm_xy = (uint)(as_int(a_data.w));
return res;
}
IDH_CALL float3 GetPos(HitPosNorm a_data) { return make_float3(a_data.pos_x, a_data.pos_y, a_data.pos_z); }
IDH_CALL void SetPos(__private HitPosNorm* a_pData, float3 a_pos) { a_pData->pos_x = a_pos.x; a_pData->pos_y = a_pos.y; a_pData->pos_z = a_pos.z; }
struct ALIGN_S(8) HitTexCoordT
{
float tex_u;
float tex_v;
};
typedef struct HitTexCoordT HitTexCoord;
struct ALIGN_S(8) HitMatRefT
{
int m_data;
float accumDist;
};
typedef struct HitMatRefT HitMatRef;
IDH_CALL int GetMaterialId(HitMatRef a_hitMat) { return a_hitMat.m_data; }
IDH_CALL void SetHitType(__private HitMatRef* a_pHitMat, int a_id)
{
int mask = a_id << 28;
int m_data2 = a_pHitMat->m_data & 0x0FFFFFFF;
a_pHitMat->m_data = m_data2 | mask;
}
IDH_CALL void SetMaterialId(__private HitMatRef* a_pHitMat, int a_mat_id)
{
int mask = a_mat_id & 0x0FFFFFFF;
int m_data2 = a_pHitMat->m_data & 0xF0000000;
a_pHitMat->m_data = m_data2 | mask;
}
struct ALIGN_S(8) Hit_Part4T
{
uint tangentCompressed;
uint bitangentCompressed;
};
typedef struct Hit_Part4T Hit_Part4;
static inline void CoordinateSystem(float3 v1, __private float3* v2, __private float3* v3)
{
float invLen = 1.0f;
if (fabs(v1.x) > fabs(v1.y))
{
invLen = 1.0f / sqrt(v1.x*v1.x + v1.z*v1.z);
(*v2) = make_float3(-v1.z * invLen, 0.0f, v1.x * invLen);
}
else
{
invLen = 1.0f / sqrt(v1.y*v1.y + v1.z*v1.z);
(*v2) = make_float3(0.0f, v1.z * invLen, -v1.y * invLen);
}
(*v3) = cross(v1, (*v2));
}
IDH_CALL float3 MapSampleToCosineDistribution(float r1, float r2, float3 direction, float3 hit_norm, float power)
{
if(power >= 1e6f)
return direction;
float sin_phi = sin(2.0f*r1*3.141592654f);
float cos_phi = cos(2.0f*r1*3.141592654f);
//sincos(2.0f*r1*3.141592654f, &sin_phi, &cos_phi);
float cos_theta = pow(1.0f - r2, 1.0f / (power + 1.0f));
float sin_theta = sqrt(1.0f - cos_theta*cos_theta);
float3 deviation;
deviation.x = sin_theta*cos_phi;
deviation.y = sin_theta*sin_phi;
deviation.z = cos_theta;
float3 ny = direction, nx, nz;
CoordinateSystem(ny, &nx, &nz);
{
float3 temp = ny;
ny = nz;
nz = temp;
}
float3 res = nx*deviation.x + ny*deviation.y + nz*deviation.z;
float invSign = dot(direction, hit_norm) > 0.0f ? 1.0f : -1.0f;
if (invSign*dot(res, hit_norm) < 0.0f) // reflected ray is below surface #CHECK_THIS
{
res = (-1.0f)*nx*deviation.x + ny*deviation.y - nz*deviation.z;
//belowSurface = true;
}
return res;
}
// Using the modified Phong reflectance model for physically based rendering
//
IDH_CALL float3 MapSampleToModifiedCosineDistribution(float r1, float r2, float3 direction, float3 hit_norm, float power)
{
if (power >= 1e6f)
return direction;
// float sin_phi, cos_phi;
// sincosf(2 * r1*3.141592654f, &sin_phi, &cos_phi);
float sin_phi = sin(2.0f*r1*3.141592654f);
float cos_phi = cos(2.0f*r1*3.141592654f);
float sin_theta = sqrt(1.0f - pow(r2, 2.0f / (power + 1.0f)));
float3 deviation;
deviation.x = sin_theta*cos_phi;
deviation.y = sin_theta*sin_phi;
deviation.z = sqrt(1.0f - deviation.x*deviation.x - deviation.y*deviation.y); //pow(r2, 1.0f / (power + 1.0f));
float3 ny = direction, nx, nz;
CoordinateSystem(ny, &nx, &nz);
{
float3 temp = ny;
ny = nz;
nz = temp;
}
float3 res = nx*deviation.x + ny*deviation.y + nz*deviation.z;
float invSign = dot(direction, hit_norm) >= 0.0f ? 1.0f : -1.0f;
if (invSign*dot(res, hit_norm) < 0.0f) // reflected ray is below surface #CHECK_THIS
res = (-1.0f)*nx*deviation.x - ny*deviation.y + nz*deviation.z;
return res;
}
/**
\brief transform float2 sample in rect [-1,1]x[-1,1] to disc centered at (0,0) with radius == 1.
\param xy - input sample in rect [-1,1]x[-1,1]
\return position in disc
*/
static inline float2 MapSamplesToDisc(float2 xy)
{
float x = xy.x;
float y = xy.y;
float r = 0;
float phi = 0;
float2 res = xy;
if (x>y && x>-y)
{
r = x;
phi = 0.25f*3.141592654f*(y / x);
}
if (x < y && x > -y)
{
r = y;
phi = 0.25f*3.141592654f*(2.0f - x / y);
}
if (x < y && x < -y)
{
r = -x;
phi = 0.25f*3.141592654f*(4.0f + y / x);
}
if (x >y && x<-y)
{
r = -y;
phi = 0.25f*3.141592654f*(6 - x / y);
}
//float sin_phi, cos_phi;
//sincosf(phi, &sin_phi, &cos_phi);
float sin_phi = sin(phi);
float cos_phi = cos(phi);
res.x = r*sin_phi;
res.y = r*cos_phi;
return res;
}
static inline float3 MapSamplesToCone(float cosCutoff, float2 sample, float3 direction)
{
float cosTheta = (1.0f - sample.x) + sample.x * cosCutoff;
float sinTheta = sqrt(1.0f - cosTheta * cosTheta);
//float sinPhi, cosPhi;
//sincosf(2.0f * M_PI * sample.y, &sinPhi, &cosPhi);
float sinPhi = sin(2.0f * M_PI * sample.y);
float cosPhi = cos(2.0f * M_PI * sample.y);
float3 deviation = make_float3(cosPhi * sinTheta, sinPhi * sinTheta, cosTheta);
// transform to different basis
//
float3 ny = direction;
float3 nx, nz;
CoordinateSystem(ny, &nx, &nz);
//swap(ny, nz);
{
float3 temp = ny;
ny = nz;
nz = temp;
}
return nx*deviation.x + ny*deviation.y + nz*deviation.z;
}
IDH_CALL float3 MapSamplesToSphere(float r1, float r2) // [-1..1]
{
float phi = r1*3.141592654f * 2.0f; // [0 .. 2PI]
float h = r2*2.0f - 1.0f; // [-1 .. 1]
float sin_phi = sin(phi);
float cos_phi = cos(phi);
float x = sin_phi*sqrt(1 - h*h);
float y = cos_phi*sqrt(1 - h*h);
float z = h;
return make_float3(x, y, z);
}
struct ALIGN_S(16) ZBlockT
{
#ifndef OCL_COMPILER
#ifndef __CUDACC__
ZBlockT() { index = 0; diff = 100; counter = 0; index2 = 0; }
ZBlockT(int a_index, float a_diff)
{
index = a_index;
index2 = 0;
diff = a_diff;
counter = 0;
}
#endif
inline static int GetSize() { return Z_ORDER_BLOCK_SIZE*Z_ORDER_BLOCK_SIZE; }
inline int GetOffset() const { return index*GetSize(); }
inline bool operator<(const ZBlockT& rhs) const { return (diff < rhs.diff); }
#endif
int index; // just block offset if global screen buffer
int index2; // index in other buffer + avg trace depth
int counter; // how many times this block was traced?
float diff; // error in some units. stop criterion if fact
};
typedef struct ZBlockT ZBlock;
//IDH_CALL uint unpackAvgTraceDepth(uint a_flags) { return ((a_flags & 0xFF000000) >> 24); }
//IDH_CALL uint packAvgTraceDepth(uint a_oldData, uint a_flags) { return (a_oldData & 0x00FFFFFF) | (a_flags << 24); }
//IDH_CALL uint unpackIndex2(uint a_flags) { return (a_flags & 0x00FFFFFF); }
//IDH_CALL uint packIndex2(uint a_oldData, uint a_flags) { return (a_oldData & 0xFF000000) | a_flags; }
static bool BlockFinished(ZBlock block, int a_minRaysPerPixel, int a_maxRaysPerPixel, float* a_outDiff) // for use on the cpu side ... for current
{
int samplesPerPixel = block.counter; // was *2 due to odd and even staff
if(a_outDiff!=NULL)
*a_outDiff = block.diff;
float acceptedBadPixels = 8.0f; // sqrt((float)(CMP_RESULTS_BLOCK_SIZE));
int minRaysPerPixel = a_minRaysPerPixel;
bool summErrorOk = (block.diff <= acceptedBadPixels);
bool maxErrorOk = false;
return ((summErrorOk || maxErrorOk) && samplesPerPixel >= minRaysPerPixel) || (samplesPerPixel >= a_maxRaysPerPixel);
}
IDH_CALL uint ThreadSwizzle1D(uint pixelId, uint zBlockIndex)
{
uint indexInsideZBlock = pixelId%CMP_RESULTS_BLOCK_SIZE;
return zBlockIndex*CMP_RESULTS_BLOCK_SIZE + indexInsideZBlock;
}
static inline float PdfAtoW(const float aPdfA, const float aDist, const float aCosThere)
{
return (aPdfA*aDist*aDist) / fmax(aCosThere, DEPSILON2);
}
static inline float PdfWtoA(const float aPdfW, const float aDist, const float aCosThere)
{
return aPdfW * fabs(aCosThere) / fmax(aDist*aDist, DEPSILON2);
}
struct MRaysStat
{
#ifndef OCL_COMPILER
MRaysStat() { memset(this, 0, sizeof(MRaysStat)); }
#endif
int traceTimePerCent;
float raysPerSec;
float samplesPerSec;
float reorderTimeMs;
float traversalTimeMs;
float samLightTimeMs;
float shadowTimeMs;
float shadeTimeMs;
float bounceTimeMS;
float evalHitMs;
float nextBounceMs;
float sampleTimeMS;
};
IDH_CALL float probabilityAbsorbRR(uint a_flags, uint a_globalFlags)
{
if (a_globalFlags & HRT_ENABLE_MMLT) // metropolis don't use roultte
return 0.0f;
const uint diffBounceNum = unpackBounceNumDiff(a_flags);
const uint otherFlags = unpackRayFlags(a_flags);
float pabsorb = 0.0f;
if (diffBounceNum >= 4)
pabsorb = 0.50f;
else if (diffBounceNum >= 3)
pabsorb = 0.25f;
else
pabsorb = 0.0f;
return pabsorb;
}
static inline float MonteCarloVariance(float3 avgColor, float sqrColor, int nSamples)
{
const float maxColor = fmax(avgColor.x, fmax(avgColor.y, avgColor.z));
const float fnSamples = ((float)(nSamples));
const float nSampleInv = 1.0f / fnSamples;
return fabs(sqrColor*nSampleInv - (maxColor*maxColor*nSampleInv*nSampleInv));
}
static inline float MonteCarloRelErr(float maxColor, float sqrColor, int nSamples)
{
const float fnSamples = ((float)(nSamples));
const float nSampleInv = 1.0f / fnSamples;
const float variance = fabs(sqrColor*nSampleInv - (maxColor*maxColor*nSampleInv*nSampleInv));
const float stdError = sqrt(variance);
return stdError / (fmax(maxColor, 0.00001f));
}
static inline float MonteCarloRelErr2(float3 avgColor, float sqrColor, int nSamples)
{
const float maxColor = fmax(avgColor.x, fmax(avgColor.y, avgColor.z));
return MonteCarloRelErr(maxColor, sqrColor, nSamples);
}
static inline float colorSquareMax3(float3 calcColor)
{
float3 calcColorSqr;
calcColorSqr.x = calcColor.x*calcColor.x;
calcColorSqr.y = calcColor.y*calcColor.y;
calcColorSqr.z = calcColor.z*calcColor.z;
return fmax(calcColorSqr.x, fmax(calcColorSqr.y, calcColorSqr.z));
}
static inline float colorSquareMax4(float4 calcColor)
{
float4 calcColorSqr;
calcColorSqr.x = calcColor.x*calcColor.x;
calcColorSqr.y = calcColor.y*calcColor.y;
calcColorSqr.z = calcColor.z*calcColor.z;
calcColorSqr.w = calcColor.w*calcColor.w;
return fmax(calcColorSqr.x, fmax(calcColorSqr.y, calcColorSqr.z));
}
// Unpolarized fresnel reflection term for dielectric materials
// this formula is simplified and should be checked
//
static inline float fresnelCoeffSimple(float cosThetaI, float a_eta)
{
float g = sqrt(a_eta*a_eta - 1.0f + cosThetaI * cosThetaI);
float t1 = (g - cosThetaI) / (g + cosThetaI);
float t2 = (cosThetaI * (g + cosThetaI) - 1) / (cosThetaI * (g - cosThetaI) + 1.0f);
return 0.5f * t1 * t1 * (1.0f + t2 * t2);
}
// The following functions calculate the reflected and refracted
// directions in addition to the fresnel coefficients. Based on PBRT
// and the paper "Derivation of Refraction Formulas" by Paul S. Heckbert.
//
static inline float fresnelDielectric(float cosTheta1, float cosTheta2, float etaExt, float etaInt)
{
float Rs = (etaExt * cosTheta1 - etaInt * cosTheta2) / (etaExt * cosTheta1 + etaInt * cosTheta2);
float Rp = (etaInt * cosTheta1 - etaExt * cosTheta2) / (etaInt * cosTheta1 + etaExt * cosTheta2);
return (Rs * Rs + Rp * Rp) / 2.0f;
}
static inline float fresnelConductor(float cosTheta, float eta, float roughness)
{
float tmp = (eta*eta + roughness*roughness) * (cosTheta * cosTheta);
float rParl2 = (tmp - (eta * (2.0f * cosTheta)) + 1.0f) / (tmp + (eta * (2.0f * cosTheta)) + 1.0f);
float tmpF = eta*eta + roughness*roughness;
float rPerp2 = (tmpF - (eta * (2.0f * cosTheta)) + (cosTheta*cosTheta)) / (tmpF + (eta * (2.0f * cosTheta)) + (cosTheta*cosTheta));
return (rParl2 + rPerp2) / 2.0f;
}
static inline float fresnelReflectionCoeff(float cosTheta1, float etaExt, float etaInt)
{
// Swap the indices of refraction if the interaction starts
// at the inside of the object
//
if (cosTheta1 < 0.0f)
{
float temp = etaInt;
etaInt = etaExt;
etaExt = temp;
}
// Using Snell's law, calculate the sine of the angle
// between the transmitted ray and the surface normal
//
float sinTheta2 = etaExt / etaInt * sqrt(fmax(0.0f, 1.0f - cosTheta1*cosTheta1));
if (sinTheta2 > 1.0f)
return 1.0f; // Total internal reflection!
// Use the sin^2+cos^2=1 identity - max() guards against
// numerical imprecision
//
float cosTheta2 = sqrt(fmax(0.0f, 1.0f - sinTheta2*sinTheta2));
// Finally compute the reflection coefficient
//
return fresnelDielectric(fabs(cosTheta1), cosTheta2, etaInt, etaExt);
}
static inline float fresnelReflectionCoeffMentalLike(float cosTheta, float refractIOR)
{
return fresnelReflectionCoeff(fabs(cosTheta), 1.0f, refractIOR);
}
static inline float contribFunc(float3 color)
{
return fmax(0.33334f*(color.x + color.y + color.z), 0.0f);
}
static inline int packXY1616(int x, int y) { return (y << 16) | (x & 0x0000FFFF); }
// CPU and CUDA only code
//
#ifndef OCL_COMPILER
IDH_CALL float3 clamp3(float3 x, float a, float b) { return make_float3(fmin(fmax(x.x, a), b), fmin(fmax(x.y, a), b), fmin(fmax(x.z, a), b)); }
static unsigned short MortonTable256Host[] =
{
0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015,
0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055,
0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115,
0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155,
0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415,
0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455,
0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515,
0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555,
0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015,
0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055,
0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115,
0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155,
0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415,
0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455,
0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515,
0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555,
0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015,
0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055,
0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115,
0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155,
0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415,
0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455,
0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515,
0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555,
0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015,
0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055,
0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115,
0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155,
0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415,
0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455,
0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515,
0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555
};
static inline uint ZIndexHost(ushort x, ushort y)
{
return MortonTable256Host[y >> 8] << 17 |
MortonTable256Host[x >> 8] << 16 |
MortonTable256Host[y & 0xFF] << 1 |
MortonTable256Host[x & 0xFF];
}
static inline uint HostIndexZBlock2D(int x, int y, int pitch)
{
uint zOrderX = x % Z_ORDER_BLOCK_SIZE;
uint zOrderY = y % Z_ORDER_BLOCK_SIZE;
uint zIndex = ZIndexHost(zOrderX, zOrderY);
uint wBlocks = pitch / Z_ORDER_BLOCK_SIZE;
uint blockX = x / Z_ORDER_BLOCK_SIZE;
uint blockY = y / Z_ORDER_BLOCK_SIZE;
return (blockX + (blockY)*(wBlocks))*Z_ORDER_BLOCK_SIZE*Z_ORDER_BLOCK_SIZE + zIndex;
}
static void ImageZBlockMemToRowPitch(const float4* inData, float4* outData, int w, int h)
{
#pragma omp parallel for
for (int y = 0; y<h; y++)
{
for (int x = 0; x<w; x++)
{
int indexSrc = HostIndexZBlock2D(x, y, w);
int indexDst = Index2D(x, y, w);
outData[indexDst] = inData[indexSrc];
}
}
}
#endif
#ifdef __CUDACC__
#undef ushort
#undef uint
#endif
#define PREFIX_SUMM_MACRO(idata,odata,l_Data,_bsize) \
{ \
uint pos = 2 * LOCAL_ID_X - (LOCAL_ID_X & (_bsize - 1)); \
l_Data[pos] = 0; \
pos += _bsize; \
l_Data[pos] = idata; \
\
for (uint offset = 1; offset < _bsize; offset <<= 1) \
{ \
SYNCTHREADS_LOCAL; \
uint t = l_Data[pos] + l_Data[pos - offset]; \
SYNCTHREADS_LOCAL; \
l_Data[pos] = t; \
} \
\
odata = l_Data[pos]; \
} \
enum CLEAR_FLAGS{ CLEAR_MATERIALS = 1,
CLEAR_GEOMETRY = 2,
CLEAR_LIGHTS = 4,
CLEAR_TEXTURES = 8,
CLEAR_CUSTOM_DATA = 16,
CLEAR_ALL = CLEAR_MATERIALS | CLEAR_GEOMETRY | CLEAR_LIGHTS | CLEAR_TEXTURES | CLEAR_CUSTOM_DATA };
enum BVH_FLAGS { BVH_ENABLE_SMOOTH_OPACITY = 1};
typedef struct GBuffer1T
{
float depth;
float3 norm;
float4 rgba;
int matId;
float coverage;
} GBuffer1;
typedef struct GBuffer2T
{
float2 texCoord;
int objId;
int instId;
} GBuffer2;
typedef struct GBufferAll
{
GBuffer1 data1;
GBuffer2 data2;
} GBufferAll;
static inline void initGBufferAll(__private GBufferAll* a_pElem)
{
a_pElem->data1.depth = 1e+6f;
a_pElem->data1.norm = make_float3(0, 0, 0);
a_pElem->data1.rgba = make_float4(0, 0, 0, 1);
a_pElem->data1.matId = -1;
a_pElem->data1.coverage = 0.0f;
a_pElem->data2.texCoord = make_float2(0, 0);
a_pElem->data2.objId = -1;
a_pElem->data2.instId = -1;
}
#define GBUFFER_SAMPLES 16
#define PMPIX_SAMPLES 256 // Production Mode Pixel Samples
static inline float4 packGBuffer1(GBuffer1 a_input)
{
float4 resColor;
unsigned int packedRGBX = RealColorToUint32(a_input.rgba);
const float clampedCoverage = fmin(fmax(a_input.coverage*255.0f, 0.0f), 255.0f);
const int compressedCoverage = ((int)(clampedCoverage)) << 24;
const int packedMIdAncCov = (a_input.matId & 0x00FFFFFF) | (compressedCoverage & 0xFF000000);
resColor.x = a_input.depth;
resColor.y = as_float(encodeNormal(a_input.norm));
resColor.z = as_float(packedMIdAncCov);
resColor.w = as_float(packedRGBX);
return resColor;
}
static inline GBuffer1 unpackGBuffer1(float4 a_input)
{
GBuffer1 res;
res.depth = a_input.x;
res.norm = decodeNormal(as_int(a_input.y));
res.matId = as_int(a_input.z) & 0x00FFFFFF;
const int compressedCoverage = (as_int(a_input.z) & 0xFF000000) >> 24;
res.coverage = ((float)compressedCoverage)*(1.0f / 255.0f);
unsigned int rgba = as_int(a_input.w);
res.rgba.x = (rgba & 0x000000FF)*(1.0f / 255.0f);
res.rgba.y = ((rgba & 0x0000FF00) >> 8)*(1.0f / 255.0f);
res.rgba.z = ((rgba & 0x00FF0000) >> 16)*(1.0f / 255.0f);
res.rgba.w = ((rgba & 0xFF000000) >> 24)*(1.0f / 255.0f);
return res;
}
static inline float4 packGBuffer2(GBuffer2 a_input)
{
float4 res;
res.x = a_input.texCoord.x;
res.y = a_input.texCoord.y;
res.z = as_float(a_input.objId);
res.w = as_float(a_input.instId);
return res;
}
static inline GBuffer2 unpackGBuffer2(float4 a_input)
{
GBuffer2 res;
res.texCoord.x = a_input.x;
res.texCoord.y = a_input.y;
res.objId = as_int(a_input.z);
res.instId = as_int(a_input.w);
return res;
}
static inline float projectedPixelSize(float dist, float FOV, float w, float h)
{
float ppx = (FOV / w)*dist;
float ppy = (FOV / h)*dist;
if (dist > 0.0f)
return 2.0f*fmax(ppx, ppy);
else
return 1000.0f;
}
static inline float surfaceSimilarity(float4 data1, float4 data2, const float MADXDIFF)
{
const float MANXDIFF = 0.15f;
float3 n1 = to_float3(data1);
float3 n2 = to_float3(data2);
float dist = length(n1 - n2);
if (dist >= MANXDIFF)
return 0.0f;
float d1 = data1.w;
float d2 = data2.w;
if (fabs(d1 - d2) >= MADXDIFF)
return 0.0f;
float normalSimilar = sqrt(1.0f - (dist / MANXDIFF));
float depthSimilar = sqrt(1.0f - fabs(d1 - d2) / MADXDIFF);
return normalSimilar * depthSimilar;
}
static inline float gbuffDiff(GBufferAll s1, GBufferAll s2, const float a_fov, float w, float h)
{
const float ppSize = projectedPixelSize(s1.data1.depth, a_fov, w, h);
const float surfaceSimilar = surfaceSimilarity(to_float4(s1.data1.norm, s1.data1.depth),
to_float4(s2.data1.norm, s2.data1.depth), ppSize*2.0f);
const float surfaceDiff = 1.0f - surfaceSimilar;
const float objDiff = (s1.data2.instId == s2.data2.instId && s1.data2.objId == s2.data2.objId) ? 0.0f : 1.0f;
const float matDiff = (s1.data1.matId == s2.data1.matId) ? 0.0f : 1.0f;
const float alphaDiff = fabs(s1.data1.rgba.w - s2.data1.rgba.w);
return surfaceDiff + objDiff + matDiff + alphaDiff;
}
static inline float gbuffDiffObj(GBufferAll s1, GBufferAll s2, const float a_fov, int w, int h)
{
const float objDiff = (s1.data2.instId == s2.data2.instId && s1.data2.objId == s2.data2.objId) ? 0.0f : 1.0f;
const float matDiff = (s1.data1.matId == s2.data1.matId) ? 0.0f : 1.0f;
return objDiff + matDiff;
}
// static inline int reverseBits(int a_input, int a_maxSize)
// {
// int maxBit = 0;
// while (a_maxSize >>= 1)
// ++maxBit;
//
// int result = 0;
//
// for (int i = 0; i < maxBit; i++)
// {
// const int j = maxBit - i - 1;
// const int inputMask = (0x00000001 << j);
// result |= ((a_input & inputMask) >> j) << i;
// }
//
// return result;
// }
enum PLAIN_LIGHT_TYPES {
PLAIN_LIGHT_TYPE_POINT_OMNI = 0,
PLAIN_LIGHT_TYPE_POINT_SPOT = 1,
PLAIN_LIGHT_TYPE_DIRECT = 2,
PLAIN_LIGHT_TYPE_SKY_DOME = 3,
PLAIN_LIGHT_TYPE_AREA = 4,
PLAIN_LIGHT_TYPE_SPHERE = 5,
PLAIN_LIGHT_TYPE_CYLINDER = 6,
PLAIN_LIGHT_TYPE_MESH = 7,
};
enum PLAIN_LIGHT_FLAGS{
DISABLE_SAMPLING = 1,
SEPARATE_SKY_LIGHT_ENVIRONMENT = 2,
SKY_LIGHT_USE_PEREZ_ENVIRONMENT = 4,
AREA_LIGHT_SKY_PORTAL = 8,
LIGHT_HAS_IES = 16, ///< have spherical distribution mask around light
LIGHT_IES_POINT_AREA = 32, ///< apply IES honio from the center of light always.
LIGHT_DO_NOT_SAMPLE_ME = 64, ///< zero selection probability. never sample it.
};
enum SKY_PORTAL_COLOR_SOURCE { SKY_PORTAL_SOURCE_ENVIRONMENT = 1,
SKY_PORTAL_SOURCE_SKYLIGHT = 2,
SKY_PORTAL_SOURCE_CUSTOM = 3
};
static inline float3 triBaricentrics3(float3 ray_pos, float3 ray_dir, float3 A_pos, float3 B_pos, float3 C_pos)
{
const float3 edge1 = B_pos - A_pos;
const float3 edge2 = C_pos - A_pos;
const float3 pvec = cross(ray_dir, edge2);
const float det = dot(edge1, pvec);
const float inv_det = 1.0f / det;
const float3 tvec = ray_pos - A_pos;
const float v = dot(tvec, pvec)*inv_det;
const float3 qvec = cross(tvec, edge1);
const float u = dot(ray_dir, qvec)*inv_det;
const float t = dot(edge2, qvec)*inv_det;
return make_float3(u, v, t);
}
typedef struct ShadeContextT
{
float3 wp; ///< world pos
//float3 lp; ///< local pos
float3 l; ///< direction to light
float3 v; ///< view vector
float3 n; ///< smooth normal (for shading and new rays offsets)
float3 fn; ///< flat normal (for bump mapping and tangent space transform)
float3 tg; ///< tangent (for bump mapping and tangent space transform)
float3 bn; ///< binormal (for bump mapping and tangent space transform)
float2 tc; ///< tex coord (0);
//float2 tc1; ///< tex coord (1);
bool hfi; ///< Hit.From.Inside. if hit surface from the inside of the object that have glass or SSS material
} ShadeContext;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define MAXPROCTEX 16
#define F4_PROCTEX_SIZE 12
/**
\brief this structure will store results of procedural texture kernel execution.
*/
typedef struct ProcTextureListT
{
int currMaxProcTex;
int id_f4 [MAXPROCTEX];
float3 fdata4[MAXPROCTEX];
} ProcTextureList;
static inline void InitProcTextureList(__private ProcTextureList* a_pList)
{
a_pList->currMaxProcTex = 0;
a_pList->id_f4[0] = INVALID_TEXTURE;
}
static inline void WriteProcTextureList(__global float4* fdata, int tid, int size, __private const ProcTextureList* a_pList)
{
__global int* idata = (__global int*)fdata;
if(a_pList->currMaxProcTex == 0)
{
idata[tid] = INVALID_TEXTURE;
return;
}
const int finalProcTex = (a_pList->currMaxProcTex > MAXPROCTEX) ? MAXPROCTEX : a_pList->currMaxProcTex;
for(int i=0;i<finalProcTex;i++)
idata[tid + size * i] = a_pList->id_f4[i];
if(finalProcTex < MAXPROCTEX)
idata[tid + size * finalProcTex] = INVALID_TEXTURE; // list end
#ifdef OCL_COMPILER
for(int i=0;i<finalProcTex;i+=2)
{
const float4 h1 = to_float4(a_pList->fdata4[i+0], 0.0f);
const float4 h2 = to_float4(a_pList->fdata4[i+1], 0.0f);
float8 data = {h1.x, h1.y, h1.z, h1.w,
h2.x, h2.y, h2.z, h2.w,};
const int offset = (tid + size * (i/2 + MAXPROCTEX/4));
vstore_half8(data, 0, (__global half*)(fdata + offset) );
}
#endif
}
static inline void ReadProcTextureList(__global float4* fdata, int tid, int size,
__private ProcTextureList* a_pList)
{
if (fdata == 0)
return;
__global int* idata = (__global int*)fdata;
int currMaxProcTex;
for(currMaxProcTex = 0; currMaxProcTex < MAXPROCTEX; currMaxProcTex++)
{
const int texId = idata[tid + size * currMaxProcTex];
a_pList->id_f4[currMaxProcTex] = texId;
if(texId == INVALID_TEXTURE)
break;
}
#ifdef OCL_COMPILER
for(int i=0;i<currMaxProcTex;i+=2)
{
const int offset = (tid + size * (i/2 + MAXPROCTEX/4));
const float8 data = vload_half8(0, (__global half*)(fdata + offset));
a_pList->fdata4[i+0] = to_float3(data.s0123);
a_pList->fdata4[i+1] = to_float3(data.s4567);
}
#endif
a_pList->currMaxProcTex = currMaxProcTex;
}
/**
\brief get color for precomputed procedural texture
\param a_texId - input tex id
\param a_pList - input ptl
\return texture color;
*/
static inline float4 readProcTex(int a_texId, const __private ProcTextureList* a_pList)
{
//for(int i=0; i<maxIter; i++)
//{
// if(a_texId == a_pList->id_f4[i])
// return to_float4(a_pList->fdata4[i], 0.0f);
//}
//
//return make_float4(1, 1, 1, -1.0f);
const int maxIter = (a_pList->currMaxProcTex < MAXPROCTEX) ? a_pList->currMaxProcTex : MAXPROCTEX; // min
float4 quad1 = make_float4(1, 1, 1, -1.0f);
quad1 = (0 < maxIter && a_texId == a_pList->id_f4[0]) ? to_float4(a_pList->fdata4[0], 0.0f) : quad1;
quad1 = (1 < maxIter && a_texId == a_pList->id_f4[1]) ? to_float4(a_pList->fdata4[1], 0.0f) : quad1;
quad1 = (2 < maxIter && a_texId == a_pList->id_f4[2]) ? to_float4(a_pList->fdata4[2], 0.0f) : quad1;
quad1 = (3 < maxIter && a_texId == a_pList->id_f4[3]) ? to_float4(a_pList->fdata4[3], 0.0f) : quad1;
float4 quad2 = make_float4(1, 1, 1, -1.0f);
quad2 = (4 < maxIter && a_texId == a_pList->id_f4[4]) ? to_float4(a_pList->fdata4[4], 0.0f) : quad2;
quad2 = (5 < maxIter && a_texId == a_pList->id_f4[5]) ? to_float4(a_pList->fdata4[5], 0.0f) : quad2;
quad2 = (6 < maxIter && a_texId == a_pList->id_f4[6]) ? to_float4(a_pList->fdata4[6], 0.0f) : quad2;
quad2 = (7 < maxIter && a_texId == a_pList->id_f4[7]) ? to_float4(a_pList->fdata4[7], 0.0f) : quad2;
const float4 quad12 = (quad1.w != -1.0f) ? quad1 : quad2;
float4 quad3 = make_float4(1, 1, 1, -1.0f);
quad3 = (8 < maxIter && a_texId == a_pList->id_f4[8]) ? to_float4(a_pList->fdata4[8], 0.0f) : quad3;
quad3 = (9 < maxIter && a_texId == a_pList->id_f4[9]) ? to_float4(a_pList->fdata4[9], 0.0f) : quad3;
quad3 = (10 < maxIter && a_texId == a_pList->id_f4[10]) ? to_float4(a_pList->fdata4[10], 0.0f) : quad3;
quad3 = (11 < maxIter && a_texId == a_pList->id_f4[11]) ? to_float4(a_pList->fdata4[11], 0.0f) : quad3;
float4 quad4 = make_float4(1, 1, 1, -1.0f);
quad4 = (12 < maxIter && a_texId == a_pList->id_f4[12]) ? to_float4(a_pList->fdata4[12], 0.0f) : quad4;
quad4 = (13 < maxIter && a_texId == a_pList->id_f4[13]) ? to_float4(a_pList->fdata4[13], 0.0f) : quad4;
quad4 = (14 < maxIter && a_texId == a_pList->id_f4[14]) ? to_float4(a_pList->fdata4[14], 0.0f) : quad4;
quad4 = (15 < maxIter && a_texId == a_pList->id_f4[15]) ? to_float4(a_pList->fdata4[15], 0.0f) : quad4;
const float4 quad34 = (quad3.w != -1.0f) ? quad3 : quad4;
return (quad12.w != -1.0f) ? quad12 : quad34;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct ShadowSampleT
{
float3 pos;
float3 color;
float pdf;
float maxDist;
float cosAtLight;
bool isPoint;
} ShadowSample;
static inline void WriteShadowSample(const __private ShadowSample* a_pSam, float a_lightProbSel, int a_lightOffset, int a_tid, int a_threadNum,
__global float4* a_out)
{
const float pdfAndIsPoint = a_pSam->isPoint ? (-1.0f)*a_pSam->pdf : a_pSam->pdf;
a_out[a_tid + a_threadNum*0] = make_float4(a_pSam->pos.x, a_pSam->pos.y, a_pSam->pos.z, pdfAndIsPoint);
a_out[a_tid + a_threadNum*1] = make_float4(a_pSam->color.x, a_pSam->color.y, a_pSam->color.z, a_pSam->maxDist);
a_out[a_tid + a_threadNum*2] = make_float4(a_pSam->cosAtLight, a_lightProbSel, as_float(a_lightOffset), 0);
}
static inline void ReadShadowSample(const __global float4* a_in, int a_tid, int a_threadNum,
__private ShadowSample* a_pSam, __private float* a_pLightProbSel, __private int* a_pLightOffset)
{
const float4 f0 = a_in[a_tid + a_threadNum*0];
const float4 f1 = a_in[a_tid + a_threadNum*1];
const float4 f2 = a_in[a_tid + a_threadNum*2];
a_pSam->pos.x = f0.x; a_pSam->pos.y = f0.y;
a_pSam->pos.z = f0.z; a_pSam->pdf = fabs(f0.w); a_pSam->isPoint = (f0.w <= 0); // this is ok, if pdf is 0, it can be only point light
a_pSam->color.x = f1.x; a_pSam->color.y = f1.y;
a_pSam->color.z = f1.z; a_pSam->maxDist = f1.w;
a_pSam->cosAtLight = f2.x; (*a_pLightProbSel) = f2.y;
(*a_pLightOffset) = as_int(f2.z);
}
/**
\brief Per ray accumulated (for all bounces) data.
*/
typedef struct ALIGN_S(16) PerRayAccT
{
float pdfGTerm; ///< accumulated G term equal to product of G(x1,x2,x3) for all bounces; for 3-Way we aqctually don't need it and mult it with "-1" to store first bounce specular flag from light direcction.
float pdfLightWP; ///< accumulated probability per projected solid angle for light path
float pdfCameraWP; ///< accumulated probability per projected solid angle for camera path
float pdfCamA0; ///< equal to pdfWP[0]*G[0] (if [0] means light)
} PerRayAcc;
static inline PerRayAcc InitialPerParAcc()
{
PerRayAcc res;
res.pdfGTerm = 1.0f;
res.pdfLightWP = 1.0f;
res.pdfCameraWP = 1.0f;
res.pdfCamA0 = 1.0f;
return res;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct SurfaceHitT
{
float3 pos;
float3 normal;
float3 flatNormal;
float3 tangent;
float3 biTangent;
float2 texCoord;
int matId;
float t;
float sRayOff;
bool hfi;
} SurfaceHit;
#define PV_PACK_VALID_FIELD 1
#define PV_PACK_WASSP_FIELD 2
#define PV_PACK_HITFI_FIELD 4 // Hit From Inside
#define PV_PACK_RCONN_FIELD 8 // Ready For Connect (pack this if capera path don't hit light but store camera vertex istead).
#define SURFACE_HIT_SIZE_IN_F4 4
static inline void WriteSurfaceHit(const __private SurfaceHit* a_pHit, int a_tid, int a_threadNum,
__global float4* a_out)
{
const float4 f1 = to_float4(a_pHit->pos, a_pHit->texCoord.x);
const float4 f2 = to_float4(a_pHit->normal, a_pHit->texCoord.y);
const float4 f3 = make_float4(as_float( encodeNormal(a_pHit->flatNormal)),
as_float( encodeNormal(a_pHit->tangent)),
as_float( encodeNormal(a_pHit->biTangent)),
as_float( a_pHit->matId)
);
// ignore (hit.t, hit.sRayOff) because bpt don't need them!
const int bit3 = a_pHit->hfi ? PV_PACK_HITFI_FIELD : 0;
const float4 f4 = make_float4(a_pHit->t, a_pHit->sRayOff, 0, as_float(bit3));
a_out[a_tid + 0*a_threadNum] = f1;
a_out[a_tid + 1*a_threadNum] = f2;
a_out[a_tid + 2*a_threadNum] = f3;
a_out[a_tid + 3*a_threadNum] = f4;
}
static inline void WriteSurfaceHitMatId(const int a_matId, int a_tid, int a_threadNum,
__global float4* a_out)
{
const float4 f3 = make_float4(0, 0, 0, as_float(a_matId));
a_out[a_tid + 2*a_threadNum] = f3;
}
static inline void ReadSurfaceHit(const __global float4* a_in, int a_tid, int a_threadNum,
__private SurfaceHit* a_pHit)
{
const float4 f1 = a_in[a_tid + 0*a_threadNum];
const float4 f2 = a_in[a_tid + 1*a_threadNum];
const float4 f3 = a_in[a_tid + 2*a_threadNum];
const float4 f4 = a_in[a_tid + 3*a_threadNum];
a_pHit->pos = to_float3 (f1); a_pHit->texCoord.x = f1.w;
a_pHit->normal = to_float3 (f2); a_pHit->texCoord.y = f2.w;
a_pHit->flatNormal = decodeNormal(as_int(f3.x));
a_pHit->tangent = decodeNormal(as_int(f3.y));
a_pHit->biTangent = decodeNormal(as_int(f3.z));
a_pHit->matId = as_int(f3.w);
a_pHit->t = f4.x;
a_pHit->sRayOff = f4.y;
const int flags = as_int(f4.w);
a_pHit->hfi = ((flags & PV_PACK_HITFI_FIELD) != 0);
}
static inline int ReadSurfaceHitMatId(const __global float4* a_in, int a_tid, int a_threadNum)
{
const float4 f3 = a_in[a_tid + 2*a_threadNum];
return as_int(f3.w);
}
static inline float3 ReadSurfaceHitPos(const __global float4* a_in, int a_tid, int a_threadNum)
{
return to_float3(a_in[a_tid + 0*a_threadNum]);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
enum PLAIN_MAT_TYPES {
PLAIN_MAT_CLASS_PHONG_SPECULAR = 0,
PLAIN_MAT_CLASS_BLINN_SPECULAR = 1, // Micro Facet Torrance Sparrow model with Blinn distribution
PLAIN_MAT_CLASS_PERFECT_MIRROR = 2,
PLAIN_MAT_CLASS_THIN_GLASS = 3,
PLAIN_MAT_CLASS_GLASS = 4,
PLAIN_MAT_CLASS_TRANSLUCENT = 5,
PLAIN_MAT_CLASS_SHADOW_MATTE = 6,
PLAIN_MAT_CLASS_LAMBERT = 7,
PLAIN_MAT_CLASS_OREN_NAYAR = 8,
PLAIN_MAT_CLASS_BLEND_MASK = 9,
PLAIN_MAT_CLASS_EMISSIVE = 10,
PLAIN_MAT_CLASS_VOLUME_PERLIN = 11,
PLAIN_MAT_CLASS_SSS = 12
};
enum PLAIN_MAT_FLAGS{
PLAIN_MATERIAL_IS_LIGHT = 1,
PLAIN_MATERIAL_CAST_CAUSTICS = 2,
PLAIN_MATERIAL_HAS_DIFFUSE = 4,
PLAIN_MATERIAL_HAS_TRANSPARENCY = 8,
PLAIN_MATERIAL_INVERT_NMAP_X = 16,
PLAIN_MATERIAL_INVERT_NMAP_Y = 32,
PLAIN_MATERIAL_INVERT_SWAP_NMAP_XY = 64,
PLAIN_MATERIAL_INVERT_HEIGHT = 128,
PLAIN_MATERIAL_SKIP_SHADOW = 256,
PLAIN_MATERIAL_FORBID_EMISSIVE_GI = 512,
PLAIN_MATERIAL_SKIP_SKY_PORTAL = 1024,
PLAIN_MATERIAL_EMISSION_FALOFF = 2048,
// This flag marks node as a real blend of different materials.
// It used for blending emissive properties and normal maps.
//
PLAIN_MATERIAL_SURFACE_BLEND = 4096,
PLAIN_MATERIAL_HAVE_BTDF = 8192,
PLAIN_MATERIAL_INVIS_LIGHT = 16384,
PLAIN_MATERIAL_CAN_SAMPLE_REFL_ONLY = 32768,
PLAIN_MATERIAL_HAVE_PROC_TEXTURES = 32768*2,
PLAIN_MATERIAL_LOCAL_AO1 = 32768*4,
PLAIN_MATERIAL_LOCAL_AO2 = 32768*8,
PLAIN_MATERIAL_CAMERA_MAPPED_REFL = 32768*16,
PLAIN_MATERIAL_EMISSIVE_SHADOW_CATCHER = 32768*32,
};
#define PLAIN_MATERIAL_DATA_SIZE 192
#define PLAIN_MATERIAL_CUSTOM_DATA_SIZE 80
#define MIX_TREE_MAX_DEEP 7
struct PlainMaterialT
{
float data[PLAIN_MATERIAL_DATA_SIZE];
};
typedef struct PlainMaterialT PlainMaterial;
// emissive component, always present in material to speed-up code
//
#define EMISSIVE_COLORX_OFFSET 4
#define EMISSIVE_COLORY_OFFSET 5
#define EMISSIVE_COLORZ_OFFSET 6
#define EMISSIVE_TEXID_OFFSET 7
#define EMISSIVE_TEXMATRIXID_OFFSET 8
#define EMISSIVE_LIGHTID_OFFSET 9
#define OPACITY_TEX_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+1)
#define OPACITY_TEX_MATRIX (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+2)
#define NORMAL_TEX_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+3)
#define NORMAL_TEX_MATRIX (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+4)
#define EMISSIVE_BLEND_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+5)
#define PARALLAX_HEIGHT (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+6)
#define EMISSIVE_SAMPLER_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+8)
#define NORMAL_SAMPLER_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+20)
#define OPACITY_SAMPLER_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+32)
// #define PROC_TEX1_F4_HEAD_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+44) // FREE SLOT!
// #define PROC_TEX2_F4_HEAD_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+45) // FREE SLOT!
// #define PROC_TEX3_F4_HEAD_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+46) // FREE SLOT!
// #define PROC_TEX4_F4_HEAD_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+47) // FREE SLOT!
// #define PROC_TEX5_F4_HEAD_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+48) // FREE SLOT!
#define PROC_TEX_TABLE_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+49)
#define PROC_TEX_AO_TYPE (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+50)
#define PROC_TEX_AO_SAMPLER (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+52)
#define PROC_TEX_TEX_ID (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+64)
#define PROC_TEXMATRIX_ID (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+65)
#define PROC_TEX_AO_LENGTH (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+66)
#define PROC_TEX_AO_TYPE2 (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+67)
#define PROC_TEX_AO_SAMPLER2 (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+68)
#define PROC_TEX_TEX_ID2 (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+80)
#define PROC_TEXMATRIX_ID2 (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+81)
#define PROC_TEX_AO_LENGTH2 (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+82)
#define PROC_TEX1_F4_HEAD_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+83)
#define PROC_TEXN_F4_HEAD_OFFSET (PLAIN_MATERIAL_CUSTOM_DATA_SIZE+99)
enum AO_TYPES { AO_TYPE_NONE = 0, AO_TYPE_UP = 1, AO_TYPE_DOWN = 2, AO_TYPE_BOTH = 4 };
#define PLAIN_MAT_TYPE_OFFSET 0
#define PLAIN_MAT_FLAGS_OFFSET 1
#define PLAIN_MAT_COMPONENTS_OFFSET 2
static inline int materialGetType (__global const PlainMaterial* a_pMat) { return as_int(a_pMat->data[PLAIN_MAT_TYPE_OFFSET]); }
static inline int materialGetFlags (__global const PlainMaterial* a_pMat) { return as_int(a_pMat->data[PLAIN_MAT_FLAGS_OFFSET]); }
static inline bool materialCastCaustics (__global const PlainMaterial* a_pMat) { return (as_int(a_pMat->data[PLAIN_MAT_FLAGS_OFFSET]) & PLAIN_MATERIAL_CAST_CAUSTICS) != 0; }
static inline bool materialHasTransparency (__global const PlainMaterial* a_pMat) { return (as_int(a_pMat->data[PLAIN_MAT_FLAGS_OFFSET]) & PLAIN_MATERIAL_HAS_TRANSPARENCY) != 0; }
static inline bool materialIsSkyPortal (__global const PlainMaterial* a_pMat) { return (as_int(a_pMat->data[PLAIN_MAT_FLAGS_OFFSET]) & PLAIN_MATERIAL_SKIP_SKY_PORTAL) != 0; }
static inline bool materialIsInvisLight (__global const PlainMaterial* a_pMat) { return (as_int(a_pMat->data[PLAIN_MAT_FLAGS_OFFSET]) & PLAIN_MATERIAL_INVIS_LIGHT) != 0; }
static inline void PutProcTexturesIdListToMaterialHead(const ProcTextureList* a_pData, PlainMaterial* a_pMat)
{
for(int i=0;i<a_pData->currMaxProcTex;i++)
((int*)(a_pMat->data))[PROC_TEX1_F4_HEAD_OFFSET + i] = a_pData->id_f4[i];
for(int i=a_pData->currMaxProcTex; i<MAXPROCTEX; i++)
((int*)(a_pMat->data))[PROC_TEX1_F4_HEAD_OFFSET + i] = INVALID_TEXTURE;
}
static inline void GetProcTexturesIdListFromMaterialHead(__global const PlainMaterial* a_pMat, __private ProcTextureList* a_pData)
{
int currMaxProcTex;
for(currMaxProcTex = 0; currMaxProcTex < MAXPROCTEX; currMaxProcTex++)
{
const int texId = as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET + currMaxProcTex]);
a_pData->id_f4[currMaxProcTex] = texId;
if(texId == INVALID_TEXTURE)
break;
}
a_pData->currMaxProcTex = currMaxProcTex;
}
static inline bool materialHeadHaveTargetProcTex(__global const PlainMaterial* a_pMat, int a_texId)
{
return (as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+0]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+1]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+2]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+3]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+4]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+5]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+6]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+7]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+8]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+9]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+10]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+11]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+12]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+13]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+14]) == a_texId ||
as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET+15]) == a_texId);
}
static inline bool MaterialHaveAtLeastOneProcTex(__global const PlainMaterial* a_pMat)
{
return as_int(a_pMat->data[PROC_TEX1_F4_HEAD_OFFSET]) != INVALID_TEXTURE;
}
static inline bool MaterialHaveAO(__global const PlainMaterial* a_pMat)
{
return as_int(a_pMat->data[PROC_TEX_AO_TYPE]) != AO_TYPE_NONE;
}
static inline bool MaterialHaveAO2(__global const PlainMaterial* a_pMat)
{
return as_int(a_pMat->data[PROC_TEX_AO_TYPE]) != AO_TYPE_NONE && as_int(a_pMat->data[PROC_TEX_AO_TYPE2]) != AO_TYPE_NONE;
}
#define EVAL_FLAG_DEFAULT 0
#define EVAL_FLAG_DISABLE_CAUSTICS 1
#define EVAL_FLAG_FWD_DIR 2
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
\brief Select index proportional to piecewise constant function that is stored in a_accum[0 .. N-2]; Binary search version.
\param a_r - input random variable in rage [0, 1]
\param a_accum - input float array. it must be a result of prefix summ - i.e. it must be sorted.
\param N - size of extended array - i.e. a_accum[N-1] == summ(a_accum[0 .. N-2]).
\param pPDF - out parameter. probability of picking up found value.
\return found index
*/
static int SelectIndexPropToOpt(const float a_r, __global const float* a_accum, const int N,
__private float* pPDF)
{
int leftBound = 0;
int rightBound = N - 2; // because a_accum[N-1] == summ(a_accum[0 .. N-2]).
int counter = 0;
int currPos = -1;
const int maxStep = 50;
const float x = a_r*a_accum[N - 1];
while (rightBound - leftBound > 1 && counter < maxStep)
{
const int currSize = rightBound + leftBound;
const int currPos1 = (currSize % 2 == 0) ? (currSize + 1) / 2 : (currSize + 0) / 2;
const float a = a_accum[currPos1 + 0];
const float b = a_accum[currPos1 + 1];
if (a < x && x <= b)
{
currPos = currPos1;
break;
}
else if (x <= a)
rightBound = currPos1;
else if (x > b)
leftBound = currPos1;
counter++;
}
if (currPos < 0) // check the rest intervals
{
const float a1 = a_accum[leftBound + 0];
const float b1 = a_accum[leftBound + 1];
const float a2 = a_accum[rightBound + 0];
const float b2 = a_accum[rightBound + 1];
if (a1 < x && x <= b1)
currPos = leftBound;
if (a2 < x && x <= b2)
currPos = rightBound;
}
if (x == 0.0f)
currPos = 0;
else if (currPos < 0)
currPos = (rightBound + leftBound + 1) / 2;
(*pPDF) = (a_accum[currPos + 1] - a_accum[currPos]) / a_accum[N - 1];
return currPos;
}
/**
\brief search for for the lower bound (left range)
\param a - array
\param length - array size
\param left_range - value to search for
*/
static inline int binarySearchForLeftRange(__global const int2* a, int length, int left_range)
{
if (a[length - 1].x < left_range)
return -1;
int low = 0;
int high = length - 1;
while (low <= high)
{
int mid = low + ((high - low) / 2);
if (a[mid].x >= left_range)
high = mid - 1;
else //if(a[mid]<i)
low = mid + 1;
}
return high + 1;
}
/**
\brief search for for the upper bound (right range)
\param a - array
\param length - array size
\param left_range - value to search for
*/
static inline int binarySearchForRightRange(__global const int2* a, int length, int right_range)
{
if (a[0].x > right_range)
return -1;
int low = 0;
int high = length - 1;
while (low <= high)
{
int mid = low + ((high - low) / 2);
if (a[mid].x > right_range)
high = mid - 1;
else //if(a[mid]<i)
low = mid + 1;
}
return low - 1;
}
/**
\brief perform material id remap for instanced objects;
\param a_mId - input old material id
\param a_instId - input instance id
\param in_remapInst - array/table that maps instance id to remap list id
\param a_instTabSize - max instance id / size of 'in_remapInst' array
\param in_allMatRemapLists - all remap listss packed in to single array
\param in_remapTable - array/table that store offset inside 'in_allMatRemapLists' for each remap list which id we got from 'in_remapInst'
\papam a_remapTableSize - size of 'in_remapTable' array
\return new material id
*/
static inline int remapMaterialId(int a_mId, int a_instId,
__global const int* in_remapInst, int a_instTabSize,
__global const int* in_allMatRemapLists,
__global const int2* in_remapTable, int a_remapTableSize)
{
if (a_mId < 0 || a_instId < 0 || a_instId >= a_instTabSize || in_remapInst == 0 || in_allMatRemapLists == 0 || in_remapTable == 0)
return a_mId;
const int remapListId = in_remapInst[a_instId];
if(remapListId < 0 || remapListId >= a_remapTableSize) // || remapListId >= some size
return a_mId;
const int2 offsAndSize = in_remapTable[remapListId];
// int res = a_mId;
// for (int i = 0; i < offsAndSize.y; i++) // #TODO: change to binery search
// {
// int idRemapFrom = in_allMatRemapLists[offsAndSize.x + i * 2 + 0];
// int idRemapTo = in_allMatRemapLists[offsAndSize.x + i * 2 + 1];
//
// if (idRemapFrom == a_mId)
// {
// res = idRemapTo;
// break;
// }
// }
int low = 0;
int high = offsAndSize.y - 1;
while (low <= high)
{
const int mid = low + ((high - low) / 2);
const int idRemapFrom = in_allMatRemapLists[offsAndSize.x + mid * 2 + 0];
if (idRemapFrom >= a_mId)
high = mid - 1;
else //if(a[mid]<i)
low = mid + 1;
}
if (high+1 < offsAndSize.y)
{
const int idRemapFrom = in_allMatRemapLists[offsAndSize.x + (high + 1) * 2 + 0];
const int idRemapTo = in_allMatRemapLists[offsAndSize.x + (high + 1) * 2 + 1];
const int res = (idRemapFrom == a_mId) ? idRemapTo : a_mId;
return res;
}
else
return a_mId;
}
#define AO_RAYS_PACKED 4
static inline ushort4 compressShadow(float3 shadow)
{
ushort4 shadowCompressed;
shadowCompressed.x = (ushort)(65535.0f * shadow.x);
shadowCompressed.y = (ushort)(65535.0f * shadow.y);
shadowCompressed.z = (ushort)(65535.0f * shadow.z);
shadowCompressed.w = 0;
return shadowCompressed;
}
static inline float3 decompressShadow(ushort4 shadowCompressed)
{
const float invNormCoeff = 1.0f / 65535.0f;
return invNormCoeff*make_float3((float)shadowCompressed.x, (float)shadowCompressed.y, (float)shadowCompressed.z);
}
#define SPLIT_DL_BY_GRAMMAR true
//#define SBDPT_DEBUG_SPLIT 0
//#define SBDPT_DEBUG_DEPTH 4
//#define SBDPT_CHECK_BOUNCE 4
//#define SBDPT_INDIRECT_ONLY (void)
#endif
|
#include "WitnessSet.h"
|
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <algorithm>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h" // for stringify JSON
#include "rapidjson/writer.h" // for stringify JSON
#include "rapidjson/filestream.h" // wrapper of C stream for prettywriter as output
#include "Vector2d.h"
#include "Simulation.h"
#include "Environment.h"
#include "EnvironmentStore.h"
using namespace std;
//Just run it once!
int sample_number = 1;
int sample_method = 0;
//TODO Copied from ga - import properly
long long fitness_function(Simulation *s, Environment &env, int run_time) {
std::vector<long long> score_store;
for(int sample=0; sample<sample_number; sample++) {
s->reset();
if(env.init != NULL)
env.init();
s->setScore(0);
s->runSimulation(run_time);
if(env.destroy != NULL)
env.destroy();
long long score = s->getScore();
score_store.push_back(score);
}
//cout << endl;
sort(score_store.begin(), score_store.end());
return score_store[sample_method];
}
//hack
void environment_food_init_no_arg(void) {
// Init with a constant amount of food
environment_food_init(200);
}
int main() {
SwarmValues *v = new SwarmValues();
v->proj_weight = 0.4;
v->align_weight = 0.4;
v->noise_weight = 0.2;
Environment env;
env.onDraw = &environment_food_onDraw;
env.onFrame = &environment_food_onFrame;
env.init = &environment_food_init_no_arg;
env.destroy = &environment_food_destroy;
Simulation *s = new Simulation(100, v);
s->setEnvironment(&env);
clock_t time_sum = 0;
int count = 0;
clock_t start;
clock_t end;
cout << "start of sum: " << time_sum << endl;
while(true) {
start = clock() / (CLOCKS_PER_SEC / 1000);
cout << fitness_function(s, env, 1000);
end = clock() / (CLOCKS_PER_SEC / 1000);
clock_t time_taken = end-start;
time_sum += time_taken;
count++;
cout << time_sum/count << "ms\t\t(N=" << count << ") +" << time_taken << endl;
}
}
|
#include <assert.h>
#include "primitive.h"
#include "body.h"
#include "octree.h"
namespace physics
{
Primitive::Primitive(PRIMITIVE_TYPE t)
: id(0), tContact(-1), tProfile(-1), tPrimitive(t), body(0), parent(0), node(0), isStatic(false), isTrigger(false), interCount(0)
{
body = new RigidBody(this);
}
Primitive::~Primitive()
{
if (body != 0)
{
delete body;
body = 0;
}
}
void Primitive::refreshAABB()
{
assert("You shoule implement refreshAABB method!!!");
}
void Primitive::render()
{
#ifndef DISABLE_RENDER
assert("You shoule implement render method!!!");
#endif
}
void Primitive::updateTransform()
{
transform = body->transformMatrix;
}
Vector3 Primitive::getColumnVector(unsigned index) const
{
return transform.getColumnVector(index);
}
Vector3 Primitive::getTransformPos() const
{
return transform.getTransformPos();
}
void Primitive::setPosition(const Vector3 &position)
{
body->setPosition(position);
body->updateDerivedData();
updateTransform();
}
void Primitive::setOrientation(const Quaternion &direction)
{
body->setOrientation(direction);
body->updateDerivedData();
updateTransform();
}
Vector3 Primitive::getPosition()
{
return body->position;
}
Quaternion Primitive::getOrientation()
{
return body->orientation;
}
void Primitive::findFarthestPointInDirection(const Vector3 &dir, Vector3 &pointWorld)
{
pointWorld = Vector3::zero;
}
void Primitive::getAllPoints(std::vector<Vector3> &points)
{
}
Vector3 Primitive::getPointInWorldSpace(const Vector3 &point)
{
return body->getPosInWorldSpace(point);
}
Vector3 Primitive::getPointInBodySpace(const Vector3 &point)
{
return body->getPosInBodySpace(point);
}
}
|
#include "StdAfx.h"
#include "utilites\unittest.h"
#include "plot\range_test.h"
#include "plot\buffer_test.h"
|
// 30. Write a program in C++ to compute the total and average of four numbers.
#include <iostream>
using namespace std;
int main()
{
float n1,n2,n3,n4,tot,avrg;
cout<<" Input 1st two numbers:";
cin>> n1 >> n2;
cout<<" Input last two numbers:";
cin>> n3 >> n4;
tot=n1+n2+n3+n4;
avrg=tot/4;
cout<<" The total of four numbers is : "<< tot << endl;
cout<<" The average of four numbers is : "<< avrg << endl;
return 0;
}
|
#include "ibm.h"
#include "mem.h"
#include "video.h"
#include "vid_svga.h"
#include "vid_svga_render.h"
#include "vid_svga_render_remap.h"
void svga_render_null(svga_t *svga)
{
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
}
void svga_render_blank(svga_t *svga)
{
int x, xx;
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
for (x = 0; x < svga->hdisp; x++)
{
switch (svga->seqregs[1] & 9)
{
case 0:
for (xx = 0; xx < 9; xx++) ((uint32_t *)buffer32->line[svga->displine])[(x * 9) + xx + 32] = 0;
break;
case 1:
for (xx = 0; xx < 8; xx++) ((uint32_t *)buffer32->line[svga->displine])[(x * 8) + xx + 32] = 0;
break;
case 8:
for (xx = 0; xx < 18; xx++) ((uint32_t *)buffer32->line[svga->displine])[(x * 18) + xx + 32] = 0;
break;
case 9:
for (xx = 0; xx < 16; xx++) ((uint32_t *)buffer32->line[svga->displine])[(x * 16) + xx + 32] = 0;
break;
}
}
}
void svga_render_text_40(svga_t *svga)
{
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (svga->fullchange)
{
int offset = ((8 - svga->scrollcache) << 1) + 16;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
int x, xx;
int drawcursor;
uint8_t chr, attr, dat;
uint32_t charaddr;
int fg, bg;
int xinc = (svga->seqregs[1] & 1) ? 16 : 18;
for (x = 0; x < svga->hdisp; x += xinc)
{
uint32_t addr = svga->remap_func(svga, svga->ma) & svga->vram_display_mask;
drawcursor = ((svga->ma == svga->ca) && svga->con && svga->cursoron);
chr = svga->vram[addr];
attr = svga->vram[addr+1];
if (attr & 8) charaddr = svga->charsetb + (chr * 128);
else charaddr = svga->charseta + (chr * 128);
if (drawcursor)
{
bg = svga->pallook[svga->egapal[attr & 15]];
fg = svga->pallook[svga->egapal[attr >> 4]];
}
else
{
fg = svga->pallook[svga->egapal[attr & 15]];
bg = svga->pallook[svga->egapal[attr >> 4]];
if (attr & 0x80 && svga->attrregs[0x10] & 8)
{
bg = svga->pallook[svga->egapal[(attr >> 4) & 7]];
if (svga->blink & 16)
fg = bg;
}
}
dat = svga->vram[charaddr + (svga->sc << 2)];
if (svga->seqregs[1] & 1)
{
for (xx = 0; xx < 16; xx += 2)
p[xx] = p[xx + 1] = (dat & (0x80 >> (xx >> 1))) ? fg : bg;
}
else
{
for (xx = 0; xx < 16; xx += 2)
p[xx] = p[xx + 1] = (dat & (0x80 >> (xx >> 1))) ? fg : bg;
if ((chr & ~0x1F) != 0xC0 || !(svga->attrregs[0x10] & 4))
p[16] = p[17] = bg;
else
p[16] = p[17] = (dat & 1) ? fg : bg;
}
svga->ma += 4;
p += xinc;
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_text_80(svga_t *svga)
{
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (svga->fullchange)
{
int offset = (8 - svga->scrollcache) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
int x, xx;
int drawcursor;
uint8_t chr, attr, dat;
uint32_t charaddr;
int fg, bg;
int xinc = (svga->seqregs[1] & 1) ? 8 : 9;
for (x = 0; x < svga->hdisp; x += xinc)
{
uint32_t addr = svga->remap_func(svga, svga->ma) & svga->vram_display_mask;
drawcursor = ((svga->ma == svga->ca) && svga->con && svga->cursoron);
chr = svga->vram[addr];
attr = svga->vram[addr+1];
if (attr & 8) charaddr = svga->charsetb + (chr * 128);
else charaddr = svga->charseta + (chr * 128);
if (drawcursor)
{
bg = svga->pallook[svga->egapal[attr & 15]];
fg = svga->pallook[svga->egapal[attr >> 4]];
}
else
{
fg = svga->pallook[svga->egapal[attr & 15]];
bg = svga->pallook[svga->egapal[attr >> 4]];
if (attr & 0x80 && svga->attrregs[0x10] & 8)
{
bg = svga->pallook[svga->egapal[(attr >> 4) & 7]];
if (svga->blink & 16)
fg = bg;
}
}
dat = svga->vram[charaddr + (svga->sc << 2)];
if (svga->seqregs[1] & 1)
{
for (xx = 0; xx < 8; xx++)
p[xx] = (dat & (0x80 >> xx)) ? fg : bg;
}
else
{
for (xx = 0; xx < 8; xx++)
p[xx] = (dat & (0x80 >> xx)) ? fg : bg;
if ((chr & ~0x1F) != 0xC0 || !(svga->attrregs[0x10] & 4))
p[8] = bg;
else
p[8] = (dat & 1) ? fg : bg;
}
svga->ma += 4;
p += xinc;
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_text_80_ksc5601(svga_t *svga)
{
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (svga->fullchange)
{
int offset = (8 - svga->scrollcache) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
int x, xx;
int drawcursor;
uint8_t chr, attr, dat, nextchr;
uint32_t charaddr;
int fg, bg;
int xinc = (svga->seqregs[1] & 1) ? 8 : 9;
for (x = 0; x < svga->hdisp; x += xinc)
{
uint32_t addr = svga->remap_func(svga, svga->ma) & svga->vram_display_mask;
drawcursor = ((svga->ma == svga->ca) && svga->con && svga->cursoron);
chr = svga->vram[addr];
nextchr = svga->vram[addr + 8];
attr = svga->vram[addr + 1];
if (drawcursor)
{
bg = svga->pallook[svga->egapal[attr & 15]];
fg = svga->pallook[svga->egapal[attr >> 4]];
}
else
{
fg = svga->pallook[svga->egapal[attr & 15]];
bg = svga->pallook[svga->egapal[attr >> 4]];
if (attr & 0x80 && svga->attrregs[0x10] & 8)
{
bg = svga->pallook[svga->egapal[(attr >> 4) & 7]];
if (svga->blink & 16)
fg = bg;
}
}
if(x + xinc < svga->hdisp && (chr & (nextchr | svga->ksc5601_sbyte_mask) & 0x80))
{
if((chr == svga->ksc5601_udc_area_msb[0] || chr == svga->ksc5601_udc_area_msb[1]) && (nextchr > 0xa0 && nextchr < 0xff))
dat = fontdatksc5601_user[(chr == svga->ksc5601_udc_area_msb[1] ? 96 : 0) + (nextchr & 0x7F) - 0x20][svga->sc];
else if(nextchr & 0x80)
{
if(svga->ksc5601_swap_mode == 1 && (nextchr > 0xa0 && nextchr < 0xff))
{
if(chr >= 0x80 && chr < 0x99) chr += 0x30;
else if(chr >= 0xB0 && chr < 0xC9) chr -= 0x30;
}
dat = fontdatksc5601[((chr & 0x7F) << 7) | (nextchr & 0x7F)][svga->sc];
}
else
dat = 0xFF;
}
else
{
if (attr & 8) charaddr = svga->charsetb + (chr * 128);
else charaddr = svga->charseta + (chr * 128);
if ((svga->ksc5601_english_font_type >> 8) == 1) dat = fontdatksc5601[((svga->ksc5601_english_font_type & 0x7F) << 7) | (chr >> 1)][((chr & 1) << 4) | svga->sc];
else dat = svga->vram[charaddr + (svga->sc << 2)];
}
if (svga->seqregs[1] & 1)
{
for (xx = 0; xx < 8; xx++)
p[xx] = (dat & (0x80 >> xx)) ? fg : bg;
}
else
{
for (xx = 0; xx < 8; xx++)
p[xx] = (dat & (0x80 >> xx)) ? fg : bg;
if ((chr & ~0x1F) != 0xC0 || !(svga->attrregs[0x10] & 4))
p[8] = bg;
else
p[8] = (dat & 1) ? fg : bg;
}
svga->ma += 4;
p += xinc;
if(x + xinc < svga->hdisp && (chr & (nextchr | svga->ksc5601_sbyte_mask) & 0x80))
{
attr = svga->vram[((svga->ma << 1) + 1) & svga->vram_display_mask];
if (drawcursor)
{
bg = svga->pallook[svga->egapal[attr & 15]];
fg = svga->pallook[svga->egapal[attr >> 4]];
}
else
{
fg = svga->pallook[svga->egapal[attr & 15]];
bg = svga->pallook[svga->egapal[attr >> 4]];
if (attr & 0x80 && svga->attrregs[0x10] & 8)
{
bg = svga->pallook[svga->egapal[(attr >> 4) & 7]];
if (svga->blink & 16)
fg = bg;
}
}
if((chr == svga->ksc5601_udc_area_msb[0] || chr == svga->ksc5601_udc_area_msb[1]) && (nextchr > 0xa0 && nextchr < 0xff))
dat = fontdatksc5601_user[(chr == svga->ksc5601_udc_area_msb[1] ? 96 : 0) + (nextchr & 0x7F) - 0x20][svga->sc + 16];
else if(nextchr & 0x80)
{
dat = fontdatksc5601[((chr & 0x7F) << 7) | (nextchr & 0x7F)][svga->sc + 16];
}
else
dat = 0xFF;
if (svga->seqregs[1] & 1)
{
for (xx = 0; xx < 8; xx++)
p[xx] = (dat & (0x80 >> xx)) ? fg : bg;
}
else
{
for (xx = 0; xx < 8; xx++)
p[xx] = (dat & (0x80 >> xx)) ? fg : bg;
if ((chr & ~0x1F) != 0xC0 || !(svga->attrregs[0x10] & 4))
p[8] = bg;
else
p[8] = (dat & 1) ? fg : bg;
}
svga->ma += 4;
p += xinc;
x += xinc;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_2bpp_lowres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = ((8 - svga->scrollcache) << 1) + 16;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 8)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint8_t dat[2];
dat[0] = svga->vram[addr];
dat[1] = svga->vram[addr + 1];
svga->ma += 4;
svga->ma &= svga->vram_display_mask;
p[0] = p[1] = svga->pallook[svga->egapal[(dat[0] >> 6) & 3]];
p[2] = p[3] = svga->pallook[svga->egapal[(dat[0] >> 4) & 3]];
p[4] = p[5] = svga->pallook[svga->egapal[(dat[0] >> 2) & 3]];
p[6] = p[7] = svga->pallook[svga->egapal[dat[0] & 3]];
p[8] = p[9] = svga->pallook[svga->egapal[(dat[1] >> 6) & 3]];
p[10] = p[11] = svga->pallook[svga->egapal[(dat[1] >> 4) & 3]];
p[12] = p[13] = svga->pallook[svga->egapal[(dat[1] >> 2) & 3]];
p[14] = p[15] = svga->pallook[svga->egapal[dat[1] & 3]];
p += 16;
}
}
}
void svga_render_2bpp_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - svga->scrollcache) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
for (x = 0; x <= svga->hdisp; x += 8)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint8_t dat[2];
dat[0] = svga->vram[addr];
dat[1] = svga->vram[addr + 1];
svga->ma += 4;
svga->ma &= svga->vram_display_mask;
*p++ = svga->pallook[svga->egapal[(dat[0] >> 6) & 3]];
*p++ = svga->pallook[svga->egapal[(dat[0] >> 4) & 3]];
*p++ = svga->pallook[svga->egapal[(dat[0] >> 2) & 3]];
*p++ = svga->pallook[svga->egapal[dat[0] & 3]];
*p++ = svga->pallook[svga->egapal[(dat[1] >> 6) & 3]];
*p++ = svga->pallook[svga->egapal[(dat[1] >> 4) & 3]];
*p++ = svga->pallook[svga->egapal[(dat[1] >> 2) & 3]];
*p++ = svga->pallook[svga->egapal[dat[1] & 3]];
}
}
}
void svga_render_4bpp_lowres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = ((8 - svga->scrollcache) << 1) + 16;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 8)
{
uint8_t edat[4];
uint8_t dat;
uint32_t addr = svga->remap_func(svga, svga->ma);
*(uint32_t *)(&edat[0]) = *(uint32_t *)(&svga->vram[addr]);
svga->ma += 4;
svga->ma &= svga->vram_display_mask;
dat = edatlookup[edat[0] >> 6][edat[1] >> 6] | (edatlookup[edat[2] >> 6][edat[3] >> 6] << 2);
p[0] = p[1] = svga->pallook[svga->egapal[(dat >> 4) & svga->plane_mask]];
p[2] = p[3] = svga->pallook[svga->egapal[dat & svga->plane_mask]];
dat = edatlookup[(edat[0] >> 4) & 3][(edat[1] >> 4) & 3] | (edatlookup[(edat[2] >> 4) & 3][(edat[3] >> 4) & 3] << 2);
p[4] = p[5] = svga->pallook[svga->egapal[(dat >> 4) & svga->plane_mask]];
p[6] = p[7] = svga->pallook[svga->egapal[dat & svga->plane_mask]];
dat = edatlookup[(edat[0] >> 2) & 3][(edat[1] >> 2) & 3] | (edatlookup[(edat[2] >> 2) & 3][(edat[3] >> 2) & 3] << 2);
p[8] = p[9] = svga->pallook[svga->egapal[(dat >> 4) & svga->plane_mask]];
p[10] = p[11] = svga->pallook[svga->egapal[dat & svga->plane_mask]];
dat = edatlookup[edat[0] & 3][edat[1] & 3] | (edatlookup[edat[2] & 3][edat[3] & 3] << 2);
p[12] = p[13] = svga->pallook[svga->egapal[(dat >> 4) & svga->plane_mask]];
p[14] = p[15] = svga->pallook[svga->egapal[dat & svga->plane_mask]];
p += 16;
}
}
}
void svga_render_4bpp_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - svga->scrollcache) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
for (x = 0; x <= svga->hdisp; x += 8)
{
uint8_t edat[4];
uint8_t dat;
uint32_t addr = svga->remap_func(svga, svga->ma);
*(uint32_t *)(&edat[0]) = *(uint32_t *)(&svga->vram[addr]);
svga->ma += 4;
svga->ma &= svga->vram_display_mask;
dat = edatlookup[edat[0] >> 6][edat[1] >> 6] | (edatlookup[edat[2] >> 6][edat[3] >> 6] << 2);
*p++ = svga->pallook[svga->egapal[(dat >> 4) & svga->plane_mask]];
*p++ = svga->pallook[svga->egapal[dat & svga->plane_mask]];
dat = edatlookup[(edat[0] >> 4) & 3][(edat[1] >> 4) & 3] | (edatlookup[(edat[2] >> 4) & 3][(edat[3] >> 4) & 3] << 2);
*p++ = svga->pallook[svga->egapal[(dat >> 4) & svga->plane_mask]];
*p++ = svga->pallook[svga->egapal[dat & svga->plane_mask]];
dat = edatlookup[(edat[0] >> 2) & 3][(edat[1] >> 2) & 3] | (edatlookup[(edat[2] >> 2) & 3][(edat[3] >> 2) & 3] << 2);
*p++ = svga->pallook[svga->egapal[(dat >> 4) & svga->plane_mask]];
*p++ = svga->pallook[svga->egapal[dat & svga->plane_mask]];
dat = edatlookup[edat[0] & 3][edat[1] & 3] | (edatlookup[edat[2] & 3][edat[3] & 3] << 2);
*p++ = svga->pallook[svga->egapal[(dat >> 4) & svga->plane_mask]];
*p++ = svga->pallook[svga->egapal[dat & svga->plane_mask]];
}
}
}
void svga_render_8bpp_lowres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - (svga->scrollcache & 6)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 8)
{
uint32_t dat = *(uint32_t *)(&svga->vram[svga->ma & svga->vram_display_mask]);
p[0] = p[1] = svga->pallook[dat & 0xff];
p[2] = p[3] = svga->pallook[(dat >> 8) & 0xff];
p[4] = p[5] = svga->pallook[(dat >> 16) & 0xff];
p[6] = p[7] = svga->pallook[(dat >> 24) & 0xff];
svga->ma += 4;
p += 8;
}
}
else
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 8)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
p[0] = p[1] = svga->pallook[dat & 0xff];
p[2] = p[3] = svga->pallook[(dat >> 8) & 0xff];
p[4] = p[5] = svga->pallook[(dat >> 16) & 0xff];
p[6] = p[7] = svga->pallook[(dat >> 24) & 0xff];
svga->ma += 4;
p += 8;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_8bpp_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x += 8)
{
uint32_t dat = *(uint32_t *)(&svga->vram[svga->ma & svga->vram_display_mask]);
*p++ = svga->pallook[dat & 0xff];
*p++ = svga->pallook[(dat >> 8) & 0xff];
*p++ = svga->pallook[(dat >> 16) & 0xff];
*p++ = svga->pallook[(dat >> 24) & 0xff];
dat = *(uint32_t *)(&svga->vram[(svga->ma+4) & svga->vram_display_mask]);
*p++ = svga->pallook[dat & 0xff];
*p++ = svga->pallook[(dat >> 8) & 0xff];
*p++ = svga->pallook[(dat >> 16) & 0xff];
*p++ = svga->pallook[(dat >> 24) & 0xff];
svga->ma += 8;
}
}
else
{
for (x = 0; x <= svga->hdisp; x += 4)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
svga->ma += 4;
*p++ = svga->pallook[dat & 0xff];
*p++ = svga->pallook[(dat >> 8) & 0xff];
*p++ = svga->pallook[(dat >> 16) & 0xff];
*p++ = svga->pallook[(dat >> 24) & 0xff];
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_15bpp_lowres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - (svga->scrollcache & 6)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 4)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1)) & svga->vram_display_mask]);
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat >> 16];
*p++ = video_15to32[dat >> 16];
}
svga->ma += x << 1;
}
else
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 2)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat >> 16];
*p++ = video_15to32[dat >> 16];
svga->ma += 2 << 1;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_15bpp_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x += 8)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1)) & svga->vram_display_mask]);
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat >> 16];
dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1) + 4) & svga->vram_display_mask]);
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat >> 16];
dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1) + 8) & svga->vram_display_mask]);
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat >> 16];
dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1) + 12) & svga->vram_display_mask]);
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat >> 16];
}
svga->ma += x << 1;
}
else
{
for (x = 0; x <= svga->hdisp; x += 2)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
*p++ = video_15to32[dat & 0xffff];
*p++ = video_15to32[dat >> 16];
svga->ma += 4;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_16bpp_lowres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - (svga->scrollcache & 6)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 2)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1)) & svga->vram_display_mask]);
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat >> 16];
*p++ = video_16to32[dat >> 16];
}
svga->ma += x << 1;
}
else
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 2)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat >> 16];
*p++ = video_16to32[dat >> 16];
svga->ma += 2 << 1;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_16bpp_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x += 8)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1)) & svga->vram_display_mask]);
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat >> 16];
dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1) + 4) & svga->vram_display_mask]);
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat >> 16];
dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1) + 8) & svga->vram_display_mask]);
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat >> 16];
dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 1) + 12) & svga->vram_display_mask]);
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat >> 16];
}
svga->ma += x << 1;
}
else
{
for (x = 0; x <= svga->hdisp; x += 2)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
*p++ = video_16to32[dat & 0xffff];
*p++ = video_16to32[dat >> 16];
svga->ma += 4;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_24bpp_lowres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - (svga->scrollcache & 6)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
if (svga->swaprb) {
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x++)
{
uint32_t fg = svga->vram[svga->ma + 2] | (svga->vram[svga->ma + 1] << 8) | (svga->vram[svga->ma + 0] << 16);
svga->ma += 3;
svga->ma &= svga->vram_display_mask;
p[0] = p[1] = fg;
svga->ma += 12;
p += 8;
}
} else {
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x++)
{
uint32_t dat0 = *(uint32_t *)(&svga->vram[svga->ma & svga->vram_display_mask]);
uint32_t dat1 = *(uint32_t *)(&svga->vram[(svga->ma + 4) & svga->vram_display_mask]);
uint32_t dat2 = *(uint32_t *)(&svga->vram[(svga->ma + 8) & svga->vram_display_mask]);
p[0] = p[1] = dat0 & 0xffffff;
p[2] = p[3] = (dat0 >> 24) | ((dat1 & 0xffff) << 8);
p[4] = p[5] = (dat1 >> 16) | ((dat2 & 0xff) << 16);
p[6] = p[7] = dat2 >> 8;
svga->ma += 12;
p += 8;
}
}
}
else
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x += 4)
{
uint32_t dat0, dat1, dat2;
uint32_t addr;
addr = svga->remap_func(svga, svga->ma);
dat0 = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
addr = svga->remap_func(svga, svga->ma + 4);
dat1 = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
addr = svga->remap_func(svga, svga->ma + 8);
dat2 = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
p[0] = p[1] = dat0 & 0xffffff;
p[2] = p[3] = (dat0 >> 24) | ((dat1 & 0xffff) << 8);
p[4] = p[5] = (dat1 >> 16) | ((dat2 & 0xff) << 16);
p[6] = p[7] = dat2 >> 8;
svga->ma += 12;
p += 8;
}
}
}
}
void svga_render_24bpp_lowres_swaprb(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - (svga->scrollcache & 6)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x++)
{
uint32_t fg = svga->vram[svga->ma + 2] | (svga->vram[svga->ma + 1] << 8) | (svga->vram[svga->ma + 0] << 16);
svga->ma += 3;
svga->ma &= svga->vram_display_mask;
p[0] = p[1] = fg;
p += 2;
}
}
else
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x++)
{
uint32_t addr;
addr = svga->remap_func(svga, svga->ma);
uint32_t fg = svga->vram[addr + 2] | (svga->vram[addr + 1] << 8) | (svga->vram[addr + 0] << 16);
svga->ma += 3;
svga->ma &= svga->vram_display_mask;
p[0] = p[1] = fg;
p += 2;
}
}
}
}
void svga_render_24bpp_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x += 4)
{
uint32_t dat0 = *(uint32_t *)(&svga->vram[svga->ma & svga->vram_display_mask]);
uint32_t dat1 = *(uint32_t *)(&svga->vram[(svga->ma + 4) & svga->vram_display_mask]);
uint32_t dat2 = *(uint32_t *)(&svga->vram[(svga->ma + 8) & svga->vram_display_mask]);
*p++ = dat0 & 0xffffff;
*p++ = (dat0 >> 24) | ((dat1 & 0xffff) << 8);
*p++ = (dat1 >> 16) | ((dat2 & 0xff) << 16);
*p++ = dat2 >> 8;
svga->ma += 12;
}
}
else
{
for (x = 0; x <= svga->hdisp; x += 4)
{
uint32_t dat0, dat1, dat2;
uint32_t addr;
addr = svga->remap_func(svga, svga->ma);
dat0 = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
addr = svga->remap_func(svga, svga->ma + 4);
dat1 = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
addr = svga->remap_func(svga, svga->ma + 8);
dat2 = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
*p++ = dat0 & 0xffffff;
*p++ = (dat0 >> 24) | ((dat1 & 0xffff) << 8);
*p++ = (dat1 >> 16) | ((dat2 & 0xff) << 16);
*p++ = dat2 >> 8;
svga->ma += 12;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_24bpp_highres_swaprb(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t*)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t fg = svga->vram[svga->ma + 2] | (svga->vram[svga->ma + 1] << 8) | (svga->vram[svga->ma + 0] << 16);
svga->ma += 3;
svga->ma &= svga->vram_display_mask;
*p++ = fg;
}
}
else
{
for (x = 0; x <= svga->hdisp; x += 4)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t fg = svga->vram[addr + 2] | (svga->vram[addr + 1] << 8) | (svga->vram[addr + 0] << 16);
svga->ma += 3;
svga->ma &= svga->vram_display_mask;
*p++ = fg;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_32bpp_lowres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - (svga->scrollcache & 6)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x++)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 2)) & svga->vram_display_mask]);
*p++ = dat & 0xffffff;
*p++ = dat & 0xffffff;
}
svga->ma += x * 4;
}
else
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x++)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr]);
*p++ = dat & 0xffffff;
*p++ = dat & 0xffffff;
svga->ma += 4;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_32bpp_lowres_swaprb(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - (svga->scrollcache & 6)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x++)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 2)) & svga->vram_display_mask]);
dat = ((dat & 0xff0000) >> 16) | ((dat & 0x0000ff) << 16) | ((dat & 0x00ff00));
*p++ = dat & 0xffffff;
*p++ = dat & 0xffffff;
}
svga->ma += x * 4;
}
else
{
for (x = 0; x <= svga->hdisp << svga->horizontal_linedbl; x++)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr]);
dat = ((dat & 0xff0000) >> 16) | ((dat & 0x0000ff) << 16) | ((dat & 0x00ff00));
*p++ = dat & 0xffffff;
*p++ = dat & 0xffffff;
svga->ma += 4;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_32bpp_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 2)) & svga->vram_display_mask]);
*p++ = dat & 0xffffff;
}
svga->ma += x * 4;
}
else
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
*p++ = dat & 0xffffff;
svga->ma += 4;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_32bpp_highres_swaprb(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 2)) & svga->vram_display_mask]);
dat = ((dat & 0xff0000) >> 16) | ((dat & 0x0000ff) << 16) | ((dat & 0x00ff00));
*p++ = dat & 0xffffff;
}
svga->ma += x * 4;
}
else
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
dat = ((dat & 0xff0000) >> 16) | ((dat & 0x0000ff) << 16) | ((dat & 0x00ff00));
*p++ = dat & 0xffffff;
svga->ma += 4;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_ABGR8888_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 2)) & svga->vram_display_mask]);
*p++ = ((dat & 0xff0000) >> 16) | (dat & 0x00ff00) | ((dat & 0x0000ff) << 16);
}
svga->ma += x * 4;
}
else
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
*p++ = ((dat & 0xff0000) >> 16) | (dat & 0x00ff00) | ((dat & 0x0000ff) << 16);
svga->ma += 4;
}
}
svga->ma &= svga->vram_display_mask;
}
}
void svga_render_RGBA8888_highres(svga_t *svga)
{
uint32_t changed_addr = svga->remap_func(svga, svga->ma);
if (svga->changedvram[changed_addr >> 12] || svga->changedvram[(changed_addr >> 12) + 1] || svga->fullchange)
{
int x;
int offset = (8 - ((svga->scrollcache & 6) >> 1)) + 24;
uint32_t *p = &((uint32_t *)buffer32->line[svga->displine])[offset];
if (svga->firstline_draw == 4000)
svga->firstline_draw = svga->displine;
svga->lastline_draw = svga->displine;
if (!svga->remap_required)
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t dat = *(uint32_t *)(&svga->vram[(svga->ma + (x << 2)) & svga->vram_display_mask]);
*p++ = dat >> 8;
}
svga->ma += x * 4;
}
else
{
for (x = 0; x <= svga->hdisp; x++)
{
uint32_t addr = svga->remap_func(svga, svga->ma);
uint32_t dat = *(uint32_t *)(&svga->vram[addr & svga->vram_display_mask]);
*p++ = dat >> 8;
svga->ma += 4;
}
}
svga->ma &= svga->vram_display_mask;
}
}
|
/*
Author: Nayeemul Islam Swad
Idea:
- https://www.facebook.com/notes/facebook-hacker-cup/hacker-cup-2019-round-2-solutions/2860037857345430/
Note: The solution in the editorial uses flood-fill to find all the
connected components whereas the following code uses dsu.
*/
#include <bits/stdc++.h>
using namespace std;
#define debug(a) cerr << #a << ": " << a << endl
typedef long long ll;
typedef pair<int, int> ii;
#define x first
#define y second
const int N = 4e3 + 5;
const int M = 1e4 + 5;
int n, m;
int par[N];
int sz[N];
vector<int> terms[N];
int ans[N];
int parent(int i) {
if (i == par[i]) return i;
return par[i] = parent(par[i]);
}
void merge(int i, int j) {
i = parent(i);
j = parent(j);
if (i == j) return;
if (sz[i] < sz[j]) swap(i, j);
par[j] = i;
sz[i] += sz[j];
}
int main() {
#ifdef LOCAL
freopen("bitstrings_as_a_service.txt", "r", stdin);
freopen("out", "w", stdout);
#endif
int t;
cin >> t;
for (int cs = 1; cs <= t; cs++) {
// reset everything
iota(par, par + N, 0);
fill(sz, sz + N, 1);
for (int i = 0; i < N; i++) terms[i].clear();
memset(ans, 0, sizeof ans);
cin >> n >> m;
while (m--) {
int x, y;
scanf("%d %d", &x, &y);
for (int i = x, j = y; i < j; i++, j--) {
merge(i, j);
}
}
for (int i = 1; i <= n; i++) {
if (parent(i) == i) {
for (int sum = n / 2; sum > sz[i]; sum--)
if (terms[sum].empty() && !terms[sum - sz[i]].empty()) {
terms[sum] = terms[sum - sz[i]];
terms[sum].push_back(i);
}
if (terms[sz[i]].empty())
terms[sz[i]].push_back(i);
}
}
int sum = 0;
for (int i = 1; i <= n / 2; i++)
if (!terms[i].empty())
sum = i;
for (int i : terms[sum]) ans[i] = 1;
for (int i = 1; i <= n; i++)
ans[i] = ans[parent(i)];
printf("Case #%d: ", cs);
for (int i = 1; i <= n; i++) printf("%d", ans[i]);
printf("\n");
}
return 0;
}
|
/***************************************************************************
dialogomodificador.cpp - description
-------------------
begin : ago 2 2003
copyright : (C) 2003 by Oscar G. Duarte
email : ogduarte@ing.unal.edu.co
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "dialogomodificador.h"
BEGIN_EVENT_TABLE(DialogoModificador, wxDialog)
EVT_BUTTON(DLG_MODIFICADOR_BTN_OK, DialogoModificador::cerrarOk)
EVT_BUTTON(DLG_MODIFICADOR_BTN_CANCEL, DialogoModificador::cancelar)
EVT_BUTTON(DLG_MODIFICADOR_BTN_AYUDA, DialogoModificador::ayuda)
EVT_LISTBOX(DLG_MODIFICADOR_LISTBOX_MODIFICADOR, DialogoModificador::clickModificador)
END_EVENT_TABLE()
DialogoModificador::DialogoModificador(VariableLinguistica *var,
Proyecto *proy, wxWindow *parent,const wxString& title, wxHtmlHelpController *ayuda)
:wxDialog(parent,-1,title)
{
Proy=proy;
Ayuda=ayuda;
VarTemp=var;
Var=*VarTemp;
SetTitle(wxT("Autodefinir Variable Lingüística"));
ButtonOK =new wxButton(this,DLG_MODIFICADOR_BTN_OK, wxT("OK"));
ButtonCancelar =new wxButton(this,DLG_MODIFICADOR_BTN_CANCEL, wxT("Cancelar"));
ButtonAyuda =new wxButton (this,DLG_MODIFICADOR_BTN_AYUDA, wxT("Ayuda"));
StaticCadena =new wxStaticText(this,DLG_MODIFICADOR_STATIC_CADENA, wxT("Etiqueta"));
ListBoxModificador =new wxListBox (this,DLG_MODIFICADOR_LISTBOX_MODIFICADOR);
wxString cad;
Var.strEtiqueta(&cad);
StaticCadena->SetLabel(cad);
ListBoxModificador->Append(wxT("Sin Modificador"));
ListBoxModificador->Append(wxT("A lo sumo"));
ListBoxModificador->Append(wxT("Por lo menos"));
ListBoxModificador->Append(wxT("Nada"));
ListBoxModificador->Append(wxT("Cualquier cosa"));
ListBoxModificador->SetSelection(Var.Modificador);
wxBoxSizer *sizerEtiqueta = new wxBoxSizer(wxVERTICAL);
sizerEtiqueta->Add(StaticCadena, 0, wxALIGN_LEFT | wxALL, 5);
sizerEtiqueta->Add(ListBoxModificador, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerButInf = new wxBoxSizer(wxHORIZONTAL);
sizerButInf->Add(ButtonOK, 0, wxALIGN_CENTER | wxALL, 5);
sizerButInf->Add(ButtonCancelar, 0, wxALIGN_CENTER | wxALL, 5);
sizerButInf->Add(ButtonAyuda, 0, wxALIGN_CENTER | wxALL, 5);
wxBoxSizer *sizerTotal = new wxBoxSizer(wxVERTICAL);
sizerTotal->Add(sizerEtiqueta, 0, wxALIGN_CENTER | wxALL, 5);
sizerTotal->Add(sizerButInf, 0, wxALIGN_CENTER | wxALL, 5);
SetAutoLayout(TRUE);
SetSizer(sizerTotal);
sizerTotal->SetSizeHints(this);
sizerTotal->Fit(this);
// llenarCuadro();
}
DialogoModificador::~DialogoModificador()
{
}
void DialogoModificador::clickModificador(wxCommandEvent&)
{
Var.Modificador=ListBoxModificador->GetSelection();
wxString cad;
Var.strEtiqueta(&cad);
StaticCadena->SetLabel(cad);
}
void DialogoModificador::cerrarOk(wxCommandEvent&)
{
*VarTemp=Var;
Close();
}
void DialogoModificador::cancelar(wxCommandEvent&)
{
Close();
}
void DialogoModificador::ayuda(wxCommandEvent&)
{
Ayuda->Display(wxT("Edición de Modificadores Lingüísticos"));
}
|
#include "liststack.h"
// -------------------- //
//拷贝功能函数
void ListStack::copy(const ListStack& other)
{
top = 0;
ListNode *tmp = other.top;
ListNode *prenode;
while (tmp)
{
ListNode *newnode = new ListNode(tmp->data);
if (top == 0)
{
top = newnode;
}
else
{
prenode->next = newnode;
}
prenode = newnode;
tmp = tmp->next;
}
}
//清空栈函数
void ListStack::clear()
{
while (top)
{
ListNode *delnode = top;
top = top->next;
delete delnode;
}
}
//拷贝构造函数
ListStack::ListStack(const ListStack& other)
{
copy(other);
}
//析构函数
ListStack::~ListStack()
{
clear();
}
//赋值函数
ListStack& ListStack::operator=(const ListStack& other)
{
if (this != &other)
{
clear();
copy(other);
}
return *this;
}
//判栈空函数
bool ListStack::isempty()const
{
return top == 0;
}
//入栈函数
void ListStack::push(int value)
{
ListNode *newnode = new ListNode(value);
newnode->next = top;
top = newnode;
}
//出栈函数
bool ListStack::pop()
{
if (isempty())
{
return false;
}
ListNode *delnode = top;
top = top->next;
delete delnode;
return true;
}
//取栈顶元素
bool ListStack::get_top(int &value)const
{
if (isempty())
{
return false;
}
value = top->data;
return true;
}
|
#define NDEBUG
#include "common.h"
class ChainEnumerator {
public:
int n;
Board &board;
vector<vector<int>> paths;
vector<int> path;
int sum;
ChainEnumerator(int n, Board &board)
: n(n), board(board) {
}
void find() {
assert(paths.empty());
for (int i = 0; i < board.size(); i++) {
if (board[i] != EMPTY)
find_starting(i);
}
}
void find_starting(int pos) {
path.clear();
sum = 0;
Cell backup = board[pos];
assert(backup != EMPTY);
board[pos] = EMPTY;
rec(pos);
board[pos] = backup;
assert(sum == 0);
assert(path.empty());
}
void rec(int pos) {
path.push_back(pos);
vector<int> deltas = get_deltas(n, pos);
bool has_moves = false;
for (int delta : deltas) {
if (board[pos + delta] == EMPTY) continue;
if (board[pos + 2*delta] != EMPTY) continue;
has_moves = true;
Cell backup = board[pos + delta];
sum += backup;
board[pos + delta] = EMPTY;
rec(pos + 2*delta);
sum -= backup;
board[pos + delta] = backup;
}
if (path.size() >= 2) {
paths.push_back(path);
}
path.pop_back();
}
};
int sum(const vector<int> xs) {
int result = 0;
for (int x : xs) result += x;
return result;
}
vector<Cell> apply_path(Board &board, const vector<int> &path) {
vector<Cell> consumed;
assert(path.size() >= 2);
Cell moving_peg = board[path.front()];
assert(moving_peg != EMPTY);
board[path.front()] = EMPTY;
int sum = 0;
for (int i = 1; i < path.size(); i++) {
assert(board[path[i]] == EMPTY);
int x = (path[i - 1] + path[i]) / 2;
assert(board[x] != EMPTY);
consumed.push_back(board[x]);
board[x] = EMPTY;
}
board[path.back()] = moving_peg;
return consumed;
}
void undo_path(Board &board, const vector<int> &path, const vector<Cell> &consumed) {
assert(path.size() - 1 == consumed.size());
for (int i = 1; i < path.size(); i++) {
board[(path[i - 1] + path[i]) / 2] = consumed[i - 1];
}
Cell t = board[path.back()];
board[path.back()] = EMPTY;
board[path.front()] = t;
}
bool paths_commute(vector<int> path1, vector<int> path2) {
int k = path1.size();
for (int i = 1; i < k; i++)
path1.push_back((path1[i - 1] + path1[i]) / 2);
k = path2.size();
for (int i = 1; i < k; i++)
path2.push_back((path2[i - 1] + path2[i]) / 2);
//cerr << path1 << path2 << endl;
sort(path1.begin(), path1.end());
sort(path2.begin(), path2.end());
vector<int> intersection;
set_intersection(path1.begin(), path1.end(), path2.begin(), path2.end(), back_inserter(intersection));
return intersection.empty();
}
class Brute {
public:
int n;
Board board;
int score, best_score;
int cnt;
vector<vector<int>> paths, best_paths;
Brute(int n, const Board &board) : n(n), board(board) {
score = 0;
best_score = 0;
cnt = 0;
}
void rec() {
cnt++;
if (cnt > 50000000) {
cout << "EXIT!" << endl;
return;
}
//cerr << "rec" << paths << score << endl;
if (paths.size() == 1) {
cerr << paths << "..." << endl;
}
if (score > best_score) {
cerr << "improvement: " << score << paths << endl;
best_score = score;
best_paths = paths;
}
//Board backup = board;
ChainEnumerator ce(n, board);
ce.find();
//assert(board == backup);
for (const auto &path : ce.paths) {
if (!paths.empty()) {
if (paths.back().back() == path.front())
continue;
if (paths.back() < path && paths_commute(paths.back(), path))
continue;
}
auto consumed = apply_path(board, path);
int path_score = (path.size() - 1) * sum(consumed);
paths.push_back(path);
score += path_score;
rec();
score -= path_score;
paths.pop_back();
undo_path(board, path, consumed);
// cout << path << endl;
// cout << board_to_string(board);
// cout << board_to_string(backup);
// cout << "-------" << endl;
//assert(board == backup);
//board = backup;
}
}
};
vector<Move> path_to_moves(const vector<int> &path) {
assert(path.size() >= 2);
vector<Move> result;
for (int i = 1; i < path.size(); i++) {
int start = path[i - 1];
int delta = path[i] - start;
assert(delta % 2 == 0);
delta /= 2;
result.emplace_back(start, delta);
}
return result;
}
int main() {
int n = 10;
Board board;
for (int i = 0; i < n * n; i++) {
board.push_back(EMPTY);
if (rand() % 1000 < 400)
board.back() = rand() % 9 + 1;
}
// for (int i = 4; i < 6; i++)
// for (int j = 4; j < 6; j++)
// board[i * n + j ] = 5;
cout << board_to_string(board) << endl;
ChainEnumerator ce(n, board);
ce.find();
cout << ce.paths.size() << endl;
// for (auto path : ce.paths)
// cout << path << endl;
Brute b(n, board);
b.rec();
cout << b.best_score << endl;
cout << b.best_paths << endl;
cout << b.cnt << endl;
for (auto path: b.best_paths) {
auto moves = path_to_moves(path);
cout << moves_to_strings(n, moves) << endl;
for (auto move : moves) move.apply(board);
cout << board_to_string(board);
}
cout << "digraph {" << endl;
for (int i = 0; i < b.best_paths.size(); i++) {
cout << " " << i << "[label=\"" << i << " (" << (b.best_paths[i].size() - 1) << ")\"];" << endl;
for (int j = 0; j < i; j++) {
if (!paths_commute(b.best_paths[i], b.best_paths[j])) {
bool has_intermediate = false;
for (int k = j + 1; k < i; k++) {
if (!paths_commute(b.best_paths[i], b.best_paths[k]) && !paths_commute(b.best_paths[k], b.best_paths[j]))
has_intermediate = true;
}
if (!has_intermediate)
cout << " " << j << "->" << i << ";" << endl;
}
}
}
cout << "}" << endl;
//cout << paths_commute({1, 7, 11}, {2, 2}) << endl;
}
|
#include "StandState.h"
#include "../RunState/RunState.h"
#include "../../../../GameDefines/GameDefine.h"
StandState::StandState(GamePlayer* gp) : GameState(gp)
{
this->gp->setVx(0);
}
void StandState::handlerKeyBoard(std::map<int, bool> keys, float dt)
{
gp->setVy(Define::PLAYER_MAX_JUMP_VELOCITY);
if (keys[VK_LEFT] || keys[VK_RIGHT])
gp->setState(new RunState(gp));
}
PlayerState StandState::getState()
{
return PlayerState::Stand;
}
|
////////////////////////////////////////////
// Params.hh
//
// Header file for 'Params' class.
//
// Code for program TsArchive2Dsr
//
/////////////////////////////////////////////
#ifndef Params_hh
#define Params_hh
#include <vector>
using namespace std;
#include <iostream>
#include <cstdio>
#include <climits>
#include <cfloat>
// Class definition
class Params {
public:
// enum typedefs
typedef enum xmit_rcv_mode_t {
/// Single polarization (NEXRAD)
SP = 0,
/// Dual pol, alternating transmission, copolar receiver only
/// (CP2 SBand)
DP_ALT_HV_CO_ONLY = 1,
/// Dual pol, alternating transmission, co-polar and cross-polar
///receivers (SPOL with Mitch Switch and receiver in
/// switching mode, CHILL)
DP_ALT_HV_CO_CROSS = 2,
/// Dual pol, alternating transmission, fixed H and V receivers (SPOL
/// with Mitch Switch and receivers in fixed mode)
DP_ALT_HV_FIXED_HV = 3,
/// Dual pol, simultaneous transmission, fixed H and V receivers (NEXRAD
/// upgrade, SPOL with T and receivers in fixed mode)
DP_SIM_HV_FIXED_HV = 4,
/// Dual pol, simultaneous transmission, switching H and V receivers
/// (SPOL with T and receivers in switching mode)
DP_SIM_HV_SWITCHED_HV = 5,
/// Dual pol, H transmission, fixed H and V receivers (CP2 X band)
DP_H_ONLY_FIXED_HV = 6,
/// Staggered PRT (Eldora and DOWs)
SP_STAGGERED_2_3 = 7,
SP_STAGGERED_3_4 = 8,
SP_STAGGERED_4_5 = 9
} xmit_rcv_mode_t;
typedef enum debug_t {
DEBUG_OFF = 0,
DEBUG_NORM = 1,
DEBUG_VERBOSE = 2,
DEBUG_EXTRA_VERBOSE = 3
} debug_t;
typedef enum algorithm_t {
ALG_PP = 0,
ALG_FFT = 1
} algorithm_t;
typedef enum fft_window_t {
WINDOW_VONHANN = 0,
WINDOW_BLACKMAN = 1,
WINDOW_NONE = 2
} fft_window_t;
typedef enum moments_mode_t {
SINGLE_POL = 0,
DUAL_CP2_SBAND = 1,
DUAL_CP2_XBAND = 2
} moments_mode_t;
// struct typedefs
typedef struct radar_params_t {
xmit_rcv_mode_t xmit_rcv_mode;
double horiz_beam_width;
double vert_beam_width;
double pulse_width;
double wavelength_cm;
double xmit_peak_pwr;
} radar_params_t;
typedef struct receiver_t {
double noise_dBm; // as digitized, i.e. after gain applied
double noise_h_dBm;
double noise_v_dBm;
double gain;
double radar_constant;
} receiver_t;
typedef struct moments_params_t {
moments_mode_t mode;
int n_samples;
double start_range;
double gate_spacing;
algorithm_t algorithm;
fft_window_t window;
bool apply_clutter_filter;
double azimuth_resolution;
bool index_beams_in_azimuth;
} moments_params_t;
///////////////////////////
// Member functions
//
////////////////////////////////////////////
// Default constructor
//
Params();
////////////////////////////////////////////
// Destructor
//
~Params ();
///////////////////////////
// Data Members
//
debug_t debug;
double atmos_attenuation;
double dbz_calib_correction;
double zdr_correction;
double ldr_correction;
radar_params_t radar;
receiver_t hc_receiver;
receiver_t hx_receiver;
receiver_t vc_receiver;
receiver_t vx_receiver;
moments_params_t moments_params;
// Correction for system phidp
bool correct_for_system_phidp;
double system_phidp;
protected:
void setDefault();
private:
};
#endif
|
//
// Menu.h
// tower
//
// Created by wangpeng on 15/8/18.
//
//
#ifndef __tower__MenuScene__
#define __tower__MenuScene__
#include <stdio.h>
#include "MyLayer.h"
class MenuScene : public MyLayer
{
public:
virtual bool init() override;
virtual void notificationHandler(Ref* pSender) override;
CREATE_FUNC(MenuScene);
private:
};
#endif /* defined(__tower__MenuScene__) */
|
//
//
//
#include "TimeTest.h"
#include "LiquidCrystal.h"
#include "HIC.h"
#include "Mode.h"
extern LiquidCrystal lcd;
static void PrintTime ()
{
unsigned time = (unsigned)(millis () / 1000);
hic.print (F ("Time "));
hic.print (time);
hic.print ('\n');
lcd.setCursor (10, 1);
lcd.print (time);
}
void TimeTest::Activate ()
{
lcd.clear ();
lcd.print (F ("Print Time"));
Mode::Show ();
}
void TimeTest::Select ()
{
Mode::Next ();
}
void TimeTest::Execute ()
{
Mode::Execute (PrintTime);
}
|
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
struct People {
int id;
bool deleted;
People *left, *right;
People() {
id = 0;
deleted = false;
left = right = NULL;
}
People(int _id, People* _left = NULL, People* _right = NULL, bool _deleted = false)
: id(_id)
, left(_left)
, right(_right)
, deleted(_deleted) {}
};
const int maxn = 100005;
int n, m;
People p[maxn];
int main() {
// #define DEBUG
#ifdef DEBUG
freopen("d:\\.in", "r", stdin);
freopen("d:\\.out", "w", stdout);
#endif
cin >> n;
p[1].id = 1;
p[0].right = &p[1];
p[1].right = &p[n + 1];
p[1].left = &p[0];
p[n + 1].left = &p[1];
int id, direct;
for (int i = 2; i <= n; ++i) {
p[i].id = i;
cin >> id >> direct;
// 将i放在id的左边
if (direct == 0) {
p[i].left = p[id].left;
p[i].right = &p[id];
p[id].left->right = &p[i];
p[id].left = &p[i];
} else {
p[i].left = &p[id];
p[i].right = p[id].right;
p[id].right->left = &p[i];
p[id].right = &p[i];
}
}
cin >> m;
for (int i = 0; i < m; ++i) {
cin >> id;
p[id].deleted = true;
}
for (People* i = p[0].right; i != &p[n + 1]; i = i->right)
if (!i->deleted)
cout << i->id << " ";
return 0;
}
|
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> table;
for (int i = 0; i < strs.size(); i++) {
string key = strs[i];
sort(key.begin(), key.end());
table[key].push_back(strs[i]);
}
vector<vector<string>> result;
for (auto &itor: table) {
vector<string> temp(itor.second.begin(), itor.second.end());
result.push_back(temp);
}
return result;
}
};
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head||!head->next) {
return head;
}
ListNode dummy(-1);
ListNode *p1 =&dummy;
ListNode *p2 =&dummy;
ListNode *p3 =head;
int flag1 = 0;
int flag2 = 0;
int val = head->val;
head=head->next;
while (head) {
if (val==head->val) {
flag2 = 1;
}
else{
if (flag1 ==0&&flag2 ==0) {
p1 = p3;
p2 = p3;
flag1 =1;
}
else if (flag2==0) {
p2->next = p3;
p2 = p2->next;
}
val = head->val;
p3 = head;
flag2 = 0;
}
head = head->next;
}
if (flag1 ==0&&flag2 ==0) {
return p3;
}
else if(flag1 ==0&&flag2 ==1)
{
return head;
}
else if(flag1 ==1&&flag2 ==1)
{
p2->next = NULL;
return p1;
}
else
{
p2->next = p3;
return p1;
}
}
};
|
#ifndef SWIDGET_H
#define SWIDGET_H
#include <QWidget>
#include <QPushButton>
#include <QDebug>
#include <QString>
#include <QLabel>
#include <QLayout>
#include <QtMath>
#include <QtCore/qmath.h>
#include <QList>
#include <QFont>
#include <QRadioButton>
#include <QButtonGroup>
#include <QAction>
#include <QMenu>
#include <QCursor>
class SWidget : public QWidget
{
Q_OBJECT
public:
SWidget(QWidget *parent = 0);
~SWidget();
protected:
void contextMenuEvent(QContextMenuEvent *);
private:
bool Ans,em1,em2;
int pid; //用于保存上一次的进制
QLabel label1,label2,label3;
QMenu rmenu;
QAction gcopy,gstick;
QString ls1,gM;
QString num1,num2,goperator,cnum1,cnum2,cgoperator;
QButtonGroup bg1;
QRadioButton bsixteen,bten,beight,btwo;
QPushButton bMC,bMR,bMS,bMplus,bMminus;
QPushButton bback,bCE,bC;
QPushButton b7,b8,b9,bdivide;
QPushButton b4,b5,b6,bmultiply;
QPushButton b1,b2,b3,bminus,bequal,benter;
QPushButton bMod,b0,bplus;
QPushButton ba,bb,bc,bd,be,bf;
QPushButton brol,bror,bor,bxor,blsh,brsh,bnot,band;
QGridLayout glayout;
int gnummax();//用于计算当前进制允许的最大位数
int gcount();//计算式子的函数
int gstrtoint();//把算符字符串转换成我设的id
void fbsixteen();//特定按钮对应槽函数,下同
void fbten();
void fbeight();
void fbtwo();
void fbMC();
void fbMR();
void fbMS();
void fbMplus();
void fbMminus();
void fbback();
void fbCE();
void fbC();
void fb1();
void fb2();
void fb3();
void fb4();
void fb5();
void fb6();
void fb7();
void fb8();
void fb9();
void fb0();
void fba();
void fbb();
void fbc();
void fbd();
void fbe();
void fbf();
void fbdivide();
void fbmultiply();
void fbminus();
void fbplus();
void fbMod();
int fbequal();
void fbrol();
void fbror();
void fbor();
void fbxor();
void fblsh();
void fbrsh();
void fbnot();
void fband();
void fgcopy();
void fgstick();
void glayoutaddwidget();//处理界面的函数,仅在构造的时候调用,下同
void glabelset();
void gbuttongroupset();
void gbuttonset();
void gconnect();
void gsetshortcut();
void gnumset(const QString &n);//用于输入数字
void goperatorset(const QString &n);//用于输入算符
};
#endif // SWIDGET_H
|
#include<bits/stdc++.h>
using namespace std;
#define ll long long
map<ll, ll> mp;
int main()
{
ll m, n, i, j;
ll t;
ll sm=0 , mx=0, ans=0;
mp[0]=1;
cin>>n;
for(i=1; i<=n; i++)
{
cin>>m;
sm+=m;
cout<<mx<<" "<<sm<<endl;
mx=max(mx, mp[sm]);
cout<<ans<<" "<<i<<" "<<mx <<" "<<mp[sm]<<endl;
ans+=i-mx;
mp[sm]=i+1;
}
cout<<ans<<endl;
}
|
#include <Arduino.h>
#include <Wire.h>
#include "Preferences.h"
#include "M5Stack.h"
#include "math.h"
#include "bmm150.h"
#include "bmm150_defs.h"
class BMM150class
{
public:
Preferences prefs;
struct bmm150_dev dev;
bmm150_mag_data mag_offset;
bmm150_mag_data mag_scale; // for Soft iron distortion
bmm150_mag_data mag_max;
bmm150_mag_data mag_min;
bmm150_mag_data mag_chord; // for Soft iron distortion
private:
// int8_t i2c_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *read_data, uint16_t len);
// int8_t i2c_write(uint8_t dev_id, uint8_t reg_addr, uint8_t *read_data, uint16_t len);
int8_t bmm150_initialization();
void bmm150_offset_save();
void bmm150_offset_load();
public:
BMM150class();
void Init(void);
void bmm150_calibrate(uint32_t calibrate_time);
void getMagnetData(float *mx, float *my, float *mz);
void getMagnetOffset(float *mx, float *my, float *mz); // hard iron
void getMagnetScale(float *mx, float *my, float *mz); // soft iron
};
|
// Copyright 2020-2021 Russ 'trdwll' Treadwell <trdwll.com>. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Steam.h"
#include "SteamEnums.h"
#include "SteamStructs.h"
#include "UObject/NoExportTypes.h"
#include "SteamMatchmaking.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnFavoritesListAccountsUpdatedDelegate, ESteamResult, Result);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_SevenParams(FOnFavoritesListChangedDelegate, FString, IP, int32, QueryPort, int32, ConnectionPort, int32, AppID, TArray<ESteamFavoriteFlags>, Flags, bool, bAdd, FAccountID, AccountID);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FOnLobbyChatMsgDelegate, FSteamID, SteamIDLobby, FSteamID, SteamIDUser, ESteamChatEntryType, ChatEntryType, int32, ChatID);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FOnLobbyChatUpdateDelegate, FSteamID, SteamIDLobby, FSteamID, SteamIDUserChanged, FSteamID, SteamIDMakingChange, TArray<ESteamChatMemberStateChange>, ChatMemberStateChange);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnLobbyCreatedDelegate, ESteamResult, Result, FSteamID, SteamIDLobby);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnLobbyDataUpdateDelegate, FSteamID, SteamIDLobby, FSteamID, SteamIDMember, bool, bSuccess);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnLobbyEnterDelegate, FSteamID, SteamIDLobby, bool, bLocked, ESteamChatRoomEnterResponse, ChatRoomEnterResponse);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FOnLobbyGameCreatedDelegate, FSteamID, SteamIDLobby, FSteamID, SteamIDGameServer, FString, IP, int32, Port);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnLobbyInviteDelegate, FSteamID, SteamIDUser, FSteamID, SteamIDLobby, int32, GameID);
// DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnLobbyKickedDelegate); // This is currently unused
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnLobbyMatchListDelegate, int32, LobbiesMatching);
/**
* Functions for clients to access matchmaking services, favorites, and to operate on game lobbies.
* https://partner.steamgames.com/doc/api/ISteamMatchmaking
*/
UCLASS()
class STEAMBRIDGE_API USteamMatchmaking final : public UObject
{
GENERATED_BODY()
public:
USteamMatchmaking();
~USteamMatchmaking();
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore", meta = (DisplayName = "Steam Matchmaking", CompactNodeTitle = "SteamMatchmaking"))
static USteamMatchmaking* GetSteamMatchmaking() { return USteamMatchmaking::StaticClass()->GetDefaultObject<USteamMatchmaking>(); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
int32 AddFavoriteGame(int32 AppID, const FString& IP, int32 ConnPort, int32 QueryPort, const TArray<ESteamFavoriteFlags>& Flags, int32 TimeLastPlayedOnServer) const;
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void AddRequestLobbyListDistanceFilter(ESteamLobbyDistanceFilter LobbyDistanceFilter) { SteamMatchmaking()->AddRequestLobbyListDistanceFilter((ELobbyDistanceFilter)LobbyDistanceFilter); }
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void AddRequestLobbyListFilterSlotsAvailable(int32 SlotsAvailable) { SteamMatchmaking()->AddRequestLobbyListFilterSlotsAvailable(SlotsAvailable); }
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void AddRequestLobbyListNearValueFilter(const FString& KeyToMatch, int32 ValueToBeCloseTo) { SteamMatchmaking()->AddRequestLobbyListNearValueFilter(TCHAR_TO_UTF8(*KeyToMatch), ValueToBeCloseTo); }
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void AddRequestLobbyListNumericalFilter(const FString& KeyToMatch, int32 ValueToMatch, ESteamLobbyComparison ComparisonType) { SteamMatchmaking()->AddRequestLobbyListNumericalFilter(TCHAR_TO_UTF8(*KeyToMatch), ValueToMatch, (ELobbyComparison)((uint8)ComparisonType - 2)); }
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void AddRequestLobbyListResultCountFilter(int32 MaxResults) { SteamMatchmaking()->AddRequestLobbyListResultCountFilter(MaxResults); }
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void AddRequestLobbyListStringFilter(const FString& KeyToMatch, const FString& ValueToMatch, ESteamLobbyComparison ComparisonType) { SteamMatchmaking()->AddRequestLobbyListStringFilter(TCHAR_TO_UTF8(*KeyToMatch), TCHAR_TO_UTF8(*ValueToMatch), (ELobbyComparison)((uint8)ComparisonType - 2)); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
FSteamAPICall CreateLobby(ESteamLobbyType LobbyType = ESteamLobbyType::FriendsOnly, uint8 MaxMembers = 1) const { return SteamMatchmaking()->CreateLobby((ELobbyType)LobbyType, MaxMembers); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool DeleteLobbyData(FSteamID SteamIDLobby, const FString& Key) const { return SteamMatchmaking()->DeleteLobbyData(SteamIDLobby, TCHAR_TO_UTF8(*Key)); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool GetFavoriteGame(int32 GameIndex, int32& AppID, FString& IP, int32& ConnPort, int32& QueryPort, TArray<ESteamFavoriteFlags>& Flags, int32& TimeLastPlayedOnServer) const;
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
int32 GetFavoriteGameCount() const { return SteamMatchmaking()->GetFavoriteGameCount(); }
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
FSteamID GetLobbyByIndex(int32 LobbyIndex) const { return SteamMatchmaking()->GetLobbyByIndex(LobbyIndex).ConvertToUint64(); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
int32 GetLobbyChatEntry(FSteamID SteamIDLobby, int32 ChatID, FSteamID& SteamIDUser, FString& Message, ESteamChatEntryType& ChatEntryType) const;
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
FString GetLobbyData(FSteamID SteamIDLobby, const FString& Key) const { return UTF8_TO_TCHAR(SteamMatchmaking()->GetLobbyData(SteamIDLobby, TCHAR_TO_UTF8(*Key))); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool GetLobbyDataByIndex(FSteamID SteamIDLobby, int32 LobbyData, FString& Key, FString& Value) const;
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
int32 GetLobbyDataCount(FSteamID SteamIDLobby) const { return SteamMatchmaking()->GetLobbyDataCount(SteamIDLobby); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool GetLobbyGameServer(FSteamID SteamIDLobby, FString& GameServerIP, int32& GameServerPort, FSteamID& SteamIDGameServer) const;
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
FSteamID GetLobbyMemberByIndex(FSteamID SteamIDLobby, int32 MemberIndex) const { return SteamMatchmaking()->GetLobbyMemberByIndex(SteamIDLobby, MemberIndex).ConvertToUint64(); }
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
FString GetLobbyMemberData(FSteamID SteamIDLobby, FSteamID SteamIDUser, const FString& Key) const { return UTF8_TO_TCHAR(SteamMatchmaking()->GetLobbyMemberData(SteamIDLobby, SteamIDUser, TCHAR_TO_UTF8(*Key))); }
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
int32 GetLobbyMemberLimit(FSteamID SteamIDLobby) const { return SteamMatchmaking()->GetLobbyMemberLimit(SteamIDLobby); }
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
FSteamID GetLobbyOwner(FSteamID SteamIDLobby) const { return SteamMatchmaking()->GetLobbyOwner(SteamIDLobby).ConvertToUint64(); }
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Matchmaking")
int32 GetNumLobbyMembers(FSteamID SteamIDLobby) const { return SteamMatchmaking()->GetNumLobbyMembers(SteamIDLobby); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool InviteUserToLobby(FSteamID SteamIDLobby, FSteamID SteamIDInvitee) const { return SteamMatchmaking()->InviteUserToLobby(SteamIDLobby, SteamIDInvitee); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
FSteamAPICall JoinLobby(FSteamID SteamIDLobby) const { return SteamMatchmaking()->JoinLobby(SteamIDLobby); }
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void LeaveLobby(FSteamID SteamIDLobby) { SteamMatchmaking()->LeaveLobby(SteamIDLobby); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool RemoveFavoriteGame(int32 AppID, const FString& IP, int32 ConnPort, int32 QueryPort, const TArray<ESteamFavoriteFlags>& Flags) const;
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool RequestLobbyData(FSteamID SteamIDLobby) const { return SteamMatchmaking()->RequestLobbyData(SteamIDLobby); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
FSteamAPICall RequestLobbyList() const { return SteamMatchmaking()->RequestLobbyList(); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool SendLobbyChatMsg(FSteamID SteamIDLobby, FString Message) const;
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool SetLobbyData(FSteamID SteamIDLobby, const FString& Key, const FString& Value) const { return SteamMatchmaking()->SetLobbyData(SteamIDLobby, TCHAR_TO_UTF8(*Key), TCHAR_TO_UTF8(*Value)); }
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void SetLobbyGameServer(FSteamID SteamIDLobby, const FString& GameServerIP, int32 GameServerPort, FSteamID SteamIDGameServer) const;
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool SetLobbyJoinable(FSteamID SteamIDLobby, bool bLobbyJoinable) const { return SteamMatchmaking()->SetLobbyJoinable(SteamIDLobby, bLobbyJoinable); }
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Matchmaking")
void SetLobbyMemberData(FSteamID SteamIDLobby, const FString& Key, const FString& Value) { SteamMatchmaking()->SetLobbyMemberData(SteamIDLobby, TCHAR_TO_UTF8(*Key), TCHAR_TO_UTF8(*Value)); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool SetLobbyMemberLimit(FSteamID SteamIDLobby, uint8 MaxMembers = 5) const { return SteamMatchmaking()->SetLobbyMemberLimit(SteamIDLobby, MaxMembers); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool SetLobbyOwner(FSteamID SteamIDLobby, FSteamID SteamIDNewOwner) const { return SteamMatchmaking()->SetLobbyOwner(SteamIDLobby, SteamIDNewOwner); }
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Matchmaking")
bool SetLobbyType(FSteamID SteamIDLobby, ESteamLobbyType LobbyType) const { return SteamMatchmaking()->SetLobbyType(SteamIDLobby, (ELobbyType)LobbyType); }
/** Delegates */
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnFavoritesListAccountsUpdated"))
FOnFavoritesListAccountsUpdatedDelegate m_OnFavoritesListAccountsUpdated;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnFavoritesListChanged"))
FOnFavoritesListChangedDelegate m_OnFavoritesListChanged;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyChatMsg"))
FOnLobbyChatMsgDelegate m_OnLobbyChatMsg;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyChatUpdate"))
FOnLobbyChatUpdateDelegate m_OnLobbyChatUpdate;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyCreated"))
FOnLobbyCreatedDelegate m_OnLobbyCreated;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyDataUpdate"))
FOnLobbyDataUpdateDelegate m_OnLobbyDataUpdate;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyEnter"))
FOnLobbyEnterDelegate m_OnLobbyEnter;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyGameCreated"))
FOnLobbyGameCreatedDelegate m_OnLobbyGameCreated;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyInvite"))
FOnLobbyInviteDelegate m_OnLobbyInvite;
// This is currently unused
/*UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyKicked"))
FOnLobbyKickedDelegate m_OnLobbyKicked;*/
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Matchmaking", meta = (DisplayName = "OnLobbyMatchList"))
FOnLobbyMatchListDelegate m_OnLobbyMatchList;
protected:
private:
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnFavoritesListAccountsUpdated, FavoritesListAccountsUpdated_t, OnFavoritesListAccountsUpdatedCallback);
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnFavoritesListChanged, FavoritesListChanged_t, OnFavoritesListChangedCallback);
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyChatMsg, LobbyChatMsg_t, OnLobbyChatMsgCallback);
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyChatUpdate, LobbyChatUpdate_t, OnLobbyChatUpdateCallback);
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyCreated, LobbyCreated_t, OnLobbyCreatedCallback);
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyDataUpdate, LobbyDataUpdate_t, OnLobbyDataUpdateCallback);
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyEnter, LobbyEnter_t, OnLobbyEnterCallback);
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyGameCreated, LobbyGameCreated_t, OnLobbyGameCreatedCallback);
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyInvite, LobbyInvite_t, OnLobbyInviteCallback);
// STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyKicked, LobbyKicked_t, OnLobbyKickedCallback); // This is currently unused
STEAM_CALLBACK_MANUAL(USteamMatchmaking, OnLobbyMatchList, LobbyMatchList_t, OnLobbyMatchListCallback);
};
|
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
const int N = 200222;
vector<int> g[N], gt[N];
bool used[N];
int mark[N];
int inverse[N];
vector<int> order;
void dfs(int x) {
used[x] = true;
for (int y : g[x])
if (!used[y]) dfs(y);
order.push_back(x);
}
void dfs2(int x, int color) {
mark[x] = color;
for (int y : gt[x])
if (!mark[y]) {
dfs2(y, color);
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
int k;
scanf("%d", &k);
for (int j = 0; j < k; ++j) {
int x; scanf("%d", &x);
if (j == 0) {
g[n + x - 1].push_back(i);
gt[i].push_back(n + x - 1);
inverse[n + x - 1] = i;
} else {
g[i].push_back(n + x - 1);
gt[n + x - 1].push_back(i);
}
}
}
/*
for (int i = 0; i < n + n; ++i)
for (int x : g[i]) cerr << i << " --> " << x << endl;
*/
for (int i = 0; i < n + n; ++i)
if (!used[i]) dfs(i);
reverse(begin(order), end(order));
int cur = 0;
for (int x : order)
if (!mark[x]) {
dfs2(x, ++cur);
}
/*
for (int x : order) cerr << x << ' ';
cerr << endl;
for (int i = 0; i < n + n; ++i) cerr << i << ": " << mark[i] << endl;
*/
for (int i = 0; i < n; ++i) {
vector<int> ans;
for (int y : g[i])
if (mark[i] == mark[ inverse[y] ]) {
ans.push_back(y - n + 1);
}
sort(begin(ans), end(ans));
printf("%d", int(ans.size()));
for (int x : ans) printf(" %d", x);
puts("");
}
return 0;
}
|
#include "JewelsGrid.h"
#include "Jewel.h"
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
JewelsGrid* JewelsGrid::create(int row, int col)
{
auto jewelsgrid = new JewelsGrid();
if (jewelsgrid && jewelsgrid->init(row, col))
{
jewelsgrid->autorelease();
return jewelsgrid;
}
else
{
CC_SAFE_DELETE(jewelsgrid);
return nullptr;
}
}
bool JewelsGrid::init(int row, int col)
{
Node::init();
m_row = row;
m_col = col;
m_jewelSelected = nullptr;
m_jewelSwapped = nullptr;
//根据行列初始化一个空的宝石容器大小
m_JewelsBox.resize(m_row);
for (auto &vec : m_JewelsBox)
vec.resize(m_col);
//1.根据布局大小创建出宝石阵列
//2.布局坐标以左下角为原点,x右y上为正方向
for (int x = 0; x < m_col; x++)
{
for (int y = 0; y < m_row; y++)
{
m_JewelsBox[x][y] = createAJewel(x, y);
}
}
while (isDeadMap())
{
log("dead map! need to update");
updateMap();
}
//加入触摸监听
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(JewelsGrid::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(JewelsGrid::onTouchMoved, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
log("JewelsGrid init!");
return true;
}
void JewelsGrid::updateMap()
{
for (int x = 0; x < m_col; x++)
{
for (int y = 0; y < m_row; y++)
{
m_JewelsBox[x][y]->removeFromParent();
m_JewelsBox[x][y] = createAJewel(x, y);
}
}
log("update a new map!");
}
bool JewelsGrid::isDeadMap()
{
//模拟交换,判断交换后是否能消除,如不能,那么就是个死图
auto swap = [](Jewel** a, Jewel** b)
{
auto temp = *a;
*a = *b;
*b = temp;
};
bool isDeadMap = true;
//遍历每一颗宝石
for (int x = 0; x < m_col; x++)
{
for (int y = 0; y < m_row; y++)
{
//跟左边的交换
if (x > 0)
{
swap(&m_JewelsBox[x][y], &m_JewelsBox[x-1][y]);
if (canCrush())
isDeadMap = false;
swap(&m_JewelsBox[x][y], &m_JewelsBox[x-1][y]);
}
//跟右边的交换
if (x < m_col - 1)
{
swap(&m_JewelsBox[x][y], &m_JewelsBox[x+1][y]);
if (canCrush())
isDeadMap = false;
swap(&m_JewelsBox[x][y], &m_JewelsBox[x+1][y]);
}
//跟上面的交换
if (y < m_row - 1)
{
swap(&m_JewelsBox[x][y], &m_JewelsBox[x][y+1]);
if (canCrush())
isDeadMap = false;
swap(&m_JewelsBox[x][y], &m_JewelsBox[x][y+1]);
}
//跟下面的交换
if (y > 0)
{
swap(&m_JewelsBox[x][y], &m_JewelsBox[x][y-1]);
if (canCrush())
isDeadMap = false;
swap(&m_JewelsBox[x][y], &m_JewelsBox[x][y-1]);
}
}
}
//canCrush会存储能消除的宝石进去,由于是模拟交换,所以还要清空
m_crushJewelBox.clear();
return isDeadMap;
}
Jewel* JewelsGrid::createAJewel(int x, int y)
{
//1.根据布局坐标创建一颗宝石,类型随机
//2.判断该宝石是否合法(不会三消)
//3.设置该宝石的世界坐标
//4.将该宝石加入渲染节点
Jewel* jewel = nullptr;
while(1)
{
jewel = Jewel::createByType(random(FIRST_JEWEL_ID, LAST_JEWEL_ID), x, y);
if (isJewelLegal(jewel, x, y))
{
break;
}
}
setJewelPixPos(jewel, x, y);
addChild(jewel);
//log("add a jewel!---type:%d---x:%d---y:%d", jewel->getType(), x, y);
return jewel;
}
bool JewelsGrid::isJewelLegal(Jewel* jewel, int x, int y)
{
//1.分别判断新加入的宝石在x轴y轴方向是否会三消
//2.由于是从正方向加入宝石,因此只需往负方向判断
//3.x,y坐标小于等于1不必判断
//4.两轴同时合法方合法
bool isXLegal = true;
bool isYLegal = true;
if (x > 1)
{
//向x轴负方向分别比较两位,如果宝石类型都一样,那么表示三消,该宝石不合法
if (jewel->getType() == m_JewelsBox[x-1][y]->getType() &&
jewel->getType() == m_JewelsBox[x-2][y]->getType()
)
{
isXLegal = false;
}
else
isXLegal = true;
}
if (y > 1)
{
//向y轴负方向分别比较两位,如果宝石类型都一样,那么表示三消,该宝石不合法
if (jewel->getType() == m_JewelsBox[x][y-1]->getType() &&
jewel->getType() == m_JewelsBox[x][y-2]->getType())
{
isYLegal = false;
}
else
isYLegal = true;
}
return isXLegal && isYLegal;
}
void JewelsGrid::setJewelPixPos(Jewel* jewel, float x, float y)
{
jewel->setPosition(x * GRID_WIDTH, y * GRID_WIDTH);
}
bool JewelsGrid::onTouchBegan(Touch* pTouch, Event* pEvent)
{
//将触摸点的坐标转化为模型坐标
auto pos = this->convertToNodeSpace(pTouch->getLocation());
//是否有按在宝石布局上
if (Rect(0, 0, m_col*GRID_WIDTH, m_row*GRID_WIDTH).containsPoint(pos))
{
//得到布局坐标
int x = pos.x / GRID_WIDTH;
int y = pos.y / GRID_WIDTH;
//得到当前选中的宝石
m_jewelSelected = m_JewelsBox[x][y];
//log("touch coordinate: x=%d,y=%d jewel's type:%d", x, y, m_jewelSelected->getType());
return true;
}
else
{
return false;
}
}
void JewelsGrid::onTouchMoved(Touch* pTouch, Event* pEvent)
{
//如果没有选择宝石,那么返回
if (!m_jewelSelected)
{
return;
}
//已选择宝石的布局坐标
int startX = m_jewelSelected->getX();
int startY = m_jewelSelected->getY();
//触摸点的布局坐标
auto pos = this->convertToNodeSpace(pTouch->getLocation());
int touchX = pos.x / GRID_WIDTH;
int touchY = pos.y / GRID_WIDTH;
//如果触摸点不在布局内,或者触摸点布局坐标和已选宝石布局坐标一样,那么返回
if (!Rect(0, 0, m_col*GRID_WIDTH, m_row*GRID_WIDTH).containsPoint(pos) || Vec2(touchX, touchY) == Vec2(startX, startY))
{
return;
}
//判断已选宝石的布局坐标与触摸点的布局坐标是否直角相隔一个单位
if (abs(startX - touchX) + abs(startY - touchY) != 1)
{
//log("touch pos not on border");
return;
}
//余下的情况,触摸点上面的宝石就是欲进行交换的宝石
//通过坐标索引,获取欲交换的宝石
m_jewelSwapped = m_JewelsBox[touchX][touchY];
//交换宝石,开启交换状态捕捉函数(在交换完成后,判断是否可以消除)
swapJewels(m_jewelSelected, m_jewelSwapped);
schedule(schedule_selector(JewelsGrid::onJewelsSwaping));
}
void JewelsGrid::swapJewels(Jewel *jewelA, Jewel *jewelB)
{
_eventDispatcher->pauseEventListenersForTarget(this); //交换开始,关闭触摸监听
//1.交换宝石容器内的宝石指针
//2.交换宝石坐标
//3.宝石移动到新的位置
auto temp = m_JewelsBox[jewelA->getX()][jewelA->getY()];
m_JewelsBox[jewelA->getX()][jewelA->getY()] = m_JewelsBox[jewelB->getX()][jewelB->getY()];
m_JewelsBox[jewelB->getX()][jewelB->getY()] = temp;
auto tempX = jewelA->getX();
jewelA->setX(jewelB->getX());
jewelB->setX(tempX);
auto tempY = jewelA->getY();
jewelA->setY(jewelB->getY());
jewelB->setY(tempY);
swapJewelToNewPos(jewelA);
swapJewelToNewPos(jewelB);
}
void JewelsGrid::swapJewelToNewPos(Jewel* jewel)
{
//移动开始设置宝石交换状态为真,移动结束再设置为假
jewel->setSwapingState(true);
auto move = MoveTo::create(MOVE_SPEED, Vec2(jewel->getX() * GRID_WIDTH, jewel->getY() * GRID_WIDTH));
auto call = CallFunc::create([jewel](){
jewel->setSwapingState(false);
});
jewel->runAction(Sequence::create(move, call, nullptr));
}
bool JewelsGrid::canCrush()
{
//该函数判断当前状态的宝石阵列是否能消除
//将能消除的宝石加入消除宝石盒子,等待消除
int count = 0; //连续数
Jewel *JewelBegin = nullptr; //起始遍历的宝石
Jewel *JewelNext = nullptr; //从起始宝石开始往前遍历的宝石
//遍历每一列
for (int x = 0; x < m_col; x++)
{
for (int y = 0; y < m_row - 1;)
{
count = 1;
JewelBegin = m_JewelsBox[x][y];
JewelNext = m_JewelsBox[x][y + 1];
//如果连续出现同类型
while (JewelBegin->getType() == JewelNext->getType())
{
count++;
int nextIndex = y + count;
if (nextIndex > m_row - 1)
break;
JewelNext = m_JewelsBox[x][nextIndex];
}
//如果连续数大于等于3,那么遍历的这些宝石应当消除,把它们存入消除宝石盒子
if (count >= 3)
{
for (int n = 0; n < count; n++)
{
auto jewel = m_JewelsBox[x][y+n];
m_crushJewelBox.pushBack(jewel);
}
}
y += count;
}
}
//遍历每一行,逻辑和遍历每一列是一样的
for (int y = 0; y < m_row; y++)
{
for (int x = 0; x < m_col - 1;)
{
count = 1;
JewelBegin = m_JewelsBox[x][y];
JewelNext = m_JewelsBox[x+1][y];
while (JewelBegin->getType() == JewelNext->getType())
{
count++;
int nextIndex = x + count;
if (nextIndex > m_col - 1)
break;
JewelNext = m_JewelsBox[nextIndex][y];
}
if (count >= 3)
{
for (int n = 0; n < count; n++)
{
auto jewel = m_JewelsBox[x+n][y];
//有可能有宝石同时行列可消除,那么不能重复存储到消除宝石盒子,故需添加一次判断
if (m_crushJewelBox.find(jewel) != m_crushJewelBox.end())
{
continue;
}
m_crushJewelBox.pushBack(jewel);
}
}
x += count;
}
}
//如果消除宝石盒子不为空,那么说明该阵列可消除,返回真
if (!m_crushJewelBox.empty())
{
return true;
}
else
{
return false;
}
}
void JewelsGrid::goCrush()
{
//遍历消除宝石盒子,对其中的宝石进行消除操作
for (auto jewel : m_crushJewelBox)
{
//生成新的宝石,类型随机,初始位置在最上面一行的上边一行(布局外一格)
auto newJewel = Jewel::createByType(random(FIRST_JEWEL_ID, LAST_JEWEL_ID), jewel->getX(), m_row);
setJewelPixPos(newJewel, newJewel->getX(), m_row);
addChild(newJewel);
//将新宝石放到新宝石盒子内,等待加入布局
m_newJewelBox.pushBack(newJewel);
//宝石盒子内应当刷新的宝石暂时置为空
m_JewelsBox[jewel->getX()][jewel->getY()] = nullptr;
//原有宝石对象消除
jewel->crush();
}
}
void JewelsGrid::refreshJewelsGrid()
{
//遍历列,如果该列有空位,那么应当刷新
for (int x = 0; x < m_col; x++)
{
int empty_count = 0; //一列总的空格子数
for (int y = 0; y < m_row; y++)
{
//根据坐标索引宝石盒子内的宝石指针,如果为空,那么说明该坐标位置为空
auto jewel = m_JewelsBox[x][y];
if (!jewel)
empty_count++;
}
if (empty_count)
{
//log("the %d col has %d empty", x, empty_count);
//找到有空位的列,刷新该列的宝石
refreshJewelsToNewPos(x);
}
}
}
void JewelsGrid::refreshJewelsToNewPos(int col)
{
//刷新该列上面的宝石
int n = 0; //当前遍历到的空位数
auto pJewelsbox = &m_JewelsBox; //保存一个宝石盒子的指针,这是为了让其能传入lamda
//先让现有的宝石下落
for (int y = 0; y < m_row; y++)
{
auto jewel = m_JewelsBox[col][y];
if (!jewel)
{
n++;
continue;
}
else if (n != 0)
{
jewel->setY(jewel->getY() - n);
auto move = MoveBy::create(0.2, Vec2(0, -n*GRID_WIDTH));
auto call = CallFunc::create([pJewelsbox, jewel](){
//更新宝石盒子内的数据
(*pJewelsbox)[jewel->getX()][jewel->getY()] = jewel;
});
jewel->runAction(Sequence::create(move, call, nullptr));
}
}
//再让新宝石下落
int i = n;
int delta = 1;
for (auto jewel : m_newJewelBox)
{
if (jewel->getX() == col)
{
jewel->setY(m_row - i);
auto delay = DelayTime::create(0.2);
//后下落的速度设置慢一些
auto move = MoveBy::create(0.2*delta++, Vec2(0, -i--*GRID_WIDTH));
auto call = CallFunc::create([jewel, pJewelsbox, this](){
(*pJewelsbox)[jewel->getX()][jewel->getY()] = jewel;
//从新宝石盒子中移除该宝石
m_newJewelBox.eraseObject(jewel);
});
jewel->runAction(Sequence::create(delay, move, call, nullptr));
}
}
}
void JewelsGrid::onJewelsSwaping(float dt)
{
//捕捉两个正在交换的宝石的交换动作是否已经停止,如果没停止,返回继续捕捉
if (m_jewelSelected->isSwaping() || m_jewelSwapped->isSwaping())
{
return;
}
//如果宝石交换动作执行完毕
else
{
unschedule(schedule_selector(JewelsGrid::onJewelsSwaping)); //停止捕捉
log("swap over!");
log("is it can crush?");
//判断是否当前状态可以消除
if (canCrush())
{
log("yes,crush!");
m_jewelSelected = nullptr;
//开始消除,开启消除状态捕捉函数(捕捉到消除完毕后,刷新布局),这一轮消除正式开始
SimpleAudioEngine::getInstance()->playEffect("crush.ogg");
goCrush();
schedule(schedule_selector(JewelsGrid::onJewelsCrushing));
}
else
{
log("no, cant crush!");
//不能消除,交换回去,开启交换返回时的捕捉函数(捕捉到消除完毕后,开启触摸接听)
SimpleAudioEngine::getInstance()->playEffect("swapback.ogg");
swapJewels(m_jewelSelected, m_jewelSwapped);
schedule(schedule_selector(JewelsGrid::onJewelsSwapingBack));
}
}
}
void JewelsGrid::onJewelsSwapingBack(float dt)
{
//捕捉两个正在交换的宝石的交换动作是否已经停止,如果没停止,返回继续捕捉
if (m_jewelSelected->isSwaping() || m_jewelSwapped->isSwaping())
{
return;
}
else
{
unschedule(schedule_selector(JewelsGrid::onJewelsSwapingBack)); //停止捕捉
log("swap back!");
m_jewelSelected = nullptr;
_eventDispatcher->resumeEventListenersForTarget(this); //重新开始触摸接听
}
}
void JewelsGrid::onJewelsCrushing(float dt)
{
//捕捉宝石消除状态,如果有宝石还在消除,那么继续捕捉
for (auto jewel : m_crushJewelBox)
{
if (jewel->isCrushing())
{
//log("crushing");
return;
}
}
//如果全部宝石已经消除完毕,停止捕捉函数
unschedule(schedule_selector(JewelsGrid::onJewelsCrushing));
m_crushJewelBox.clear(); //清空消除宝石盒子
log("crush over!");
log("begin to refresh!");
//刷新宝石阵列,并开启刷新状态捕捉函数(刷新一遍结束,重新判断新阵列是否可消除)
refreshJewelsGrid();
schedule(schedule_selector(JewelsGrid::onJewelsRefreshing));
}
void JewelsGrid::onJewelsRefreshing(float dt)
{
//捕捉宝石刷新状态,如果新宝石盒子还有宝石(即新宝石还在刷新当中),那么继续捕捉
if (m_newJewelBox.size() != 0)
{
//log("refreshing!");
return;
}
else
{
unschedule(schedule_selector(JewelsGrid::onJewelsRefreshing));
log("refresh over!");
log("and now, is it can crush?");
if (canCrush())
{
log("yes, crush again!");
//如果能消除,那么继续消除
SimpleAudioEngine::getInstance()->playEffect("crush.ogg");
goCrush();
schedule(schedule_selector(JewelsGrid::onJewelsCrushing));
}
else
{
log("no, cant crush! over!");
//判断是否为死图,如果是,则执行一段文字动画,提示即将更新地图
if (isDeadMap())
{
log("cant crush any more, updating a new map!");
auto winSize = Director::getInstance()->getWinSize();
auto label = Label::createWithTTF("Cant Crush Any More, Change!", "fonts/Marker Felt.ttf", 24);
label->setTextColor(Color4B::BLACK);
label->setPosition(winSize.width / 2, winSize.height / 2);
label->setOpacity(0);
this->getParent()->addChild(label);
//提示文字淡入淡出后,更新地图,再开启触摸监听
auto fadein = FadeIn::create(0.5);
auto fadeout = FadeOut::create(0.5);
auto call = CallFunc::create([this, label](){
do
{
updateMap();
} while (isDeadMap());
label->removeFromParent();
_eventDispatcher->resumeEventListenersForTarget(this);
});
label->runAction(Sequence::create(fadein, DelayTime::create(2), fadeout, call, nullptr));
}
else
{
//如果不是死图,那么就直接开启触摸监听,等待下一轮的交互操作
_eventDispatcher->resumeEventListenersForTarget(this);
}
}
}
}
|
/*************************************************************
* > File Name : P2842.cpp
* > Author : Tony
* > Created Time : 2019/05/10 16:14:51
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 1e9 + 7;
LL a, b;
LL pow_mod(LL a, LL p, LL mod) {
a %= mod; LL ans = 1;
for (; p; p >>= 1, a *= a, a %= mod) if(p & 1) ans = ans * a % mod;
return ans;
}
int main() {
scanf("%lld %lld", &a, &b);
printf("%lld\n", pow_mod(a, pow_mod(a, b - 1, mod - 1), mod));
return 0;
}
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <flux/System>
#include "JobServer.h"
#include "JobScheduler.h"
namespace fluxmake {
Ref<JobScheduler> JobScheduler::create(int concurrency)
{
return new JobScheduler(concurrency);
}
JobScheduler::JobScheduler(int concurrency)
: concurrency_((concurrency > 0) ? concurrency : System::concurrency()),
requestChannel_(JobChannel::create()),
replyChannel_(JobChannel::create()),
started_(false),
status_(0),
totalCount_(0),
finishCount_(0)
{}
void JobScheduler::start()
{
if (started_) return;
started_ = true;
serverPool_ = ServerPool::create();
for (int i = 0; i < concurrency_; ++i)
serverPool_->pushBack(JobServer::start(requestChannel_, replyChannel_));
}
void JobScheduler::schedule(Job *job)
{
requestChannel_->pushBack(job);
++totalCount_;
}
bool JobScheduler::collect(Ref<Job> *completedJob)
{
start();
if ((finishCount_ == totalCount_) || !serverPool_) {
*completedJob = 0;
return false;
}
Ref<Job> job = replyChannel_->popFront();
*completedJob = job;
if (job->status() != 0) {
status_ = job->status();
serverPool_ = 0;
}
++finishCount_;
return true;
}
} // namespace fluxmake
|
/**
* Airboat Control Firmware
*
* Provides low-level functionality for interacting with vehicle hardware such as
* fans, servos, gyros, and simple sensors. Communication is achieved via the
* Amarino library.
*
* Functionality is broken down into separate modules for each device/actuator that
* is being controlled. Separate Amarino functions are used to isolate IO between
* modules. Each module is assumed to be called serially, so thread safety is not
* an issue except in callback functions.
*/
#include <stdlib.h>
#include <avr/eeprom.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
// Structure storing PID constants for each axis
// TODO: This placement is currently a hack to share with rudder and thruster
struct pidConstants_t { float Kp[6], Ki[6], Kd[6]; };
pidConstants_t pid;
pidConstants_t EEMEM pidEeprom;
// Core functionality
#include "board.h"
#include "meet_android.h"
#include <util/delay.h>
// Core modules
#include "rudder.h"
#include "thruster.h"
// Sensor modules
#include "depth_sensor.h"
#include "do_sensor.h"
#include "te5_sensor.h"
#include "es2_sensor.h"
#include "monitor_sensor.h"
// Define indices for specific coordinates
// Assumes X is forward, Y is left, Z is up, frame is right-handed
#define DX 0
#define DY 1
#define DZ 2
#define DRX 3
#define DRY 4
#define DRZ 5
// Define the location of the PID constants in EEPROM memory
#define PID_ADDRESS 0
// Define the char codes for the main Amarino callbacks
#define SET_VELOCITY_FN 'v'
#define SET_PID_FN 'k'
#define GET_PID_FN 'l'
#define SET_SAMPLER_FN 'q'
// Defines update interval in milliseconds
#define UPDATE_INTERVAL 100
// Arrays to store the actual and desired velocity of the vehicle in 6D
float desiredVelocity[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
float actualVelocity[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
// Hardware configuration
LedHW<UserLed> led;
// Communication structure for Amarino
SerialHW<SerialBluetooth> bluetooth(BAUD_115200);
MeetAndroid amarino(&bluetooth);
// Module configuration
ServoHW0<Motor> motor;
Thruster thruster(&amarino, &motor);
ServoHW1<Servo1> servo1;
Rudder rudder(&amarino, &servo1);
//MonitorConfig monitorConfig = { &PORTK, PIN4 };
//MonitorSensor<monitorConfig, Serial2> monitorSensor(&amarino);
//DepthConfig depthConfig = { &PORTK, PIN4 };
//DepthSensor<depthConfig, Serial2> depthSensor(&amarino);
DOSensor<Serial3> doSensor(&amarino);
TE5Config teConfig = { &PORTD, PIN1 };
TE5Sensor<teConfig, Serial4> teSensor(&amarino);
//ES2Config esConfig = { &PORTD, PIN1 };
//ES2Sensor<esConfig, Serial4> esSensor(&amarino);
/**
* Reads ADC calibration information from EEPROM
*/
uint8_t readCalibrationByte( uint8_t index )
{
uint8_t result;
/* Load the NVM Command register to read the calibration row. */
NVM_CMD = NVM_CMD_READ_CALIB_ROW_gc;
result = pgm_read_byte(index);
/* Clean up NVM Command register. */
NVM_CMD = NVM_CMD_NO_OPERATION_gc;
return( result );
}
/**
* Gradually transition the boat to a safe state.
*/
void decayVelocity()
{
// Slow the vehicle down by reducing velocity in every direction
for (int i = 0; i < 6; ++i)
desiredVelocity[i] *= 0.95;
}
/**
* Receives a 6D desired velocity command from Amarino.
*/
void setVelocity(uint8_t flag, uint8_t numOfValues)
{
// Ignore if wrong number of arguments
if (numOfValues != 6) return;
// Load these values into array of desired velocities
amarino.getFloatValues(desiredVelocity);
}
/**
* Receives PID constants for a particular axis.
*/
void setPID(uint8_t flag, uint8_t numOfValues)
{
// Ignore if wrong number of arguments
if (numOfValues != 4) return;
// Load all the arguments into memory
float args[numOfValues];
amarino.getFloatValues(args);
// Get the axis that is being set
int axis = (int)args[0];
if (axis < 0 || axis >= 6) return;
// Set these values and save them to the EEPROM
pid.Kp[axis] = args[1];
pid.Ki[axis] = args[2];
pid.Kd[axis] = args[3];
eeprom_update_block(&pid, &pidEeprom, sizeof(pidConstants_t));
}
/**
* Sends the PID constants of a particular axis to Amarino.
*/
void getPID(uint8_t flag, uint8_t numOfValues)
{
// Ignore if wrong number of arguments
if (numOfValues != 1) return;
// Load the argument into memory
float axisRaw = amarino.getFloat();
// Get the axis that is being set
int axis = (int)axisRaw;
if (axis < 0 || axis >= 6) return;
// Return the appropriate values to Amarino
amarino.send(GET_PID_FN);
amarino.send((float)axis);
amarino.send(pid.Kp[axis]);
amarino.send(pid.Ki[axis]);
amarino.send(pid.Kd[axis]);
amarino.sendln();
}
/**
* Sets the PID gains to zero-values.
*/
void resetPID()
{
memset(&pid, 0, sizeof(pid));
pid.Kp[0] = 32000.0;
pid.Kp[5] = -32000.0; // We invert the rudder so +-100% is positive RHS angle
eeprom_update_block(&pid, &pidEeprom, sizeof(pidConstants_t));
}
/**
* Configures ADC to read voltage and current.
*/
void setupADC()
{
// ADC Setup:
// Read ADCA calibration from NVM signature row into ADC register
ADCB.CALL = readCalibrationByte( offsetof(NVM_PROD_SIGNATURES_t, ADCBCAL0) );
ADCB.CALH = readCalibrationByte( offsetof(NVM_PROD_SIGNATURES_t, ADCBCAL1) );
// 12 Bit Resolution, unsigned mode
ADCB.CTRLB = ADC_RESOLUTION_12BIT_gc;
// Set ADC clock
ADCB.PRESCALER = ADC_PRESCALER_DIV64_gc;
// Set ADC reference voltage
ADCB.REFCTRL = ADC_REFSEL_VCC_gc | 0x02;
// Configure PORTB pins as input
PORTB.DIRCLR = _BV(PIN3) | _BV(PIN7);
PORTB.OUTCLR = _BV(PIN3) | _BV(PIN7);
// Set ADC in single-ended mode
ADCB.CH0.CTRL = ADC_CH_INPUTMODE0_bm;
ADCB.CH1.CTRL = ADC_CH_INPUTMODE0_bm;
// Set positive terminal of ADC comparator
ADCB.CH0.MUXCTRL = ADC_CH_MUXPOS_PIN3_gc;
ADCB.CH1.MUXCTRL = ADC_CH_MUXPOS_PIN7_gc;
// Enable ADC
ADCB.CTRLA |= ADC_ENABLE_bm;
}
/**
* The main setup function for the vehicle. Initalized the Amarino communications,
* then calls the various setup functions for the various modules.
*/
void setup()
{
// Core board initialization
initBoard();
// Arm thruster
thruster.arm();
// Reset all PID values to zero
resetPID();
// Load PID constants in from EEPROM
eeprom_read_block(&pid, &pidEeprom, sizeof(pidConstants_t));
// Set up serial communications
amarino.registerFunction(setVelocity, SET_VELOCITY_FN);
amarino.registerFunction(setPID, SET_PID_FN);
amarino.registerFunction(getPID, GET_PID_FN);
// Configure ADC
setupADC();
}
/**
* Main update loop for ADC values.
*/
void adcUpdate()
{
// Trigger conversion on both channels
ADCB.CH0.CTRL |= ADC_CH_START_bm;
ADCB.CH1.CTRL |= ADC_CH_START_bm;
// Wait for result on both channels
while(!ADCB.CH0.INTFLAGS || !ADCB.CH1.INTFLAGS);
int voltage = ADCB.CH0RES;
int current = ADCB.CH1RES;
// offset = 3.3V * (4.99k / 10k), scale = 0.001 * 4.99k / 1k
amarino.send('i');
amarino.send((current - 3270) * 0.101f);
amarino.sendln();
amarino.send('v');
amarino.send(voltage / (331.0f));
amarino.sendln();
}
/**
* The main event update loop for the vehicle. Within this function we check for
* events from Amarino and the process timers.
*/
void loop()
{
// Get any incoming messages and process them
amarino.receive();
// Process the sensors
// monitorSensor.loop();
// depthSensor.loop();
doSensor.loop();
teSensor.loop();
// esSensor.loop();
}
/**
* The main control loop for the vehicle. Within this function we mainly call the
* periodic update functions for the various modules.
*/
void update(void *)
{
// Toggle LED just to let us know things are working
led.toggle();
// Update the thrust and rudder control loops
rudder.update();
thruster.update();
// Perform periodic updates for sensors
teSensor.update();
doSensor.update();
// depthSensor.update();
// esSensor.update();
// monitorSensor.update();
// Decay the desired velocities slightly
decayVelocity();
//Try reading analog sensor
adcUpdate();
}
int main(void)
{
// Initial setup for boat
setup();
// Schedule periodic updates
Task<UserTask> task(update, NULL, UPDATE_INTERVAL);
// Start main tight loop
while(true) { loop(); }
}
|
#include "SensitiveWordFilter.h"
#include <iostream>
using namespace std;
std::wstring Ascii2Unicode(const std::string& str)
{
// 先计算转换后的大小
int nLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, nullptr, 0);
wchar_t* pUnicode = new wchar_t[nLen + 1];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pUnicode, nLen + 1);
wstring ret_str = pUnicode;
delete[]pUnicode;
return ret_str;
}
string Unicode2Utf8(const std::wstring& wstr)
{
int nLen = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
char* pStr = new char[nLen + 1];
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, pStr, nLen + 1, nullptr, nullptr);
string ret_str = pStr;
delete[]pStr;
return ret_str;
}
string Ascii2Utf8(const std::string& str)
{
return Unicode2Utf8(Ascii2Unicode(str));
}
int main()
{
CSensitiveWordFilter* pWordFilter = new CSensitiveWordFilter();
if (NULL == pWordFilter)
{
std::cout << "ERROR!!! pWordFilter == NULL" << endl;
return 1;
}
pWordFilter->load("../../../../GitHub/SensitiveWords/config/ChatSensitiveWord.txt");
char szTest[64];
while (true)
{
cin.getline(szTest, 64);
//wstring wszTemp = Ascii2Unicode(string(szTest));
std::string szUtf8 = Ascii2Utf8(string(szTest));
//std::transform(szUtf8.begin(), szUtf8.end(), szUtf8.begin(), tolower);
//cout << "after transform string is " << szUtf8 << endl;
if (pWordFilter->censor(szUtf8))
{
cout << "check str has sensitiveWorld+++++++++++++++++++++++++++++++++++++++++++++++" << endl;
}
}
system("pause");
delete pWordFilter;
return 0;
}
|
#include <iostream>
#include <vector>
#include "solution.h"
using namespace std;
int main() {
vector<int> nums = {2, 7, 11, 15};
int target = 9;
Solution sol;
auto ans = sol.twoSum(nums, target);
if (ans.empty())
cout << "Not Found!" << endl;
else {
cout << nums[ans[0]] << " + " << nums[ans[1]] << " == " << target << endl;
}
return 0;
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** This program is free software; you can redistribute it and/or
//** modify it under the terms of the GNU General Public License
//** as published by the Free Software Foundation; either version 3
//** of the License, or (at your option) any later version.
//**
//** This program is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "hexen2strings.h"
#include "common_defs.h"
#include "Common.h"
// For international stuff
int* prh2_string_index = NULL;
char* prh2_global_strings = NULL;
int prh2_string_count = 0;
int* prh2_info_string_index = NULL;
char* prh2_global_info_strings = NULL;
int prh2_info_string_count = 0;
char* h2_puzzle_strings;
static void ComH2_LoadPuzzleStrings() {
FS_ReadFile( "puzzles.txt", ( void** )&h2_puzzle_strings );
}
static void ComH2_LoadGlobalStrings() {
if ( !FS_ReadFile( "strings.txt", ( void** )&prh2_global_strings ) ) {
common->FatalError( "ComH2_LoadGlobalStrings: couldn't load strings.txt" );
}
char NewLineChar = -1;
int count = 0;
for ( int i = 0; prh2_global_strings[ i ] != 0; i++ ) {
if ( prh2_global_strings[ i ] == 13 || prh2_global_strings[ i ] == 10 ) {
if ( NewLineChar == prh2_global_strings[ i ] || NewLineChar == -1 ) {
NewLineChar = prh2_global_strings[ i ];
count++;
}
}
}
if ( !count ) {
common->FatalError( "ComH2_LoadGlobalStrings: no string lines found" );
}
prh2_string_index = ( int* )Mem_Alloc( ( count + 1 ) * 4 );
count = 0;
int start = 0;
for ( int i = 0; prh2_global_strings[ i ] != 0; i++ ) {
if ( prh2_global_strings[ i ] == 13 || prh2_global_strings[ i ] == 10 ) {
if ( NewLineChar == prh2_global_strings[ i ] ) {
prh2_string_index[ count ] = start;
start = i + 1;
count++;
} else {
start++;
}
prh2_global_strings[ i ] = 0;
} else if ( GGameType & GAME_HexenWorld ) {
//for indexed prints, translate '^' to a newline
if ( prh2_global_strings[ i ] == '^' ) {
prh2_global_strings[ i ] = '\n';
}
}
}
prh2_string_count = count;
common->Printf( "Read in %d string lines\n", count );
}
static void ComH2_LoadInfoStrings() {
if ( !FS_ReadFile( "infolist.txt", ( void** )&prh2_global_info_strings ) ) {
common->FatalError( "ComH2_LoadInfoStrings: couldn't load infolist.txt" );
}
char NewLineChar = -1;
int count = 0;
for ( int i = 0; prh2_global_info_strings[ i ] != 0; i++ ) {
if ( prh2_global_info_strings[ i ] == 13 || prh2_global_info_strings[ i ] == 10 ) {
if ( NewLineChar == prh2_global_info_strings[ i ] || NewLineChar == -1 ) {
NewLineChar = prh2_global_info_strings[ i ];
count++;
}
}
}
if ( !count ) {
common->FatalError( "ComH2_LoadInfoStrings: no string lines found" );
}
prh2_info_string_index = ( int* )Mem_Alloc( ( count + 1 ) * 4 );
int start = 0;
count = 0;
for ( int i = 0; prh2_global_info_strings[ i ] != 0; i++ ) {
if ( prh2_global_info_strings[ i ] == 13 || prh2_global_info_strings[ i ] == 10 ) {
if ( NewLineChar == prh2_global_info_strings[ i ] ) {
prh2_info_string_index[ count ] = start;
start = i + 1;
count++;
} else {
start++;
}
prh2_global_info_strings[ i ] = 0;
}
}
prh2_info_string_count = count;
common->Printf( "Read in %d objectives\n",count );
}
void ComH2_LoadStrings() {
ComH2_LoadGlobalStrings();
ComH2_LoadPuzzleStrings();
if ( !( GGameType & GAME_HexenWorld ) && GGameType & GAME_H2Portals ) {
ComH2_LoadInfoStrings();
}
}
|
/**
* 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 <MediaClientHelper.h>
#include <string/String.h>
using namespace YUNOS_MM;
int main(int argc, char** argv) {
FILE *fp = freopen("/dev/null", "w", stderr);
String string = MediaClientHelper::dumpsys();
printf("%s", string.c_str());
if (!fp)
fclose(fp);
return 0;
}
|
//
// Chord.cpp
// Chord
//
// Created by Asjad Athick on 26/4/17.
// Student: 4970512
// Compilation: g++ -o CHORD main.cpp Peer.cpp Chord.cpp
// Copyright © 2017 asjad.io. All rights reserved.
//
#include "Chord.hpp"
unsigned int hash(std::string input, unsigned int chordSize){
unsigned int key = 0;
for (long i = 0; i < input.size(); i++) {
key = ((key << 5) + key) ^ input[i];
}
return key % (int)pow(2, chordSize);
}
Chord::Chord(){
chordSize = 1;
index = NULL;
}
Chord::~Chord(){
Peer *delPtr = index->getSuccessor();
Peer *tmp;
do{
tmp = delPtr->getSuccessor();
delete delPtr;
delPtr = tmp;
}while (delPtr != index);
delete index;
}
void Chord::InitChord(unsigned int n){
//size check
if (n < 1 || n > MAX_CHORD_N_SIZE) {
throw std::string ("InitChord: Cannot initialise Chord; invalid size");
}
this->chordSize = n;
//print details
std::cout << "Asjad Athick" << std::endl;
std::cout << "4970512" << std::endl;
//check if re initialised
if (index != NULL) {
//delete allocated peers
Peer *delPtr = index->getSuccessor();
Peer *tmp;
do{
tmp = delPtr->getSuccessor();
delete delPtr;
delPtr = tmp;
}while (delPtr != index);
delete index;
}
//new node at 0
index = new Peer(0, this->chordSize);
index->setSuccessor(index);
index->setPredecessor(index);
UpdateAllFingerTables();
}
void Chord::AddPeer(unsigned int id){
checkInit();
checkKeyRange(id);
Peer *insert;
FindKey(id, insert);
if (insert->getID() == id) {
throw std::string("AddPeer: Node with that ID already exists");
}
Peer *newNode = new Peer(id, this->chordSize);
if ((insert->getID() > id)) {
if ((insert->getPredecessor()->getID() > id)) {
insert = insert->getPredecessor();
}
//new node before insert node (new node is smaller)
if (insert == index) {
//first node
index = newNode;
}
newNode->setSuccessor(insert);
newNode->setPredecessor(insert->getPredecessor());
insert->getPredecessor()->setSuccessor(newNode);
insert->setPredecessor(newNode);
} else {
//new node is bigger
if (insert->getPredecessor()->getID() < id) {
insert = insert->getPredecessor();
}
newNode->setSuccessor(insert->getSuccessor());
newNode->setPredecessor(insert);
insert->getSuccessor()->setPredecessor(newNode);
insert->setSuccessor(newNode);
}
this->UpdateAllFingerTables();
std::cout << "PEER " << id << " ADDED" << std::endl;
}
void Chord::RemovePeer(unsigned int id){
checkInit();
checkKeyRange(id);
Peer *delPtr = NULL;
FindKey(id, delPtr);
if (delPtr == NULL) {
throw std::string("RemovePeer: Peer with the ID doesn't exist");
}
//move data
delPtr->getSuccessor()->addData(delPtr->getNodeData());
//break links
delPtr->getPredecessor()->setSuccessor(delPtr->getSuccessor());
delPtr->getSuccessor()->setPredecessor(delPtr->getPredecessor());
//check if index needs to be updated
if (delPtr == index) {
index = delPtr->getSuccessor();
}
//delete node
delete delPtr;
this->UpdateAllFingerTables();
std::cout << "PEER " << id << " REMOVED" << std::endl;
}
void Chord::FindKey(unsigned int key, Peer *&foundPeer){
checkInit();
checkKeyRange(key);
Peer *ptr = index;
bool found = false;
bool print;
do{
print = true;
if ((ptr->getID() >= key) && (ptr->getPredecessor()->getID() < key)) {
found = true;
print = false;
break;
}
//print visit
if (print) {
std::cout << ptr->getID() << ">";
}
//check if only 1 peer in chord?
if (ptr->getSuccessor() == ptr || ptr->getID() == key) {
break;
}
//check if it's a join position
if (ptr->getID() > ptr->getSuccessor()->getID()) {
ptr = ptr->getSuccessor();
break;
}
//check matches
if ((ptr->getID() >= key) && (ptr->getPredecessor()->getID() < key)) {
found = true;
print = false;
break;
} else {
//look in ft for largest but less than key peer
std::vector<Peer*> ft = ptr->getFingerTable();
std::sort(ft.begin(), ft.end(), Peer::ascSort);
Peer *tmp = NULL;
for (int i = 0; i < ft.size(); ++i) {
if ((ft[i]->getID() <= key) && (ft[i]->getID() >= ptr->getID())) {
if (tmp == NULL) {
tmp = ft[i];
} else if (ft[i]->getID() > tmp->getID()){
tmp = ft[i];
}
}
}
if (tmp == ptr) {
ptr = ptr->getSuccessor();
break;
}
if (tmp == NULL) {
tmp = ptr->getSuccessor();
}
ptr = tmp;
//or pass to successor if none found
}
} while (!found);
//print last
std::cout << ptr->getID() << std::endl;
foundPeer = ptr;
}
void Chord::Insert(std::string value){
ChangeData(value, true);
}
void Chord::Delete(std::string value){
ChangeData(value, false);
}
void Chord::ChangeData(std::string value, bool insert){
checkInit();
unsigned int key = hash(value, this->chordSize);
Peer *insPeer = NULL;
FindKey(key, insPeer);
if (insPeer == NULL) {
throw std::string("ChangeData: could not find a node to update value");
}
if (insert) {
insPeer->addData(value);
} else {
insPeer->removeData(value);
}
std::cout << (insert ? "INSERTED " : "REMOVED ") << value << " (key=" << key << ") " << (insert ? "AT" : "FROM") << " " << insPeer->getID() << std::endl;
}
void Chord::Print(unsigned int key){
checkInit();
checkKeyRange(key);
Peer *search = NULL;
FindKey(key, search);
if (search == NULL) {
throw std::string("Print: could not find a peer with the key");
}
std::cout << "DATA AT INDEX NODE " << key << ":" << std::endl;
search->printNodeData();
std::cout << "FINGER TABLE OF NODE " << key << ":" << std::endl;
search->printFingerTable();
}
void Chord::Read(std::string filename){
std::ifstream input(filename.c_str());
if (!input.good()) {
throw std::string("Read: File could not be opened for read");
}
std::string cmdBuffer;
std::string cmd, data;
while (getline(input, cmdBuffer)) {
//trim comments
trimCommentsAndTrailingSpace(cmdBuffer);
//get cmd and param for exec
std::size_t pos = cmdBuffer.find(' ');
cmd = cmdBuffer.substr(0, pos);
data = cmdBuffer.substr(pos + 1);
std::stringstream ss;
ss << data;
int intData;
ss >> intData;
//exec
if (cmd == "initchord") {
InitChord(intData);
} else if (cmd == "addpeer"){
AddPeer(intData);
} else if (cmd == "removepeer"){
RemovePeer(intData);
} else if (cmd == "insert"){
Insert(data);
} else if (cmd == "delete"){
Delete(data);
} else if (cmd == "print"){
Print(intData);
} else{
throw std::string("Read: Input file contains invalid command");
}
}
input.close();
}
//----Helpers---
void Chord::trimCommentsAndTrailingSpace(std::string& in){
std::size_t pos = in.find('#');
in = in.substr(0, pos -1);
pos = in.find_last_not_of(" \r\n\t");
if (std::string::npos != pos)
in.erase(pos + 1);
}
void Chord::checkInit(){
if (this->index == NULL) {
throw std::string("ChordException: Chord not initialised");
}
}
void Chord::checkKeyRange(unsigned int key){
if (key > pow(2, this->chordSize)) {
throw std::string("ChordException: ID for search key is out of range for Chord size");
}
}
void Chord::UpdateAllFingerTables(){
Peer *cur = index;
do{
cur->updateFingerTable();
cur = cur->getSuccessor();
} while(cur != index);
}
|
#pragma once
class Graphics {
public:
Graphics();
~Graphics();
void Background(float, float, float);
void loop(void);
};
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//a가 b의 앞에 와야할 때 true
//그렇지 않을 때에는 false
bool cmp(pair<int, string> a, pair<int, string> b){
//나이가 같은 경우
//if(a.first == b.first)
return a.first < b.first;
};
int main() {
vector<pair<int, string>> vec;
int N, age;
string name;
cin>>N;
for(int i=0; i< N; i++){
cin>>age>>name;
vec.push_back(make_pair(age, name));
}
//pair를 sort할 때 cmp함수 설정 없이 그냥 해주면 first를 기준으로 정렬을 해줌!
//이름은 먼저 가입 기준임으로 stable sort
stable_sort(vec.begin(), vec.end(), cmp);
//sort(vec.begin(), vec.end(), cmp); 이걸로하면 틀림!
//vector iteration
vector<pair<int, string>>::iterator iter;
for(iter = vec.begin(); iter != vec.end(); iter++)
cout<<(*iter).first<<" "<<iter->second<<'\n';
}
//다른 사람이 제출한 정답!
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int N;
vector<string> n[201];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> N;
for (int i = 0, a; i < N; i++) {
string s;
cin >> a >> s;
n[a].push_back(s);
}
for (int i = 1; i < 201; i++)
for(string &s : n[i])
cout << i << ' ' << s << '\n';
return 0;
}
|
#include "Matchlock.h"
Matchlock::Matchlock() : Ranged::Ranged()
{
range = 90;
ammunition = 15;
missile_damage = 2;
recruitment_cost = 700;
upkeep_cost = 400;
}
Matchlock::~Matchlock()
{
}
char Matchlock::type_of_unit()
{
return 'm';
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,k,a[105];
while(~scanf("%d%d",&n,&k)) {
for (int i = 0; i < n; i++)
cin >> a[i];
int sum = 0,i;
for(i = 0; i < n; i++) {
if(a[i] <= k)
sum++;
else
break;
}
for(int j = n-1; j > i; j--)
if(a[j] <= k)
sum++;
else
break;
cout << sum << endl;
}
return 0;
}
|
int num(char c)
{
return c - '0';
}
void reverse(string& A,int i,int j)
{
while(i<j)
{
swap(A[i],A[j]);
i++;
j--;
}
}
string Solution::solve(string A) {
int i;
int n = A.size();
for(i=n-2;i>=0;i--)
{
if(num(A[i])<num(A[i+1]))
break;
}
// already the maximum number
if(i==-1)
return "-1";
// replace this number with greatest right most number
int j = n-1;
for(;j>i;j--)
{
if(num(A[j])>num(A[i]))
break;
}
// swap with this number
swap(A[j],A[i]);
// remaining numbers from A[i+1] to A[j] // all are greater than 3 and sholud ber reversed
reverse(A,i+1,n-1);
return A;
}
|
#ifndef LTUI_HOME_VIEW_H
#define LTUI_HOME_VIEW_H
#include "./router.hpp"
#include "./view.hpp"
#include "ftxui/component/container.hpp"
#include "ftxui/component/menu.hpp"
#include <memory>
namespace ltui {
struct home_view : public view {
explicit home_view(std::shared_ptr<router> router);
protected:
void initialize_ui() override;
private:
void on_menu_selected(int option);
std::shared_ptr<router> _router;
ftxui::Container _container;
ftxui::Menu _menu;
};
} // namespace ltui
#endif
|
#include <CannonRush.h>
#include <Kubot.h>
#include <MacroManager.h>
#include <Utils.h>
#include <utils/Map.h>
#include <utils/UnitTraits.h>
#include <utils/UnitQuery.h>
#include <BuildOrderExecutor.h>
using namespace sc2;
Kubot::~Kubot() {}
Kubot::Kubot()
: m_sc2(*this)
{
}
void
Kubot::OnGameStart()
{
auto obs = Observation();
dump_pahting_grid(obs->GetGameInfo().pathing_grid, "map.txt");
m_map = std::make_unique<sc2::utils::Map>(sc2::utils::Map(m_sc2));
auto tech_tree = sc2::utils::make_tech_tree(*obs);
auto opening = std::make_unique<BuildOrderExecutor>(m_sc2, *m_map, tech_tree, make_4gate(m_sc2.obs()));
m_listeners.push_back(std::move(opening));
}
void
Kubot::OnStep()
{
for (auto& listener : m_listeners)
{
listener->step();
}
m_sc2.draw().update();
m_sc2.debug().SendDebug();
}
void
Kubot::OnUnitCreated(const Unit* unit)
{
static int count = 0; // HACK: skip redundant callbacks for precreated units
if (count < 13)
{
count++;
return;
}
m_map->place_building(*unit);
for (auto& listener : m_listeners)
{
listener->unitCreated(unit);
}
}
void
Kubot::OnBuildingConstructionComplete(const Unit* unit)
{
for (auto& listener : m_listeners)
{
listener->buildingConstructionComplete(unit);
}
}
void
Kubot::OnUnitDestroyed(const Unit* unit)
{
for (auto& listener : m_listeners)
{
listener->unitDestroyed(unit);
}
}
void
Kubot::OnUnitIdle(const Unit* unit)
{
for (auto& listener : m_listeners)
{
listener->unitIdle(unit);
}
}
|
//
// PlayerMoveBehavior.h
// Boids
//
// Created by Yanjie Chen on 3/10/15.
//
//
#ifndef __Boids__PlayerMoveBehavior__
#define __Boids__PlayerMoveBehavior__
#include "BehaviorBase.h"
class PlayerMoveBehavior : public BehaviorBase {
public:
PlayerMoveBehavior();
virtual ~PlayerMoveBehavior();
static PlayerMoveBehavior* create( TargetNode* unit_node );
virtual bool init( TargetNode* unit_node );
virtual bool behave( float delta = 0 );
};
#endif /* defined(__Boids__PlayerMoveBehavior__) */
|
#pragma region Properties
inline const float IIntersector::Get_ContactPoint() const { return this->m_fContactPoint; };
#pragma endregion
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h> // mkfifo
#include <fcntl.h>
#include <signal.h>
#include <sys/wait.h>
#include <time.h>
#include <errno.h>
#define READ 0
#define WRITE 1
#define BUFSIZE 100
#define MAX_JOBS 3
#define FINISHED 0
#define ACTIVE 4
using namespace std;
class Job{
int jid;
int pid;
int status;
bool finished;
public:
Job(int jid,int pid){
this->jid=jid;
this->pid=pid;
this->finished=false;
}
int getPid(){
return pid;
}
int getJid(){
return jid;
}
void setFinished(){
finished=true;
}
bool isFinished(){
if(finished) return true;
else return false;
}
};
class Pool{
const int max_jobs;
int current_jobs;
bool dead;
Job **jobs;
int fd_in;
int fd_out;
int pid;
public:
Pool(int pid,int max,int fd_in,int fd_out):max_jobs(max){
this->pid=pid;
jobs=new Job*[max_jobs];
current_jobs=0;
dead=false;
this->fd_in=fd_in;
this->fd_out=fd_out;
}
int getPid(){
return pid;
}
~Pool(){
for(int i=0;i<current_jobs;i++){
delete jobs[i];
}
delete [] jobs;
}
bool isFull(){
if(current_jobs>=max_jobs) return true;
else return false;
}
int addJob(int jid,char * entoli){
if(isFull() == true){
return -1;
}
//strcpy(entoli,"/bin/ls -l");
// if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
// perror("signal");
char newentoli[100];
sprintf(newentoli,"%d %s",jid,entoli);
if(write(fd_in, newentoli, BUFSIZE)==-1){
if (errno == EPIPE) {
/* Closed pipe. */
printf("ERROR IN PIPE");
exit(1);
}
}else{
int bytes=read(fd_out, entoli, BUFSIZE); // diavazw to response to opoio einai to pid
//printf("3e--KOLLISE EDW\n"); fflush(stdout);
if(bytes>0){
//printf("Got response: %s from pool\n",entoli);
//fflush(stdout);
}else{
printf("Didn't get response from pool\n");
fflush(stdout);
exit(1);
}
}
//write(fd_in, entoli, BUFSIZE);
//printf("KOLLISE EDW\n"); fflush(stdout);
int pid=atoi(entoli);
jobs[current_jobs]=new Job(jid,pid);
current_jobs++;
return pid;
}
bool containsJob(int jid){
int flag = 0;
for(int i=0;i<current_jobs;i++){
if(jobs[i]->getJid()==jid){
flag = 1;
}
}
if(flag == 1) return true;
return false;
}
int getJobStatus(int jid){
// if pool is dead
if(isDead() == true){
return 0; // finished
}
for(int i=0;i<current_jobs;i++){
if(jobs[i]->getJid()==jid){
if(jobs[i]->isFinished()){
//printf("CHECK THIS\n");
fflush(stdout);
return 0;
}
char entoli[BUFSIZE];
sprintf(entoli, "status %d", jobs[i]->getPid());
if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
perror("signal");
write(fd_in, entoli, sizeof(entoli));
int bytes=read(fd_out,entoli,sizeof(entoli));
if(bytes<=0){
printf("Error getting response for status...\n");
exit(1);
}else{
//printf("Got response %d bytes from pool for state: %s\n",bytes,entoli);
}
if(strcmp(entoli,"FINISHED")==0){
//printf("Coordinator[] Got FINISHED from pool...Marking dead...\n");fflush(stdout);
dead=true;
return 0;
}else{
int response=atoi(entoli);
if(response==0){
jobs[i]->setFinished();
}
return response;
}
}
}
return -1;
}
bool suspendJob(int jid){
for(int i=0;i<current_jobs;i++){
if(jobs[i]->getJid()==jid){
kill(jobs[i]->getPid(),SIGSTOP);
return true;
}
}
return false;
}
bool continueJob(int jid){
for(int i=0;i<current_jobs;i++){
if(jobs[i]->getJid()==jid){
kill(jobs[i]->getPid(),SIGCONT);
return true;
}
}
return false;
}
bool isFinishedJob(int jid){
for(int i=0;i<current_jobs;i++){
if(jobs[i]->getJid()==jid){
if(jobs[i]->isFinished() == true){
return true;
}else{
// get status
if(getJobStatus(jid)==0){
return true;
}
}
}
}
}
void statusAll(int jms_out){
for(int i=0;i<current_jobs;i++){
// printf("KOLLISE\n"); fflush(stdout);
int status=getJobStatus(jobs[i]->getJid());
char entoli[BUFSIZE];
char status_s[20];
switch(status){
case -1: strcpy(status_s,"Not exists"); break;
case 0: strcpy(status_s,"Finished"); break;
case 1: strcpy(status_s,"Signal"); break;
case 2: strcpy(status_s,"Suspended"); break;
case 3: strcpy(status_s,"Continued"); break;
default: strcpy(status_s,"Active"); break;
}
sprintf(entoli, "JobID: %d Status: %s", jobs[i]->getJid(),status_s);
write(jms_out, entoli, sizeof(entoli));
}
}
void showActive(int jms_out){
for(int i=0;i<current_jobs;i++){
int status=getJobStatus(jobs[i]->getJid());
if(status==ACTIVE){
char entoli[BUFSIZE];
sprintf(entoli, "JobID: %d", jobs[i]->getJid());
write(jms_out, entoli, sizeof(entoli));
}
}
}
int showActive(){
int active=0;
for(int i=0;i<current_jobs;i++){
int status=getJobStatus(jobs[i]->getJid());
if(status==ACTIVE){
active++;
}
}
return active;
}
void showFinished(int jms_out){
for(int i=0;i<current_jobs;i++){
int status=getJobStatus(jobs[i]->getJid());
if(status==FINISHED){
char entoli[BUFSIZE];
sprintf(entoli, "JobID: %d", jobs[i]->getJid());
write(jms_out, entoli, sizeof(entoli));
}
}
}
void showPool(int jms_out){
if(isDead()){
return;
}
int active=0;
for(int i=0;i<current_jobs;i++){
int status=getJobStatus(jobs[i]->getJid());
fflush(stdout);
if(status==ACTIVE){
active++;
}
}
char entoli[BUFSIZE];
sprintf(entoli, "%d\t%d\t%d",pid, active,current_jobs);
write(jms_out, entoli, sizeof(entoli));
}
int sendSigterm(){
if(isDead() == true){ //already dead
return 0;
}
//char entoli[BUFSIZE];
//sprintf(entoli, "SIGTERM");
int active=showActive();
kill(pid,SIGTERM);
// write(fd_in, entoli, sizeof(entoli));
return active;
}
bool isDead(){
return dead;
}
};
class PoolNode
{
public:
Pool* data;
PoolNode* previous;
PoolNode* next;
PoolNode(Pool* d, PoolNode * n){
this->data = d;
this->next = n;
}
~PoolNode(){
delete data;
}
};
class PoolList
{
PoolNode * start;
public:
PoolList(){
start = NULL;
}
~PoolList(){
PoolNode * temp1 = start;
while(temp1!=NULL){
PoolNode * temp2 = temp1->next;
delete temp1;
temp1 = temp2;
}
}
PoolNode *getStart(){
return start;
}
bool add(Pool * p){
if(start == NULL){
start = new PoolNode(p, NULL);
}else{
PoolNode * newnode = new PoolNode(p, start);
start = newnode;
}
if(start == NULL){
return false;
}
return true;
}
Pool * getAvailablePool(){
if(start!=NULL && !start->data->isFull()){
return start->data;
}
return NULL;
}
int getJobStatus(int jid){
PoolNode * temp = start;
int jobStatus;
while(temp!=NULL){
//printf("EEEEE 1\n");
if(temp->data->containsJob(jid) == true){
jobStatus = temp->data->getJobStatus(jid);
//printf("EEEEE 2\n");
return jobStatus;
}
temp = temp->next;
}
//printf("EEEEE 3\n");
return -1; // an epistrafei -1 simainei oti den uparxei job me to dothen jid
}
bool suspendJob(int jid){
PoolNode * temp = start;
bool flag = false;
while(temp!=NULL){
if(temp->data->containsJob(jid) == true){
flag = temp->data->suspendJob(jid);
return flag;
}
temp = temp->next;
}
return false;
}
bool continueJob(int jid){
PoolNode * temp = start;
bool flag = false;
while(temp!=NULL){
if(temp->data->containsJob(jid)){
flag = temp->data->continueJob(jid);
return flag;
}
temp = temp->next;
}
return false;
}
void statusAll(int jms_out){
PoolNode * temp = start;
while(temp!=NULL){
temp->data->statusAll(jms_out);
temp = temp->next;
}
}
void showActive(int jms_out){
PoolNode * temp = start;
while(temp!=NULL){
temp->data->showActive(jms_out);
temp = temp->next;
}
}
void showFinished(int jms_out){
PoolNode * temp = start;
while(temp!=NULL){
temp->data->showFinished(jms_out);
temp = temp->next;
}
}
void showPool(int jms_out){
PoolNode * temp = start;
while(temp!=NULL){
temp->data->showPool(jms_out);
temp = temp->next;
}
}
int sendSigterm(){
int active=0;
PoolNode * temp = start;
while(temp!=NULL){
active+= temp->data->sendSigterm();
temp = temp->next;
}
return active;
}
};
|
#include "Common.h"
#include "Tools.h"
#include "Application.h"
int __stdcall wWinMain(HINSTANCE, HINSTANCE, LPWSTR, INT) {
#ifdef _DEBUG
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
auto res = make_unique<Application>()->Run();
#ifdef _DEBUG
system("pause");
#endif
return res;
}
|
// *****************************************************************
// This file is part of the CYBERMED Libraries
//
// Copyright (C) 2011 LabTEVE (http://www.de.ufpb.br/~labteve),
// Federal University of Paraiba.
// All rights reserved.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free
// Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301, USA.
// *****************************************************************
#include "cybAABB.h"
CybAABB::CybAABB(int layer, CybInterator* interator, bool iib, bool draw)
: CybBroadCollision(layer, interator)
{
isInteratorBox = iib;
calculateCenterAndSizes();
realCenter = center;
realSizes = sizes;
initialSizes = sizes;
if(iib)getInteratorTransformations(lastTransf);
else getMeshTransformations(lastTransf);
if(!draw) drawer = NULL;
else{
CybVector3D<float> scale, translation;
translation[0] = lastTransf[0]; translation[1] = lastTransf[1]; translation[2] = lastTransf[2];
scale[0] = lastTransf[3]; scale[1] = lastTransf[4]; scale[2] = lastTransf[5];
drawer = new CybAABBDrawer(center, sizes, scale, translation);
}
calculateRealCenter();
calculateRealSizes();
CybCollisionObserver::getInstance()->addCollisionObject(this, "broad");
}
CybAABB::CybAABB(int layer, int interatorId, bool iib, bool draw)
: CybBroadCollision(layer, interatorId)
{
isInteratorBox = iib;
calculateCenterAndSizes();
realCenter = center;
realSizes = sizes;
initialSizes = sizes;
if(iib)getInteratorTransformations(lastTransf);
else getMeshTransformations(lastTransf);
if(!draw) drawer = NULL;
else{
CybVector3D<float> scale, translation;
translation[0] = lastTransf[0]; translation[1] = lastTransf[1]; translation[2] = lastTransf[2];
scale[0] = lastTransf[3]; scale[1] = lastTransf[4]; scale[2] = lastTransf[5];
drawer = new CybAABBDrawer(center, sizes, scale, translation);
}
calculateRealCenter();
calculateRealSizes();
CybCollisionObserver::getInstance()->addCollisionObject(this, "broad");
}
CybAABB::CybAABB(const CybAABB& caixa)
: CybBroadCollision(caixa.layerOfCollision, getInterator())
{
center = caixa.center;
sizes = caixa.sizes;
listOfTriangles = caixa.listOfTriangles;
collisionStatus = false;
isInteratorBox = caixa.isInteratorBox;
realCenter = caixa.realCenter;
realSizes = caixa.realSizes;
initialSizes = caixa.initialSizes;
drawer = caixa.drawer;
for(int i = 0; i < 9; ++ i) lastTransf[i] = caixa.lastTransf[i];
CybCollisionObserver::getInstance()->addCollisionObject(this, "broad");
}
CybAABB::CybAABB(CybNarrowCollision *narrow, bool iib, bool draw)
: CybBroadCollision(narrow->getLayerOfCollision(), narrow->getInterator())
{
isInteratorBox = iib;
calculateCenterAndSizes();
realCenter = center;
realSizes = sizes;
initialSizes = sizes;
if(iib)getInteratorTransformations(lastTransf);
else getMeshTransformations(lastTransf);
if(!draw) drawer = NULL;
else{
CybVector3D<float> scale, translation;
translation[0] = lastTransf[0]; translation[1] = lastTransf[1]; translation[2] = lastTransf[2];
scale[0] = lastTransf[3]; scale[1] = lastTransf[4]; scale[2] = lastTransf[5];
drawer = new CybAABBDrawer(center, sizes, scale, translation);
}
calculateRealCenter();
calculateRealSizes();
CybCollisionObserver::getInstance()->addCollisionObject(this, "broad");
}
CybAABB& CybAABB::operator=(const CybAABB& caixa)
{
if(this == &caixa) return *this; //self-assignment
listOfTriangles.clear(); //emptying list
center = caixa.center;
sizes = caixa.sizes;
setInterator(getInterator());
layerOfCollision = caixa.layerOfCollision;
listOfTriangles = caixa.listOfTriangles;
realCenter = caixa.realCenter;
realSizes = caixa.realSizes;
isInteratorBox = caixa.isInteratorBox;
initialSizes = caixa.initialSizes;
drawer = caixa.drawer;
for(int i = 0; i < 9; ++ i) lastTransf[i] = caixa.lastTransf[i];
objectIndex = caixa.objectIndex;
}
void CybAABB::addTest(CybAABB* c)
{
testList.push_back(c);
}
void CybAABB::calculateCenterAndSizes()
{
float maxX = 0, maxY = 0, maxZ = 0;
float minX = 0, minY = 0, minZ = 0;
cybMesh<cybSurfaceTriTraits>* mesh;
if(isInteratorBox) mesh = getInterator()->getMesh(getInterator()->getActiveMesh());
else mesh = CybParameters::getInstance()->mesh[layerOfCollision];
int numVertex = mesh->getNumberOfVertices();
for(int i = 0; i != numVertex; i++)
{
if(maxX < mesh->getVertex(i)->getCoord(0)) maxX = mesh->getVertex(i)->getCoord(0);
if(minX > mesh->getVertex(i)->getCoord(0)) minX = mesh->getVertex(i)->getCoord(0);
if(maxY < mesh->getVertex(i)->getCoord(1)) maxY = mesh->getVertex(i)->getCoord(1);
if(minY > mesh->getVertex(i)->getCoord(1)) minY = mesh->getVertex(i)->getCoord(1);
if(maxZ < mesh->getVertex(i)->getCoord(2)) maxZ = mesh->getVertex(i)->getCoord(2);
if(minZ > mesh->getVertex(i)->getCoord(2)) minZ = mesh->getVertex(i)->getCoord(2);
}
center[0] = (fabs(maxX) - fabs(minX))/2;
center[1] = (fabs(maxY) - fabs(minY))/2;
center[2] = (fabs(maxZ) - fabs(minZ))/2;
sizes[0] = (fabs(maxX) + fabs(minX))/2;
sizes[1] = (fabs(maxY) + fabs(minY))/2;
sizes[2] = (fabs(maxZ) + fabs(minZ))/2;
}
void CybAABB::calculateRealCenter()
{
realCenter[0] = (center[0] + lastTransf[0]) * lastTransf[3];
realCenter[1] = (center[1] + lastTransf[1]) * lastTransf[4];
realCenter[2] = (center[2] + lastTransf[2]) * lastTransf[5];
}
void CybAABB::calculateRealSizes()
{
realSizes[0] = sizes[0] * lastTransf[3];
realSizes[1] = sizes[1] * lastTransf[4];
realSizes[2] = sizes[2] * lastTransf[5];
}
void CybAABB::calculateRotatedSizes(int axis, float angle, float* values)
{
int rot1, rot2;
if(axis == 0){ rot1 = 1; rot2 = 2; }
else if(axis == 1){ rot1 = 0; rot2 = 2; }
else if(axis == 2){ rot1 = 0; rot2 = 1; }
else return;
float aux = angle/180;
if(aux == (int) aux) return; //If the angle is an exact multiple of 180, the sizes remain the same.
aux = angle/90;
if(aux == (int) aux){
float swap = values[rot1];
values[rot1] = values[rot2];
values[rot2] = swap;
return;
}//If the angle is an exact odd multiple of 90 (90 * {1,3,5,...}), we exchange the values of the sizes.
float hyp = sqrt(pow(values[rot1], 2) + pow(values[rot2], 2)); //we might need this from now on.
aux = angle/45;
if(aux = (int) aux){
values[rot1] = hyp;
values[rot2] = hyp;
return;
}//If the angle is an exact odd multiple of 45 (45 * {1,3,5,...}), the box becomes the maximum area square
//because the sizes are now equal to the hypotenuse of the triangle formed by them.
/*From this point on we separate the treatment of the rotation in intervals, according to the angle.*/
float size1, size2;
if((angle > 0.0 && angle < 45.0) || (angle > 180.0 && angle < 225.0)){
size1 = values[rot1] + values[rot2]*tan(degToRad(angle));
size2 = values[rot2] + values[rot1]*tan(degToRad(angle));
}
else if((angle > 135.0 && angle < 180.0) || (angle > 315.0 && angle < 360.0)){
size1 = values[rot1] - values[rot2]*tan(degToRad(angle));
size2 = values[rot2] - values[rot1]*tan(degToRad(angle));
}
else if((angle > 90.0 && angle < 135.0) || (angle > 270.0 && angle < 315.0)){
size1 = values[rot2] + values[rot1]*tan(degToRad(angle - 90.0));
size2 = values[rot1] + values[rot2]*tan(degToRad(angle - 90.0));
}
else if((angle > 45.0 && angle < 90.0) || (angle > 225.0 && angle < 270.0)){
size1 = values[rot2] - values[rot1]*tan(degToRad(angle - 90.0));
size2 = values[rot1] - values[rot2]*tan(degToRad(angle - 90.0));
}
if(size1 > hyp) values[rot1] = hyp;
else values[rot1] = size1;
if(size2 > hyp) values[rot2] = hyp;
else values[rot2] = size2;
return;
}
bool CybAABB::collision(CybAABB& c)
{
if(fabs(realCenter[0] - c.getRealCenter()[0]) > (realSizes[0] + c.getRealSizes()[0])){ return false;}
if(fabs(realCenter[1] - c.getRealCenter()[1]) > (realSizes[1] + c.getRealSizes()[1])){ return false; }
if(fabs(realCenter[2] - c.getRealCenter()[2]) > (realSizes[2] + c.getRealSizes()[2])){ return false; }
return true;
}
float CybAABB::degToRad(float angle)
{
return angle*PI/180;
}
void CybAABB::describeBox()
{
cout << "A coordenada x do centro da caixa e: " << center[0] << endl;
cout << "A coordenada y do centro da caixa e: " << center[1] << endl;
cout << "A coordenada z do centro da caixa e: " << center[2] << endl;
cout << "O semi-comprimento x da caixa e: " << sizes[0] << endl;
cout << "O semi-comprimento y da caixa e: " << sizes[1] << endl;
cout << "O semi-comprimento z da caixa e: " << sizes[2] << endl;
}
void CybAABB::destroy()
{
CybThread::destroy();
}
CybVector3D<float>& CybAABB::getCenter()
{
return center;
}
CybAABBDrawer* CybAABB::getDrawer()
{
return drawer;
}
void CybAABB::getInteratorTransformations(float *t){
CybThread::lock();
for(int i = 0; i < 9; ++i){
if(i < 3){
t[i] = getInterator()->getTranslation()[i];
}else if(i >= 3 && i < 6){
t[i] = getInterator()->getScale()[i-3];
}else t[i] = getInterator()->getRotation()[i-6];
}
CybThread::unlock();
}
void CybAABB::getMeshTransformations(float *t){
CybThread::lock();
CybParameters* cybcore = CybParameters::getInstance();
t[0] = cybcore->xTrans + cybcore->layerTrans[layerOfCollision][0];
t[1] = cybcore->yTrans + cybcore->layerTrans[layerOfCollision][1];
t[2] = cybcore->zTrans + cybcore->layerTrans[layerOfCollision][2];
t[3] = cybcore->xScale * cybcore->layerSca[layerOfCollision][0];
t[4] = cybcore->yScale * cybcore->layerSca[layerOfCollision][1];
t[5] = cybcore->zScale * cybcore->layerSca[layerOfCollision][2];
t[6] = cybcore->getXAngle() + cybcore->layerRot[layerOfCollision][0];
t[7] = cybcore->getYAngle() + cybcore->layerRot[layerOfCollision][1];
t[8] = cybcore->getZAngle() + cybcore->layerRot[layerOfCollision][2];
CybThread::unlock();
}
int CybAABB::getObjectIndex()
{
return objectIndex;
}
CybVector3D<float>& CybAABB::getRealCenter()
{
return realCenter;
}
CybVector3D<float>& CybAABB::getRealSizes()
{
return realSizes;
}
CybVector3D<float>& CybAABB::getSizes()
{
return sizes;
}
list<CybAABB*> CybAABB::getTestList()
{
return testList;
}
void CybAABB::init()
{
CybThread::init();
}
void CybAABB::removeTest(CybAABB* c)
{
list<CybAABB*>::iterator it;
for(it = testList.begin(); it != testList.end(); ++it)
{
CybThread::lock();
if((*it) == c) testList.remove(c);
CybThread::unlock();
}
}
void CybAABB::run()
{
list<CybAABB*>::iterator it;
CybThread::lock();
CybCollisionObserver* observer = CybCollisionObserver::getInstance();
bool teste;
for(it = testList.begin(); it != testList.end(); ++it)
{
teste = collision(*(*it));
observer->changeState(this, (*it), teste);
}
CybThread::unlock();
update();
}
void CybAABB::setCenter(CybVector3D<float>& center)
{
this->center = center;
}
void CybAABB::setCenter(float cx, float cy, float cz)
{
center[0] = cx;
center[1] = cy;
center[2] = cz;
}
void CybAABB::setSizes(CybVector3D<float>& sizes)
{
this->sizes = sizes;
}
void CybAABB::setSizes(float sx, float sy, float sz)
{
sizes[0] = sx;
sizes[1] = sy;
sizes[2] = sz;
}
void CybAABB::treatRotation(float* transf, bool* axis)
{
float rotX[3] = {initialSizes[0], initialSizes[1], initialSizes[2]};
float rotY[3] = {initialSizes[0], initialSizes[1], initialSizes[2]};
float rotZ[3] = {initialSizes[0], initialSizes[1], initialSizes[2]};;
float *auxRot[3] = {rotX, rotY, rotZ};
for(int i = 0; i < 3; ++i){
if(axis[i]){
calculateRotatedSizes(i, transf[i + 6], auxRot[i]);
}
}
sizes[0] = max(max(rotX[0], rotY[0]), rotZ[0]);
sizes[1] = max(max(rotX[1], rotY[1]), rotZ[1]);
sizes[2] = max(max(rotX[2], rotY[2]), rotZ[2]);
drawer->setSizes(sizes);
calculateRealCenter();
calculateRealSizes();
describeBox();
}
void CybAABB::update()
{
CybCollision::update();
if(isInteratorBox){
CybThread::lock();
CybVector3D<float> aux = CybCollisionData::getInstance()->getInteratorPositionInGraphicsCoordenates();
setCenter(aux);
drawer->setCenter(aux);
CybThread::unlock();
calculateRealCenter();
}
float transf[9];
if(isInteratorBox) getInteratorTransformations(transf);
else getMeshTransformations(transf);
//treating rotation
bool mudancaR = false;
bool eixos[3] = {false, false, false};
for(int k = 6; k < 9; ++k){
if(lastTransf[k] != transf[k]){
lastTransf[k] = transf[k];
mudancaR = true;
eixos[k-6] = true;
}
}
if(mudancaR) treatRotation(lastTransf, eixos);
//treating scale and translation
bool mudanca = false;
for(int j = 0; j < 6; ++j){
if(lastTransf[j] != transf[j]){
lastTransf[j] = transf[j];
mudanca = true;
}
}
if(mudanca){
calculateRealCenter();
calculateRealSizes();
CybVector3D<float> scale, translation;
translation[0] = lastTransf[0]; translation[1] = lastTransf[1]; translation[2] = lastTransf[2];
scale[0] = lastTransf[3]; scale[1] = lastTransf[4]; scale[2] = lastTransf[5];
drawer->setTranslation(translation);
drawer->setScale(scale);
}
}
void CybAABB::updateBox(float cx, float cy, float cz)
{
setCenter(cx,cy,cz);
}
|
#include<stdio.h>
class Character{
float m_pos;
void Move();
};
class Item{
char* name;
};
class Player:Character{
Item has_item;
};
int main(){
return 0;
}
|
int cdma_func(
// config register
int f_pingpong ,
int cbuf_dat0_address ,
int cbuf_dat1_address ,
int cbuf_wt0_address ,
int cbuf_wt1_address ,
int ddr_dat_address ,
int ddr_wt_address ,
int ddr_wt_size_norm ,
int ddr_wt_size_last ,
int num_wt_tile ,
int num_adding_zero_input_channel_cdma ,
int tile_dat_type ,
int tile_size_x_1_no_extend ,
int tile_size_y_1_no_extend ,
int tile_size_x_2_no_extend ,
int tile_size_y_2_no_extend ,
int tile_size_x_3_no_extend ,
int tile_size_y_3_no_extend ,
int tile_size_x_4_no_extend ,
int tile_size_y_4_no_extend ,
int tile_size_x_5_no_extend ,
int tile_size_y_5_no_extend ,
int tile_size_x_6_no_extend ,
int tile_size_y_6_no_extend ,
int tile_size_x_7_no_extend ,
int tile_size_y_7_no_extend ,
int tile_size_x_8_no_extend ,
int tile_size_y_8_no_extend ,
int tile_size_x_9_no_extend ,
int tile_size_y_9_no_extend ,
int tile_num_x_c ,
int tile_num_y_c ,
int ddr_size_input_channel ,
int extend_dat_type_1_num_1_r,
int extend_dat_type_1_num_2_l,
int extend_dat_type_2_num_1_b,
int extend_dat_type_2_num_2_t,
int extend_dat_type_3_num_1_b,
int extend_dat_type_3_num_1_r,
int extend_dat_type_3_num_2_b,
int extend_dat_type_3_num_2_l,
int extend_dat_type_3_num_3_t,
int extend_dat_type_3_num_3_r,
int extend_dat_type_3_num_4_t,
int extend_dat_type_3_num_4_l,
int extend_dat_type_4_num_1_b,
int extend_dat_type_4_num_1_r,
int extend_dat_type_4_num_2_b,
int extend_dat_type_4_num_2_l,
int extend_dat_type_4_num_2_r,
int extend_dat_type_4_num_3_b,
int extend_dat_type_4_num_3_l,
int extend_dat_type_4_num_4_t,
int extend_dat_type_4_num_4_r,
int extend_dat_type_4_num_5_t,
int extend_dat_type_4_num_5_l,
int extend_dat_type_4_num_5_r,
int extend_dat_type_4_num_6_t,
int extend_dat_type_4_num_6_l,
int extend_dat_type_5_num_1_b,
int extend_dat_type_5_num_1_r,
int extend_dat_type_5_num_2_b,
int extend_dat_type_5_num_2_l,
int extend_dat_type_5_num_3_t,
int extend_dat_type_5_num_3_b,
int extend_dat_type_5_num_3_r,
int extend_dat_type_5_num_4_t,
int extend_dat_type_5_num_4_b,
int extend_dat_type_5_num_4_l,
int extend_dat_type_5_num_5_t,
int extend_dat_type_5_num_5_r,
int extend_dat_type_5_num_6_t,
int extend_dat_type_5_num_6_l,
int extend_dat_type_6_num_1_b,
int extend_dat_type_6_num_1_r,
int extend_dat_type_6_num_2_b,
int extend_dat_type_6_num_2_l,
int extend_dat_type_6_num_2_r,
int extend_dat_type_6_num_3_b,
int extend_dat_type_6_num_3_l,
int extend_dat_type_6_num_4_t,
int extend_dat_type_6_num_4_b,
int extend_dat_type_6_num_4_r,
int extend_dat_type_6_num_5_t,
int extend_dat_type_6_num_5_b,
int extend_dat_type_6_num_5_l,
int extend_dat_type_6_num_5_r,
int extend_dat_type_6_num_6_t,
int extend_dat_type_6_num_6_b,
int extend_dat_type_6_num_6_l,
int extend_dat_type_6_num_7_t,
int extend_dat_type_6_num_7_r,
int extend_dat_type_6_num_8_t,
int extend_dat_type_6_num_8_l,
int extend_dat_type_6_num_8_r,
int extend_dat_type_6_num_9_t,
int extend_dat_type_6_num_9_l,
int address_incr_dat_type_0_num_1,
int address_incr_dat_type_1_num_1,
int address_incr_dat_type_1_num_2,
int address_incr_dat_type_2_num_1,
int address_incr_dat_type_2_num_2,
int address_incr_dat_type_3_num_1,
int address_incr_dat_type_3_num_2,
int address_incr_dat_type_3_num_3,
int address_incr_dat_type_3_num_4,
int address_incr_dat_type_4_num_1,
int address_incr_dat_type_4_num_2,
int address_incr_dat_type_4_num_3,
int address_incr_dat_type_4_num_4,
int address_incr_dat_type_4_num_5,
int address_incr_dat_type_4_num_6,
int address_incr_dat_type_5_num_1,
int address_incr_dat_type_5_num_2,
int address_incr_dat_type_5_num_3,
int address_incr_dat_type_5_num_4,
int address_incr_dat_type_5_num_5,
int address_incr_dat_type_5_num_6,
int address_incr_dat_type_6_num_1,
int address_incr_dat_type_6_num_2,
int address_incr_dat_type_6_num_3,
int address_incr_dat_type_6_num_4,
int address_incr_dat_type_6_num_5,
int address_incr_dat_type_6_num_6,
int address_incr_dat_type_6_num_7,
int address_incr_dat_type_6_num_8,
int address_incr_dat_type_6_num_9,
// loop counter
int *cnt_num_dat_tile ,
int *cnt_num_wt_tile ,
int *cnt_ddr_wt_address ,
int *cnt_ddr_dat_start_address ,
// data in
int **ddr ,
// data out
int **cbuf
)
{
int num_dat_tile ;
int all_feature_x ;
int all_feature_y ;
int cnt_cbuf_wt_address ;
int cnt_cbuf_dat_address ;
int cnt_ddr_dat_address ;
int cnt_ddr_wt_size ;
int tmp[128][8] ;
int extend_t ;
int extend_b ;
int extend_l ;
int extend_r ;
int tile_size_x ;
int tile_size_y ;
int cnt_address_incr_dat ;
int len_x ;
int len_y ;
int i ;
int j ;
int k ;
int l ;
int m ;
int p ;
int q ;
switch(tile_dat_type){
case 0: {
num_dat_tile = 1;
all_feature_x = tile_size_x_1_no_extend;
all_feature_y = tile_size_y_1_no_extend;
break;
}
case 1: {
num_dat_tile = 2;
all_feature_x = tile_size_x_1_no_extend + tile_size_x_2_no_extend;
all_feature_y = tile_size_y_1_no_extend;
break;
}
case 2: {
num_dat_tile = 2;
all_feature_x = tile_size_x_1_no_extend;
all_feature_y = tile_size_y_1_no_extend + tile_size_y_2_no_extend;
break;
}
case 3: {
num_dat_tile = 4;
all_feature_x = tile_size_x_1_no_extend+ tile_size_y_2_no_extend;
all_feature_y = tile_size_y_1_no_extend + tile_size_y_2_no_extend;
break;
}
case 4: {
num_dat_tile = (2 + tile_num_x_c) * 2;
all_feature_x = tile_size_x_1_no_extend+ tile_size_x_2_no_extend*tile_num_x_c+tile_size_x_3_no_extend;
all_feature_y = tile_size_y_1_no_extend+ tile_size_y_4_no_extend;
break;
}
case 5: {
num_dat_tile = (2 + tile_num_y_c) * 2;
all_feature_x = tile_size_x_1_no_extend+ tile_size_x_2_no_extend;
all_feature_y = tile_size_y_1_no_extend+ tile_size_y_3_no_extend*tile_num_y_c+tile_size_y_5_no_extend;
break;
}
case 6: {
num_dat_tile = (2 + tile_num_x_c) * (2 + tile_num_y_c);
all_feature_x = tile_size_x_1_no_extend+ tile_size_x_2_no_extend*tile_num_x_c+tile_size_x_3_no_extend;
all_feature_y = tile_size_y_1_no_extend+ tile_size_y_4_no_extend*tile_num_y_c+tile_size_y_7_no_extend;
break;
}
default:{
num_dat_tile = 1;
all_feature_x = tile_size_x_1_no_extend;
all_feature_y = tile_size_y_1_no_extend; break;
}
}
if(f_pingpong == 1){
/*-------------------------------------------------------------*/
/* */
/* feature pingpong first */
/* */
/*-------------------------------------------------------------*/
while(1){
if(*cnt_num_wt_tile == num_wt_tile){
return 1;
break;
}
/*-------------------------------*/
/* wt pingpong 1 stage */
/*-------------------------------*/
//switch wt address
if(*cnt_num_wt_tile == 0){
*cnt_ddr_wt_address = ddr_wt_address ;
}
if(*cnt_num_wt_tile%2==0){
cnt_cbuf_wt_address = cbuf_wt0_address;
}
else{
cnt_cbuf_wt_address = cbuf_wt1_address;
}
//switch wt size
if(*cnt_num_wt_tile == num_wt_tile - 1){
cnt_ddr_wt_size = ddr_wt_size_last;
}
else{
cnt_ddr_wt_size = ddr_wt_size_norm;
}
//transfer weight from ddr to cbuf
k=0;
for(i=0;i<cnt_ddr_wt_size;i++){
for(j=0;j<8;j++){
tmp[k][j]=ddr[*cnt_ddr_wt_address][j];
}
if(k==127){
k=0;
for(p=0;p<128;p++){
for(q=0;q<8;q++){
cbuf[cnt_cbuf_wt_address][q+p*8]=tmp[p][q];
}
}
cnt_cbuf_wt_address++;
}
else{
k++;
}
(*cnt_ddr_wt_address)++;
}
/*----------------------------------*/
/* dat pingpong 2 stage */
/*----------------------------------*/
while(1){
// when dat tile ends, wt tile ++
if(*cnt_num_dat_tile == num_dat_tile){
(*cnt_num_wt_tile)++;
*cnt_num_dat_tile=0;
break;
}
if(*cnt_num_dat_tile == 0){
*cnt_ddr_dat_start_address = ddr_dat_address ;
}
//switch dat address
if(*cnt_num_dat_tile%2==0){
cnt_cbuf_dat_address = cbuf_dat0_address;
}
else{
cnt_cbuf_dat_address = cbuf_dat1_address;
}
//prepare extra feature loading, prepare start ddr address
switch(tile_dat_type){
case 0:
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_0_num_1;
break;
}
case 1:
{
if(*cnt_num_dat_tile==0)
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_1_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_1_num_1;
}
else
{
extend_t = 0;
extend_b = 0;
extend_l = extend_dat_type_1_num_2_l;
extend_r = 0;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_1_num_2;
}
break;
}
case 2:
{
if(*cnt_num_dat_tile==0)
{
extend_t = 0;
extend_b = extend_dat_type_2_num_1_b;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_2_num_1;
}
else{
extend_t = extend_dat_type_2_num_2_t;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_2_num_2;
}
break;
}
case 3:
{
switch(*cnt_num_dat_tile)
{
case 0:
{
extend_t = 0;
extend_b = extend_dat_type_3_num_1_b;
extend_l = 0;
extend_r = extend_dat_type_3_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_3_num_1;
break;
}
case 1:
{
extend_t = 0;
extend_b = extend_dat_type_3_num_2_b;
extend_l = extend_dat_type_3_num_2_l;
extend_r = 0;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_3_num_2;
break;
}
case 2:
{
extend_t = extend_dat_type_3_num_3_t;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_3_num_3_r;
tile_size_x = tile_size_x_3_no_extend;
tile_size_y = tile_size_y_3_no_extend;
cnt_address_incr_dat = address_incr_dat_type_3_num_3;
break;
}
case 3:
{
extend_t = extend_dat_type_3_num_4_t;
extend_b = 0;
extend_l = extend_dat_type_3_num_4_l;
extend_r = 0;
tile_size_x = tile_size_x_4_no_extend;
tile_size_y = tile_size_y_4_no_extend;
cnt_address_incr_dat = address_incr_dat_type_3_num_4;
break;
}
}
break;
}
case 4:
{
if(*cnt_num_dat_tile==0)
{
extend_t = 0;
extend_b = extend_dat_type_4_num_1_b;
extend_l = 0;
extend_r = extend_dat_type_4_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_1;
}
else if(*cnt_num_dat_tile <tile_num_x_c+1 && *cnt_num_dat_tile >0)
{
extend_t = 0;
extend_b = extend_dat_type_4_num_2_b;
extend_l = extend_dat_type_4_num_2_l;
extend_r = extend_dat_type_4_num_2_r;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_2;
}
else if(*cnt_num_dat_tile == tile_num_x_c+1)
{
extend_t = 0;
extend_b = extend_dat_type_4_num_3_b;
extend_l = extend_dat_type_4_num_3_l;
extend_r = 0;
tile_size_x = tile_size_x_3_no_extend;
tile_size_y = tile_size_y_3_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_3;
}
else if(*cnt_num_dat_tile==tile_num_x_c+2)
{
extend_t = extend_dat_type_4_num_4_t;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_4_num_4_r;
tile_size_x = tile_size_x_4_no_extend;
tile_size_y = tile_size_y_4_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_4;
}
else if(*cnt_num_dat_tile < tile_num_x_c+1+tile_num_x_c+2 && *cnt_num_dat_tile >tile_num_x_c+2)
{
extend_t = extend_dat_type_4_num_5_t;
extend_b = 0;
extend_l = extend_dat_type_4_num_5_l;
extend_r = extend_dat_type_4_num_5_r;
tile_size_x = tile_size_x_5_no_extend;
tile_size_y = tile_size_y_5_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_5;
}
else if(*cnt_num_dat_tile==tile_num_x_c+1+tile_num_x_c+2)
{
extend_t = extend_dat_type_4_num_6_t;
extend_b = 0;
extend_l = extend_dat_type_4_num_6_l;
extend_r = 0;
tile_size_x = tile_size_x_6_no_extend;
tile_size_y = tile_size_y_6_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_6;
}
else
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_1;
}
break;
}
case 5:
{
if(*cnt_num_dat_tile==0)
{
extend_t = 0;
extend_b = extend_dat_type_5_num_1_b;
extend_l = 0;
extend_r = extend_dat_type_5_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_1;
}
else if(*cnt_num_dat_tile==1)
{
extend_t = 0;
extend_b = extend_dat_type_5_num_2_b;
extend_l = extend_dat_type_5_num_2_l;
extend_r = 0;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_2;
}
else if( (*cnt_num_dat_tile-2) > 0 && (*cnt_num_dat_tile-2) < 2*tile_num_y_c && *cnt_num_dat_tile%2==0 )
{
extend_t = extend_dat_type_5_num_3_t;
extend_b = extend_dat_type_5_num_3_b;
extend_l = 0;
extend_r = extend_dat_type_5_num_3_r;
tile_size_x = tile_size_x_3_no_extend;
tile_size_y = tile_size_y_3_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_3;
}
else if((*cnt_num_dat_tile-2) > 0 && (*cnt_num_dat_tile-2) < 2*tile_num_y_c && *cnt_num_dat_tile%2==1)
{
extend_t = extend_dat_type_5_num_4_t;
extend_b = extend_dat_type_5_num_4_b;
extend_l = extend_dat_type_5_num_4_l;
extend_r = 0;
tile_size_x = tile_size_x_4_no_extend;
tile_size_y = tile_size_y_4_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_4;
}
else if(*cnt_num_dat_tile == 2*(tile_num_y_c+1) )
{
extend_t = extend_dat_type_5_num_5_t;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_5_num_5_r;
tile_size_x = tile_size_x_5_no_extend;
tile_size_y = tile_size_y_5_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_5;
}
else if(*cnt_num_dat_tile == 2*(tile_num_y_c+1)+1 )
{
extend_t = extend_dat_type_5_num_6_t;
extend_b = 0;
extend_l = extend_dat_type_5_num_6_l;
extend_r = 0;
tile_size_x = tile_size_x_6_no_extend;
tile_size_y = tile_size_y_6_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_6;
}
else
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_1;
}
break;
}
case 6:
{
if(*cnt_num_dat_tile=0)
{
extend_t = 0;
extend_b = extend_dat_type_6_num_1_b;
extend_l = 0;
extend_r = extend_dat_type_6_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_1;
}
else if(*cnt_num_dat_tile < tile_num_x_c+1 && *cnt_num_dat_tile >0)
{
extend_t = 0;
extend_b = extend_dat_type_6_num_2_b;
extend_l = extend_dat_type_6_num_2_l;
extend_r = extend_dat_type_6_num_2_r;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_2;
}
else if(*cnt_num_dat_tile==tile_num_x_c+1)
{
extend_t = 0;
extend_b = extend_dat_type_6_num_3_b;
extend_l = extend_dat_type_6_num_3_l;
extend_r = 0;
tile_size_x = tile_size_x_3_no_extend;
tile_size_y = tile_size_y_3_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_3;
}
else if(*cnt_num_dat_tile==tile_num_x_c+2)
{
extend_t = extend_dat_type_6_num_4_t;
extend_b = extend_dat_type_6_num_4_b;
extend_l = 0;
extend_r = extend_dat_type_6_num_4_r;
tile_size_x = tile_size_x_4_no_extend;
tile_size_y = tile_size_y_4_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_4;
}
else if(*cnt_num_dat_tile>tile_num_x_c+2 &&
*cnt_num_dat_tile<(tile_num_x_c+2)*(tile_num_y_c+1) &&
*cnt_num_dat_tile % (tile_num_x_c+2)!=0 &&
(*cnt_num_dat_tile-1)%(tile_num_x_c+2)!=0)
{
extend_t = extend_dat_type_6_num_5_t;
extend_b = extend_dat_type_6_num_5_b;
extend_l = extend_dat_type_6_num_5_l;
extend_r = extend_dat_type_6_num_5_r;
tile_size_x = tile_size_x_5_no_extend;
tile_size_y = tile_size_y_5_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_5;
}
else if(*cnt_num_dat_tile == (tile_num_x_c+2)*(tile_num_y_c+1)-1 )
{
extend_t = extend_dat_type_6_num_6_t;
extend_b = extend_dat_type_6_num_6_b;
extend_l = extend_dat_type_6_num_6_l;
extend_r = 0;
tile_size_x = tile_size_x_6_no_extend;
tile_size_y = tile_size_y_6_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_6;
}
else if(*cnt_num_dat_tile == (tile_num_x_c+2)*(tile_num_y_c+1) )
{
extend_t = extend_dat_type_6_num_7_t;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_6_num_7_r;
tile_size_x = tile_size_x_7_no_extend;
tile_size_y = tile_size_y_7_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_7;
}
else if(*cnt_num_dat_tile > (tile_num_x_c+2)*(tile_num_y_c+1) &&
*cnt_num_dat_tile < (tile_num_x_c+2)*(tile_num_y_c+2)-1)
{
extend_t = extend_dat_type_6_num_8_t;
extend_b = 0;
extend_l = extend_dat_type_6_num_8_l;
extend_r = extend_dat_type_6_num_8_r;
tile_size_x = tile_size_x_8_no_extend;
tile_size_y = tile_size_y_8_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_8;
}
else if(*cnt_num_dat_tile = (tile_num_x_c+2)*(tile_num_y_c+2)-1)
{
extend_t = extend_dat_type_6_num_9_t;
extend_b = 0;
extend_l = extend_dat_type_6_num_9_l;
extend_r = 0;
tile_size_x = tile_size_x_9_no_extend;
tile_size_y = tile_size_y_9_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_9;
}
else
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_1;
}
break;
}
default:
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_0_num_1;
break;
}
}
//transfer data from ddr to cbuf
cnt_ddr_dat_address = *cnt_ddr_dat_start_address -(extend_l+extend_t*all_feature_y)*ddr_size_input_channel ;
len_y = extend_t + extend_b + tile_size_y ;
len_x = extend_l + extend_r + tile_size_x ;
for(i=0;i<len_y;i++)
{
for(j=0;j<len_x ;j++){
m=0;
for(k=0;k<ddr_size_input_channel;k++){
for(l=0;l<8;l++){
tmp[m][l]=ddr[cnt_ddr_dat_address][l];
}
cnt_ddr_dat_address++;
if(m==127){
for(p=0;p<128;p++){
for(q=0;q<8;q++){
cbuf[cnt_cbuf_dat_address][q+p*8]=tmp[p][q];
}
}
cnt_cbuf_dat_address++;
m=0;
}
else{
m++;
}
}
for(k=0;k<num_adding_zero_input_channel_cdma;k++){
for(l=0;l<8;l++){
tmp[m][l]=0;
}
if(m==127){
for(p=0;p<128;p++){
for(q=0;q<8;q++){
cbuf[cnt_cbuf_dat_address][q+p*8]=tmp[p][q];
}
}
cnt_cbuf_dat_address++;
m=0;
}
else{
m++;
}
}
}
cnt_ddr_dat_address = cnt_ddr_dat_address+ddr_size_input_channel *(all_feature_x-len_x);
}
(*cnt_num_dat_tile)++;
*cnt_ddr_dat_start_address = cnt_address_incr_dat + *cnt_ddr_dat_start_address;
}
}
}
// dat pingpong first end //
else{
while(1){
/*----------------------------------*/
/* dat pingpong 1 stage */
/*----------------------------------*/
if(*cnt_num_dat_tile == num_dat_tile){
return 1;
break;
}
if(*cnt_num_dat_tile == 0){
*cnt_ddr_dat_start_address = ddr_dat_address ;
}
//switch dat address
if(*cnt_num_dat_tile %2==0){
cnt_cbuf_dat_address = cbuf_dat0_address;
}
else{
cnt_cbuf_dat_address = cbuf_dat1_address;
}
//prepare extra feature loading, prepare start ddr address
switch(tile_dat_type){
case 0:
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_0_num_1;
break;
}
case 1:
{
if(*cnt_num_dat_tile==0)
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_1_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_1_num_1;
}
else
{
extend_t = 0;
extend_b = 0;
extend_l = extend_dat_type_1_num_2_l;
extend_r = 0;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_1_num_2;
}
break;
}
case 2:
{
if(*cnt_num_dat_tile==0)
{
extend_t = 0;
extend_b = extend_dat_type_2_num_1_b;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_2_num_1;
}
else{
extend_t = extend_dat_type_2_num_2_t;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_2_num_2;
}
break;
}
case 3:
{
switch(*cnt_num_dat_tile)
{
case 0:
{
extend_t = 0;
extend_b = extend_dat_type_3_num_1_b;
extend_l = 0;
extend_r = extend_dat_type_3_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_3_num_1;
break;
}
case 1:
{
extend_t = 0;
extend_b = extend_dat_type_3_num_2_b;
extend_l = extend_dat_type_3_num_2_l;
extend_r = 0;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_3_num_2;
break;
}
case 2:
{
extend_t = extend_dat_type_3_num_3_t;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_3_num_3_r;
tile_size_x = tile_size_x_3_no_extend;
tile_size_y = tile_size_y_3_no_extend;
cnt_address_incr_dat = address_incr_dat_type_3_num_3;
break;
}
case 3:
{
extend_t = extend_dat_type_3_num_4_t;
extend_b = 0;
extend_l = extend_dat_type_3_num_4_l;
extend_r = 0;
tile_size_x = tile_size_x_4_no_extend;
tile_size_y = tile_size_y_4_no_extend;
cnt_address_incr_dat = address_incr_dat_type_3_num_4;
break;
}
}
break;
}
case 4:
{
if(*cnt_num_dat_tile==0)
{
extend_t = 0;
extend_b = extend_dat_type_4_num_1_b;
extend_l = 0;
extend_r = extend_dat_type_4_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_1;
}
else if(*cnt_num_dat_tile <tile_num_x_c+1 && *cnt_num_dat_tile >0)
{
extend_t = 0;
extend_b = extend_dat_type_4_num_2_b;
extend_l = extend_dat_type_4_num_2_l;
extend_r = extend_dat_type_4_num_2_r;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_2;
}
else if(*cnt_num_dat_tile == tile_num_x_c+1)
{
extend_t = 0;
extend_b = extend_dat_type_4_num_3_b;
extend_l = extend_dat_type_4_num_3_l;
extend_r = 0;
tile_size_x = tile_size_x_3_no_extend;
tile_size_y = tile_size_y_3_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_3;
}
else if(*cnt_num_dat_tile == tile_num_x_c+2)
{
extend_t = extend_dat_type_4_num_4_t;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_4_num_4_r;
tile_size_x = tile_size_x_4_no_extend;
tile_size_y = tile_size_y_4_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_4;
}
else if(*cnt_num_dat_tile < tile_num_x_c+1+tile_num_x_c+2 && *cnt_num_dat_tile >tile_num_x_c+2)
{
extend_t = extend_dat_type_4_num_5_t;
extend_b = 0;
extend_l = extend_dat_type_4_num_5_l;
extend_r = extend_dat_type_4_num_5_r;
tile_size_x = tile_size_x_5_no_extend;
tile_size_y = tile_size_y_5_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_5;
}
else if(*cnt_num_dat_tile == tile_num_x_c+1+tile_num_x_c+2)
{
extend_t = extend_dat_type_4_num_6_t;
extend_b = 0;
extend_l = extend_dat_type_4_num_6_l;
extend_r = 0;
tile_size_x = tile_size_x_6_no_extend;
tile_size_y = tile_size_y_6_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_6;
}
else
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_4_num_1;
}
break;
}
case 5:
{
if(*cnt_num_dat_tile == 0)
{
extend_t = 0;
extend_b = extend_dat_type_5_num_1_b;
extend_l = 0;
extend_r = extend_dat_type_5_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_1;
}
else if(*cnt_num_dat_tile == 1)
{
extend_t = 0;
extend_b = extend_dat_type_5_num_2_b;
extend_l = extend_dat_type_5_num_2_l;
extend_r = 0;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_2;
}
else if( (*cnt_num_dat_tile-2) > 0 && (*cnt_num_dat_tile-2) < 2*tile_num_y_c && *cnt_num_dat_tile%2==0 )
{
extend_t = extend_dat_type_5_num_3_t;
extend_b = extend_dat_type_5_num_3_b;
extend_l = 0;
extend_r = extend_dat_type_5_num_3_r;
tile_size_x = tile_size_x_3_no_extend;
tile_size_y = tile_size_y_3_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_3;
}
else if((*cnt_num_dat_tile-2) > 0 && (*cnt_num_dat_tile-2) < 2*tile_num_y_c && *cnt_num_dat_tile%2==1)
{
extend_t = extend_dat_type_5_num_4_t;
extend_b = extend_dat_type_5_num_4_b;
extend_l = extend_dat_type_5_num_4_l;
extend_r = 0;
tile_size_x = tile_size_x_4_no_extend;
tile_size_y = tile_size_y_4_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_4;
}
else if(*cnt_num_dat_tile == 2*(tile_num_y_c+1) )
{
extend_t = extend_dat_type_5_num_5_t;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_5_num_5_r;
tile_size_x = tile_size_x_5_no_extend;
tile_size_y = tile_size_y_5_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_5;
}
else if(*cnt_num_dat_tile == 2*(tile_num_y_c+1)+1 )
{
extend_t = extend_dat_type_5_num_6_t;
extend_b = 0;
extend_l = extend_dat_type_5_num_6_l;
extend_r = 0;
tile_size_x = tile_size_x_6_no_extend;
tile_size_y = tile_size_y_6_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_6;
}
else
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_5_num_1;
}
break;
}
case 6:
{
if(*cnt_num_dat_tile=0)
{
extend_t = 0;
extend_b = extend_dat_type_6_num_1_b;
extend_l = 0;
extend_r = extend_dat_type_6_num_1_r;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_1;
}
else if(*cnt_num_dat_tile < tile_num_x_c+1 && *cnt_num_dat_tile >0)
{
extend_t = 0;
extend_b = extend_dat_type_6_num_2_b;
extend_l = extend_dat_type_6_num_2_l;
extend_r = extend_dat_type_6_num_2_r;
tile_size_x = tile_size_x_2_no_extend;
tile_size_y = tile_size_y_2_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_2;
}
else if(*cnt_num_dat_tile==tile_num_x_c+1)
{
extend_t = 0;
extend_b = extend_dat_type_6_num_3_b;
extend_l = extend_dat_type_6_num_3_l;
extend_r = 0;
tile_size_x = tile_size_x_3_no_extend;
tile_size_y = tile_size_y_3_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_3;
}
else if(*cnt_num_dat_tile==tile_num_x_c+2)
{
extend_t = extend_dat_type_6_num_4_t;
extend_b = extend_dat_type_6_num_4_b;
extend_l = 0;
extend_r = extend_dat_type_6_num_4_r;
tile_size_x = tile_size_x_4_no_extend;
tile_size_y = tile_size_y_4_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_4;
}
else if(*cnt_num_dat_tile>tile_num_x_c+2 &&
*cnt_num_dat_tile<(tile_num_x_c+2)*(tile_num_y_c+1) &&
*cnt_num_dat_tile%(tile_num_x_c+2)!=0 &&
(*cnt_num_dat_tile-1)%(tile_num_x_c+2)!=0)
{
extend_t = extend_dat_type_6_num_5_t;
extend_b = extend_dat_type_6_num_5_b;
extend_l = extend_dat_type_6_num_5_l;
extend_r = extend_dat_type_6_num_5_r;
tile_size_x = tile_size_x_5_no_extend;
tile_size_y = tile_size_y_5_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_5;
}
else if(*cnt_num_dat_tile == (tile_num_x_c+2)*(tile_num_y_c+1)-1 )
{
extend_t = extend_dat_type_6_num_6_t;
extend_b = extend_dat_type_6_num_6_b;
extend_l = extend_dat_type_6_num_6_l;
extend_r = 0;
tile_size_x = tile_size_x_6_no_extend;
tile_size_y = tile_size_y_6_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_6;
}
else if(*cnt_num_dat_tile == (tile_num_x_c+2)*(tile_num_y_c+1) )
{
extend_t = extend_dat_type_6_num_7_t;
extend_b = 0;
extend_l = 0;
extend_r = extend_dat_type_6_num_7_r;
tile_size_x = tile_size_x_7_no_extend;
tile_size_y = tile_size_y_7_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_7;
}
else if(*cnt_num_dat_tile > (tile_num_x_c+2)*(tile_num_y_c+1) &&
*cnt_num_dat_tile < (tile_num_x_c+2)*(tile_num_y_c+2)-1)
{
extend_t = extend_dat_type_6_num_8_t;
extend_b = 0;
extend_l = extend_dat_type_6_num_8_l;
extend_r = extend_dat_type_6_num_8_r;
tile_size_x = tile_size_x_8_no_extend;
tile_size_y = tile_size_y_8_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_8;
}
else if(*cnt_num_dat_tile = (tile_num_x_c+2)*(tile_num_y_c+2)-1)
{
extend_t = extend_dat_type_6_num_9_t;
extend_b = 0;
extend_l = extend_dat_type_6_num_9_l;
extend_r = 0;
tile_size_x = tile_size_x_9_no_extend;
tile_size_y = tile_size_y_9_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_9;
}
else
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_6_num_1;
}
break;
}
default:
{
extend_t = 0;
extend_b = 0;
extend_l = 0;
extend_r = 0;
tile_size_x = tile_size_x_1_no_extend;
tile_size_y = tile_size_y_1_no_extend;
cnt_address_incr_dat = address_incr_dat_type_0_num_1;
break;
}
}
//transfer data from ddr to cbuf
cnt_ddr_dat_address = *cnt_ddr_dat_start_address -(extend_l+extend_t*all_feature_y)*ddr_size_input_channel ;
len_y = extend_t + extend_b + tile_size_y ;
len_x = extend_l + extend_r + tile_size_x ;
for(i=0;i<len_y;i++)
{
for(j=0;j<len_x ;j++){
m=0;
for(k=0;k<ddr_size_input_channel;k++){
for(l=0;l<8;l++){
tmp[m][l]=ddr[cnt_ddr_dat_address][l];
}
cnt_ddr_dat_address++;
if(m==127){
for(p=0;p<128;p++){
for(q=0;q<8;q++){
cbuf[cnt_cbuf_dat_address][q+p*8]=tmp[p][q];
}
}
m=0;
cnt_cbuf_dat_address++;
}
else{
m++;
}
}
for(k=0;k<num_adding_zero_input_channel_cdma;k++){
for(l=0;l<8;l++){
tmp[m][l]=0;
}
if(m==127){
for(p=0;p<128;p++){
for(q=0;q<8;q++){
cbuf[cnt_cbuf_dat_address][q+p*8]=tmp[p][q];
}
}
cnt_cbuf_dat_address++;
m=0;
}
else{
m++;
}
}
}
cnt_ddr_dat_address = cnt_ddr_dat_address+ddr_size_input_channel *(all_feature_x-len_x);
}
(*cnt_num_dat_tile)++;
*cnt_ddr_dat_start_address = cnt_address_incr_dat + *cnt_ddr_dat_start_address;
while(1){
if(*cnt_num_wt_tile == num_wt_tile){
*cnt_num_wt_tile = 0;
break;
}
if(*cnt_num_wt_tile == 0){
*cnt_ddr_wt_address = ddr_wt_address ;
}
/*-------------------------------*/
/* wt pingpong 2 stage */
/*-------------------------------*/
//switch wt address
if(*cnt_num_wt_tile % 2==0){
cnt_cbuf_wt_address = cbuf_wt0_address;
}
else{
cnt_cbuf_wt_address = cbuf_wt1_address;
}
//switch wt size
if(*cnt_num_wt_tile == num_wt_tile - 1){
cnt_ddr_wt_size = ddr_wt_size_last;
}
else{
cnt_ddr_wt_size = ddr_wt_size_norm;
}
//transfer weight from ddr to cbuf
k=0;
for(i=0;i<cnt_ddr_wt_size;i++){
for(j=0;j<8;j++){
tmp[k][j]=ddr[*cnt_ddr_wt_address][j];
}
if(k==127){
k=0;
for(p=0;p<128;p++){
for(q=0;q<8;q++){
cbuf[cnt_cbuf_wt_address][q+p*8]=tmp[p][q];
}
}
cnt_cbuf_wt_address++;
}
else{
k++;
}
(*cnt_ddr_wt_address)++;
}
(*cnt_num_wt_tile)++;
}
}
}
}
|
#include <bits/stdc++.h>
using namespace std;
template <typename T , typename V>
class Pair{
T x;
V y;
public :
T getx(){
return x;}
V gety (){
return y;
}
void setx(T x){
this->x=x;
}
void sety(V y){
this->y=y;
}
};
int main(){
Pair <Pair<int , int>,int> p1;
p1.sety(30);
Pair <int,int> p2;
p2.setx(10);
p2.sety(20);
p1.setx(p2);
cout<<p1.getx().getx();
cout<<p1.getx().gety();
cout<<p1.gety();
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int m,n,a;
while(cin >>m >> n >> a)
{
if(m+n+a != 180)
cout << "Error\n";
else if(m == n && n == a && a == m && m == 60)
cout << "Equilateral\n";
else if(m ==n || a == n || a == m)
cout << "Isosceles\n";
else
cout << "Scalene\n";
}
}
|
/**
*
* @file Byte.cpp
* @Naoki Takahashi
*
**/
#include "Byte.hpp"
#include <cstdint>
#include <cassert>
#include <cstddef>
namespace Tools {
namespace Byte {
constexpr size_t maximum_support_byte_lenght = 2;
template <typename T>
T low_byte(const T &x) {
static_assert(sizeof(x) == maximum_support_byte_lenght, "Size over from Tools::Byte");
return static_cast<T>(x & 0x00ff);
}
template <typename T>
T high_byte(const T &x) {
static_assert(sizeof(x) == maximum_support_byte_lenght, "Size over from Tools::Byte");
return static_cast<T>((x & 0xff00) >> 8);
}
template <typename T>
T union_byte(const T &high, const T &low) {
static_assert(sizeof(high) == maximum_support_byte_lenght || sizeof(low) == maximum_support_byte_lenght, "Size over from Tools::Byte");
return (high << 8) + low;
}
template short low_byte<short>(const short &);
template unsigned short low_byte<unsigned short>(const unsigned short &);
template short high_byte<short>(const short &);
template unsigned short high_byte<unsigned short>(const unsigned short &);
template short union_byte<short>(const short &, const short &);
template unsigned short union_byte<unsigned short>(const unsigned short &, const unsigned short &);
}
}
|
// Factorial
#include <iostream>
using namespace std;
int fact(int n){
if(n==0){
return 1;
}
int ChotaAns=fact(n-1);
int BadaAns=n*ChotaAns;
return BadaAns;
}
int main(){
int n;
cin>>n;
cout<<fact(n)<<endl;
return 0;
}
|
#ifndef TESTUTILS_H
#define TESTUTILS_H
namespace cpp_class2_test {
void testAreEqualFloat();
void testAreEqualDouble();
}
#endif // !TESTUTILS_H
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
***************************************************************************/
#pragma once
#include "ScriptOMInterfaces.h"
//
// CSCIPropertyCtrl
//
// Implements a listview control that can display and edit properties
// from an ISCIPropertyBag
//
class SCIClassBrowser;
namespace sci
{
class PropertyValue;
class ClassDefinition;
class ClassProperty;
class Script;
}
//
// This is a property bag that supports listeners. In addition, it is initialized with
// another property bag, from which it takes its initial values (e.g. it copies the property
// bag) and tracks changes.
//
enum PROPERTYCHANGE_INFO
{
PC_ADDED,
PC_REMOVED,
PC_CHANGED,
};
typedef std::unordered_map<std::string, sci::PropertyValue> property_map;
//
// This represents a bag of properties based on a ClassDefinition
// The assumption is that this object is kept alive as long as the class.
//
class CSCIPropertyBagNotify : public ISCIPropertyBag
{
public:
ISCIPropertyBag *_pBagInner;
CSCIPropertyBagNotify(SCIClassBrowser *pBrowser, sci::ClassDefinition *pClass);
void AddListener(ISCIPropertyChange *pListener) { _listeners.Add(pListener); }
void RemoveListener(ISCIPropertyChange *pListener)
{
for (INT_PTR i = 0; i < _listeners.GetSize(); i++)
{
if (_listeners[i] == pListener)
{
_listeners.RemoveAt(i);
break;
}
}
}
// ISCIPropertyBag
bool SetProperty(PCTSTR pszName, sci::PropertyValue value);
bool GetProperty(PCTSTR pszName, sci::PropertyValue &value);
void SetBagName(PCTSTR pszName)
{
if (_strName != pszName)
{
_strName = pszName;
_fNameChanged = TRUE;
for (INT_PTR i = 0; i < _listeners.GetSize(); i++)
{
_listeners[i]->OnNameChange(this, pszName);
}
}
}
const std::string GetBagName() { return _strName; }
void SetSpecies(PCTSTR pszName)
{
if (_strSpecies != pszName)
{
_strSpecies = pszName;
_fSpeciesChanged = TRUE;
for (INT_PTR i = 0; i < _listeners.GetSize(); i++)
{
_listeners[i]->OnSpeciesChange(this, pszName);
}
}
}
const std::string GetSpecies() const { return _strSpecies; }
const std::vector<std::unique_ptr<sci::ClassProperty>> &GetProperties()
{
return _propertiesEnum; // TODO, empty
}
const sci::ClassDefinition *GetClass() const { return _pClass; }
protected:
sci::ClassDefinition *_pClass;
SCIClassBrowser *_pBrowser;
private:
CArray<ISCIPropertyChange *, ISCIPropertyChange *> _listeners;
// Map of properties
property_map _properties;
// And information about when they've changed
CMap<CString, PCTSTR, PROPERTYCHANGE_INFO, PROPERTYCHANGE_INFO> _changeInfo;
std::string _strName;
BOOL _fNameChanged;
std::string _strSpecies;
BOOL _fSpeciesChanged;
std::vector<std::unique_ptr<sci::ClassProperty>> _propertiesEnum; // TODO
};
class CSCIPropertyCtrl : public CListCtrl, public ISCIPropertyChange
{
DECLARE_DYNAMIC(CSCIPropertyCtrl)
public:
CSCIPropertyCtrl();
virtual ~CSCIPropertyCtrl();
void SetControl(CSCIPropertyBagNotify *pBag);
void Initialize(const sci::Script *pScript, SCIClassBrowser *pBrowser, CWnd *pDescription);
// ISCIPropertyChange
void OnPropertyChange(ISCIPropertyBag *pSource, PCTSTR pszName, sci::PropertyValue value);
void OnNameChange(ISCIPropertyBag *pSource, PCTSTR pszName);
void OnSpeciesChange(ISCIPropertyBag *pSource, PCTSTR pszSpecies) { /*TODO*/ }
void OnAddProperty(ISCIPropertyBag *pSource, PCTSTR pszName) { /*TODO*/ }
void OnRemoveProperty(ISCIPropertyBag *pSource, PCTSTR pszName) { /*TODO*/ }
protected:
DECLARE_MESSAGE_MAP()
void OnItemClick(NMHDR *pNMHDR, LRESULT *pResult);
void OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult);
void OnLButtonDown(UINT nFlags, CPoint point);
void _AddProperty(PCTSTR pszProp);
CSCIPropertyBagNotify *_pBag;
BOOL _fInLabelEdit;
BOOL _fMadeAutoComplete;
const sci::Script *_pScript;
SCIClassBrowser *_pBrowser;
CWnd *_pDescription;
CComboBox m_wndComboInPlace;
};
|
// Copyright [2014] <lgb (LiuGuangBao)>
//=====================================================================================
//
// Filename: log.cpp
//
// Description: easyDB 日志模块实现
//
// Version: 1.0
// Created: 04/26/2013 01:17:44 PM
// Revision: none
// Compiler: gcc
//
// Author: lgb (LiuGuangBao), easyeagel@gmx.com
// Organization: ezbty.org
//
//=====================================================================================
#include"time.hpp"
#include"log.hpp"
#include"server.hpp"
#include"string.hpp"
#include<cassert>
#include<string>
#include<ostream>
#include<iterator>
#include<boost/filesystem.hpp>
#include<boost/log/expressions.hpp>
#include<boost/log/attributes/clock.hpp>
#include<boost/log/support/date_time.hpp>
#include<boost/log/sinks/async_frontend.hpp>
#include<boost/log/expressions/formatters.hpp>
#include<boost/log/sinks/text_file_backend.hpp>
#include<boost/log/attributes/current_thread_id.hpp>
#include<boost/log/utility/setup/common_attributes.hpp>
#include<boost/iostreams/copy.hpp>
#include<boost/iostreams/device/file.hpp>
#include<boost/iostreams/filter/bzip2.hpp>
#include<boost/iostreams/filtering_stream.hpp>
#include<boost/iostreams/device/file_descriptor.hpp>
namespace core
{
bool GlobalLogInit::logOn_=true;
std::string GlobalLogInit::dir_="logs";
std::string GlobalLogInit::prefix_="svc.";
namespace io=boost::iostreams;
namespace bf=boost::filesystem;
namespace logging=boost::log;
namespace attrs=boost::log::attributes;
namespace src=boost::log::sources;
namespace sinks=boost::log::sinks;
namespace expr=boost::log::expressions;
namespace keywords=boost::log::keywords;
class BoostLog
{
struct BZipSinkCollector: public sinks::file::collector
{
void store_file(bf::path const & path)
{
if(!ComputeServer::isStopped())
return ComputeServer::post(std::bind(&BZipSinkCollector::bzipFile, this, path));
bzipFile(path);
}
uintmax_t scan_for_files(sinks::file::scan_method , bf::path const& = bf::path(), unsigned int* = nullptr)
{
return 0;
}
private:
void bzipFile(bf::path const& path)
{
std::ifstream in(path.c_str(), std::ifstream::in | std::ifstream::binary);
if(!in)
return;
auto outPath=path;
outPath += ".bz2";
io::filtering_ostream out;
out.push(io::bzip2_compressor());
out.push(io::file_sink(outPath.string().c_str()));
io::copy(in, out);
bf::remove(path);
}
};
typedef sinks::asynchronous_sink<sinks::text_file_backend> FileSink;
public:
static void logginInit(const std::string& prefix)
{
logging::add_common_attributes();
const std::streamsize oneSize=512*1024*1024;
const std::string path=prefix + "%Y%m%d%H%M%S.log";
sinkPtr_.reset(new FileSink( keywords::file_name = path
, keywords::rotation_size = oneSize));
sinkPtr_->set_formatter(
expr::format("%1%:%2%:%3%:%4% %5%")
% expr::attr<unsigned int>("LineID")
% expr::attr<attrs::current_thread_id::value_type>("ThreadID")
% expr::format_date_time<boost::posix_time::ptime>("TimeStamp", "%Y%m%d%H%M%S")
% logging::trivial::severity
% expr::smessage
);
auto& backend=*sinkPtr_->locked_backend();
backend.set_file_collector(
boost::make_shared<BZipSinkCollector>()
);
backend.scan_for_files();
auto core=logging::core::get();
core->add_sink(sinkPtr_);
severitySet(SeverityLevel::info);
//定时刷日志
static IOTimer timer(MainServer::serviceGet(), 100);
timer.timerStart(
[](const ErrorCode& )
{
ComputeServer::post(
[]()
{
sinkPtr_->flush();
}
);
}
);
}
static void loggOff()
{
logging::core::get()->set_logging_enabled(false);
}
static void severitySet(SeverityLevel level)
{
sinkPtr_->set_filter(
logging::trivial::severity >= level
);
}
static void autoFlushSet(bool val)
{
auto& backend=*sinkPtr_->locked_backend();
backend.auto_flush(val);
}
private:
static boost::shared_ptr<FileSink> sinkPtr_;
};
boost::shared_ptr<BoostLog::FileSink> BoostLog::sinkPtr_;
GlobalLogInit::GlobalLogInit()
{
struct Init
{
Init()
{
if(GlobalLogInit::logOffGet())
{
BoostLog::loggOff();
return;
}
const auto path=dir_ + '/' + prefix_;
BoostLog::logginInit(path);
}
};
static OnceConstructT<Init> gs;
}
void GlobalLogInit::init(const std::string& dir, const std::string& prefix)
{
dir_=dir;
prefix_=prefix;
if(bf::exists(dir))
return;
auto ok=bf::create_directories(dir);
if(!ok)
{
std::cerr << "Create logDir Failed: " << dir << std::endl;
std::exit(EXIT_FAILURE);
}
}
SeverityLevel severityFromString(const char* lvl)
{
#ifndef _MSC_VER
switch(constHash(lvl))
{
case constHash("trace"):
return SeverityLevel::trace;
case constHash("debug"):
return SeverityLevel::debug;
case constHash("info"):
return SeverityLevel::info;
case constHash("warning"):
return SeverityLevel::warning;
case constHash("error"):
return SeverityLevel::error;
case constHash("fatal"):
return SeverityLevel::fatal;
default:
return SeverityLevel::info;
}
#endif
return SeverityLevel::info;
}
void GlobalLogInit::severitySet(SeverityLevel level)
{
BoostLog::severitySet(level);
}
void GlobalLogInit::autoFlushSet(bool val)
{
BoostLog::autoFlushSet(val);
}
}
|
//
// Created by Will Smith on 3/8/18.
//
#include "Person.h"
const string &Person::getName() const {
return name;
}
void Person::setName(const string &name) {
Person::name = name;
}
int Person::getAge() const {
return age;
}
void Person::setAge(int age) {
Person::age = age;
}
Person::Person() {
name = "none";
age = 17;
}
Person::Person(const string &name, int age) : name(name), age(age) {}
|
#if !defined(AFX_PLTREEVIEW_H__69612D9C_A039_4AE2_8F26_4705535DD903__INCLUDED_)
#define AFX_PLTREEVIEW_H__69612D9C_A039_4AE2_8F26_4705535DD903__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// PLTreeView.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CPLTreeView view
class CPLTreeView : public CView
{
protected:
CPLTreeView(); // protected constructor used by dynamic creation
DECLARE_DYNCREATE(CPLTreeView)
// Attributes
public:
// Operations
public:
bool isInit;
CImageList m_ImgList;
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPLTreeView)
public:
virtual void OnInitialUpdate();
protected:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
//}}AFX_VIRTUAL
// Implementation
protected:
virtual ~CPLTreeView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
// Generated message map functions
protected:
//{{AFX_MSG(CPLTreeView)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
afx_msg void OnDblclkTree1(NMHDR* pNMHDR, LRESULT* pResult);
DECLARE_MESSAGE_MAP()
private:
CTreeCtrl m_tree;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_PLTREEVIEW_H__69612D9C_A039_4AE2_8F26_4705535DD903__INCLUDED_)
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string a;
cin>>a;
int mx = 0;
if(a.length()%2!=0)
{
cout<<"NO"<<endl;
continue;
}
for(int i=0; i<a.length(); i++)
{
int c = 1;
if(a[i]=='0') continue;
for(int j=i+1; j<a.length(); j++)
{
if(a[j]=='0') continue;
if(a[j]==a[i])
{
a[j] = '0';
c++;
}
}
a[i] = '0';
mx = max(mx, c);
}
if(mx==a.length()/2) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
|
#ifndef _DIALOGMERGEMESHSET_H_
#define _DIALOGMERGEMESHSET_H_
#include "SelfDefObject/QFDialog.h"
namespace Ui
{
class MeshSetMergeDialog;
}
namespace MeshData
{
class MeshData;
};
namespace MainWidget
{
class MeshWidget;
class MeshSetMergeDialog : public QFDialog
{
Q_OBJECT
public:
MeshSetMergeDialog(GUI::MainWindow* mw, MeshWidget* w);
~MeshSetMergeDialog();
private slots:
void on_typeChanged();
void on_addButton_clicked();
void on_removeButton_clicked();
void on_btn_add_clicked();
void on_btn_del_clicked();
private:
void init();
QString getNameFromUi();
QList<int> getMergeIDs();
QList<int> getCutIDs();
void accept() override;
private:
Ui::MeshSetMergeDialog* _ui{};
MeshData::MeshData* _meshData{};
MeshWidget* _meshwidget{};
};
}
#endif
|
/*
search routine generated by gen.
skip=no, match=rev, shift=d12
*/
/*
* The authors of this software are Andrew Hume and Daniel Sunday.
*
* Copyright (c) 1991 by AT&T and Daniel Sunday.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*/
#include <boost/array.hpp>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <algorithm>
#define MAXPAT 256
#ifndef TABTYPE
#define TABTYPE long
#endif
typedef TABTYPE Tab;
typedef boost::array<unsigned char, MAXPAT> array_type;
struct pattern
{
int patlen;
array_type pat;
Tab delta1[256];
Tab delta2[257];
Tab delta[256];
Tab dg[MAXPAT][128];
int rarec, rareoff;
int md2;
long cmps, accs;
pattern() : patlen(0) {}
};
static pattern pat;
typedef typename array_type::const_iterator pat_iterator;
template <typename RandomAccessIterator>
void bmprep(RandomAccessIterator base, int m)
{
Tab *d2;
int q1, t, qp, jp, kp, j;
Tab f[256], f1[256];
pat.patlen = m;
if(m > MAXPAT)
abort();
std::copy(base, base + m, pat.pat.begin());
d2 = pat.delta1;
std::fill(d2, d2 + 256, m);
for(j = 0; j < m; j++)
d2[base[j]] = m-1-j;
d2 = pat.delta2;
for(j = 1; j < m; j++)
d2[j] = 2*m-j;
for(j = m, t = m+1; j > 0; j--, t--){
f[j] = t;
while((t <= m) && (base[t-1] != base[j-1])){
if((m-j) < d2[t])
d2[t] = m-j;
t = f[t];
}
}
q1 = t;
t = m+1-q1;
qp = 1;
for(jp = 1, kp = 0; kp < t; jp++, kp++){
f1[jp] = kp;
while((kp >= 1) && (base[jp-1] != base[kp-1]))
kp = f1[kp];
}
while(q1 < m){
for(j = qp; j <= q1; j++)
if(m+q1-j < d2[j])
d2[j] = m+q1-j;
qp = q1+1;
q1 += t-f1[t];
t = f1[t];
}
d2[0] = m+1; /* the case where the match succeeded */
}
template <typename RandomAccessIterator>
RandomAccessIterator bmexec_cnt(RandomAccessIterator base, int n)
{
RandomAccessIterator e, s;
int s_offset;
RandomAccessIterator p, q;
int n1 = pat.patlen-1;
RandomAccessIterator ep;
Tab *d1 = pat.delta1;
Tab *d2 = pat.delta2+1;
int k1, k2;
s = base+pat.patlen-1;
e = base+n;
s_offset = 1-pat.patlen;
ep = pat.pat; pat.cmps = pat.accs = 0;
while(s < e){
for(p = pat.pat.begin()+n1, q = s+n1+s_offset; p >= ep; ){
if(++pat.cmps,(*q-- != *p--)){
q++, p++;
goto mismatch;
}
}
if(p < ep) return q+1; else return q;
mismatch:
k2 = d2[p-pat.pat];
k1 = d1[*q]; ++pat.accs;
if(k2 < k1)
k2 = k1;
k2 = q+k2-s+n1+s_offset;
s += k2;
}
return e;
}
template <typename RandomAccessIterator>
RandomAccessIterator bmexec(RandomAccessIterator base, int n)
{
RandomAccessIterator e, s;
int s_offset;
RandomAccessIterator p, q;
int n1 = pat.patlen-1;
RandomAccessIterator ep;
Tab *d1 = pat.delta1;
Tab *d2 = pat.delta2+1;
int k1, k2;
s = base+pat.patlen-1;
e = base+n;
s_offset = 1-pat.patlen;
ep = pat.pat;
while(s < e){
for(p = pat.pat.begin()+n1, q = s+n1+s_offset; p >= ep; ){
if(*q-- != *p--){
q++, p++;
goto mismatch;
}
}
if(p < ep) return q+1; else return q;
mismatch:
k2 = d2[p-pat.pat];
k1 = d1[*q];
if(k2 < k1)
k2 = k1;
k2 = q+k2-s+n1+s_offset;
s += k2;
}
return(e);
}
template <typename RandomAccessIterator1, typename RandomAccessIterator2>
RandomAccessIterator1 slowbm(RandomAccessIterator1 text, RandomAccessIterator1 textEnd, RandomAccessIterator2 pat, RandomAccessIterator2 patEnd)
{
bmprep(pat, patEnd - pat);
return bmexec(text, textEnd - text);
}
/*
template <class RandomAccessIterator1, class RandomAccessIterator2>
RandomAccessIterator1 slowbm(
RandomAccessIterator1 txt, RandomAccessIterator1 txtEnd,
RandomAccessIterator2 pt, RandomAccessIterator2 ptEnd)
{
#ifdef __GNUC__
CHARTYPE* pat = (CHARTYPE*)pt;
CHARTYPE* text = (CHARTYPE*)txt;
#else
CHARTYPE* pat = (CHARTYPE*)pt.base();
CHARTYPE* text = (CHARTYPE*)txt.base();
#endif
bmprep(pat, ptEnd - pt);
CHARTYPE* result = bmexec_cnt(text, txtEnd - txt);
data::accesses = ::pat.accs;
data::equal_comparisons = ::pat.cmps;
#ifdef __GNUC__
return (RandomAccessIterator1)result;
#else
return (RandomAccessIterator1)(data*)result;
#endif
}
*/
#include "freq.h"
template <typename RandomAccessIterator>
void humprep(RandomAccessIterator base, int m)
{
pat_iterator skipc;
pat_iterator pe, p;
int j;
Tab *d;
int rrr, rr;
pat_iterator pmd2;
pat.patlen = m;
if(m > MAXPAT)
abort();
std::copy(base, base + m, pat.pat.begin());
d = pat.delta;
for(j = 0; j < 256; j++)
d[j] = pat.patlen;
for(p = pat.pat.begin(), pe = p+m-1; p < pe; p++)
d[*p] = pe-p;
d[*p] = 0;
skipc = p;
rrr = 0;
for(rr = 1; rr < m; rr++){
if(freq[pat.pat[rr]] < freq[pat.pat[rrr]])
rrr = rr;
}
pat.rarec = pat.pat[rrr];
pat.rareoff = rrr - (m-1);
for(pmd2 = skipc-1; pmd2 >= pat.pat.begin(); pmd2--)
if (*pmd2 == *skipc) break;
pat.md2 = skipc - pmd2; /* *pmd2 is first leftward reoccurance of *pe */
}
template <typename RandomAccessIterator>
RandomAccessIterator humexec(RandomAccessIterator base, int n)
{
RandomAccessIterator e, s, q;
Tab *d0 = pat.delta;
pat_iterator p;
pat_iterator ep;
int ro, rc;
int n1 = pat.patlen-1;
int md2 = pat.md2;
s = base+pat.patlen-1;
e = base+n;
ro = pat.rareoff;
rc = pat.rarec;
ep = pat.pat.begin() + pat.patlen-1;
while(s < e){
int k = 0;
while( (k = d0[static_cast<char unsigned>(*(s += k))]) != 0 && (s < e));
if(s >= e)
break;
if(s[ro] != rc)
goto mismatch;
for(p = pat.pat.begin(), q = s-n1; p < ep; ){
if(*q++ != *p++)
goto mismatch;
}
return s - n1;
mismatch:
s += md2;
}
return e;
}
template <typename RandomAccessIterator>
RandomAccessIterator humexec_cnt(RandomAccessIterator base, int n)
{
RandomAccessIterator e, s;
Tab *d0 = pat.delta;
int ro, rc;
pat_iterator p, q;
pat_iterator ep;
int n1 = pat.patlen-1;
int md2 = pat.md2;
s = base+pat.patlen-1;
e = base+n;
ro = pat.rareoff;
rc = pat.rarec;
ep = pat.pat.begin() + pat.patlen-1; pat.cmps = pat.accs = 0;
while(s < e){
int k = 0;
while( (++pat.accs,(k = d0[*(s += k)])) != 0 && (s < e));
if(s >= e)
break;
if(++pat.cmps,(s[ro] != rc))
goto mismatch;
for(p = pat.pat.begin(), q = s-n1; p < ep; ){
if(++pat.cmps,(*q++ != *p++))
goto mismatch;
}
return s - n1;
mismatch:
s += md2;
}
return e;
}
template <typename RandomAccessIterator1, typename RandomAccessIterator2>
RandomAccessIterator1 hume(RandomAccessIterator1 text, RandomAccessIterator1 textEnd, RandomAccessIterator2 pat, RandomAccessIterator2 patEnd)
{
humprep(pat, patEnd - pat);
return humexec(text, textEnd - text);
}
/*
template <class RandomAccessIterator1, class RandomAccessIterator2>
RandomAccessIterator1 hume(
RandomAccessIterator1 txt, RandomAccessIterator1 txtEnd,
RandomAccessIterator2 pt, RandomAccessIterator2 ptEnd)
{
#ifdef __GNUC__
CHARTYPE* pat = (CHARTYPE*)pt;
CHARTYPE* text = (CHARTYPE*)txt;
#else
CHARTYPE* pat = (CHARTYPE*)pt.base();
CHARTYPE* text = (CHARTYPE*)txt.base();
#endif
humprep(pat, ptEnd - pt);
CHARTYPE* result = humexec_cnt(text, txtEnd - txt);
data::accesses = ::pat.accs;
data::equal_comparisons = ::pat.cmps;
#ifdef __GNUC__
return (RandomAccessIterator1)result;
#else
return (RandomAccessIterator1)(data*)result;
#endif
}
*/
template <typename RandomAccessIterator>
void fbmprep(RandomAccessIterator base, int m)
{
pat_iterator pe, p;
int j;
Tab *d;
Tab *d2;
int q1, t, qp, jp, kp;
Tab f[256], f1[256];
pat.patlen = m;
if(m > MAXPAT)
abort();
std::copy(base, base + m, pat.pat.begin());
d = pat.delta;
for(j = 0; j < 256; j++)
d[j] = pat.patlen;
for(p = pat.pat.begin(), pe = p+m-1; p < pe; p++)
d[*p] = pe-p;
d[*p] = 0;
d2 = pat.delta1;
for(j = 0; j < 256; j++)
d2[j] = m;
for(j = 0; j < m; j++)
d2[static_cast<char unsigned>(base[j])] = m-1-j;
d2 = pat.delta2;
for(j = 1; j < m; j++)
d2[j] = 2*m-j;
for(j = m, t = m+1; j > 0; j--, t--){
f[j] = t;
while((t <= m) && (base[t-1] != base[j-1])){
if((m-j) < d2[t])
d2[t] = m-j;
t = f[t];
}
}
q1 = t;
t = m+1-q1;
qp = 1;
for(jp = 1, kp = 0; kp < t; jp++, kp++){
f1[jp] = kp;
while((kp >= 1) && (base[jp-1] != base[kp-1]))
kp = f1[kp];
}
while(q1 < m){
for(j = qp; j <= q1; j++)
if(m+q1-j < d2[j])
d2[j] = m+q1-j;
qp = q1+1;
q1 += t-f1[t];
t = f1[t];
}
d2[0] = m+1; /* the case where the match succeeded */
}
template <typename RandomAccessIterator>
RandomAccessIterator fbmexec(RandomAccessIterator base, int n)
{
RandomAccessIterator e, s, q;
Tab *d0 = pat.delta;
pat_iterator p;
pat_iterator prev(pat.pat.begin() + pat.patlen - 1);
Tab *d2 = pat.delta2+1;
int k1;
s = base+pat.patlen-1;
e = base+n;
while(s < e){
int k = 0;
while( (k = d0[static_cast<char unsigned>(*(s += k))]) != 0 && (s < e));
if(s >= e)
break;
for(p = prev, q = s; p > pat.pat.begin(); ){
if(*--q != *--p)
goto mismatch;
}
return q;
mismatch:
k = d2[p - pat.pat.begin()];
k1 = d0[static_cast<char unsigned>(*q)];
if(k < k1)
k = k1;
s = RandomAccessIterator(q+k);
}
return e;
}
template <typename RandomAccessIterator>
RandomAccessIterator fbmexec_cnt(RandomAccessIterator base, int n)
{
RandomAccessIterator e, s;
Tab *d0 = pat.delta;
pat_iterator p, q;
pat_iterator prev = pat.pat.begin()+pat.patlen-1;
Tab *d2 = pat.delta2+1;
int k1;
s = base+pat.patlen-1;
e = base+n; pat.cmps = pat.accs = 0;
while(s < e){
int k = 0;
while( (++pat.accs,(k = d0[*(s += k)])) != 0 && (s < e));
if(s >= e)
break;
for(p = prev, q = s; p > pat.pat.begin(); ){
if(++pat.cmps,(*--q != *--p))
goto mismatch;
}
return q;
mismatch:
k = d2[p-pat.pat.begin()];
k1 = d0[*q];++pat.accs;
if(k < k1)
k = k1;
s = q+k;
}
return e;
}
template <typename RandomAccessIterator1, typename RandomAccessIterator2>
RandomAccessIterator1 fbm(RandomAccessIterator1 text, RandomAccessIterator1 textEnd, RandomAccessIterator2 pat, RandomAccessIterator2 patEnd)
{
fbmprep(pat, patEnd - pat);
return fbmexec(text, textEnd - text);
}
/*
template <class RandomAccessIterator1, class RandomAccessIterator2>
RandomAccessIterator1 fbm(
RandomAccessIterator1 txt, RandomAccessIterator1 txtEnd,
RandomAccessIterator2 pt, RandomAccessIterator2 ptEnd)
{
#ifdef __GNUC__
CHARTYPE* pat = (CHARTYPE*)pt;
CHARTYPE* text = (CHARTYPE*)txt;
#else
const CHARTYPE* pat = (const CHARTYPE*)pt.base();
const CHARTYPE* text = (const CHARTYPE*)txt.base();
#endif
fbmprep(pat, ptEnd - pt);
CHARTYPE* result = fbmexec_cnt(text, txtEnd - txt);
data::accesses = ::pat.accs;
data::equal_comparisons = ::pat.cmps;
#ifdef __GNUC__
return (RandomAccessIterator1)result;
#else
return (RandomAccessIterator1)(data*)result;
#endif
}
*/
template <typename RandomAccessIterator>
void gdprep(RandomAccessIterator base, int m)
{
pat_iterator pe, p;
int j;
Tab *d;
int j0, k, q, i, jj;
int endof[MAXPAT], rmin[MAXPAT];
pat.patlen = m;
if(m > MAXPAT)
abort();
std::copy(base, base + m, pat.pat.begin());
d = pat.delta;
for(j = 0; j < 256; j++)
d[j] = pat.patlen;
for(p = pat.pat.begin(), pe = p+m-1; p < pe; p++)
d[*p] = pe-p;
d[*p] = 0;
/*
endof[k] is the maximal integer such that k is not a period
rmin[jj] is the minimal period of p[0,m-1] > jj
rmin[0] is the period of pat
*/
for(i=0; i<m; i++)
rmin[i] = m;
for(k = 1, i = k, jj = 0; k < m; ){
while((pat.pat[i] == pat.pat[i-k]) && (i < m))
i++;
endof[k] = i;
q = k+1;
if(i == m){
for(j0 = jj; j0 < k; j0++)
rmin[j0] = k;
jj = k;
}
while(endof[q-k]+k < i){
endof[q] = endof[q-k]+k;
q = q+1;
}
k = q;
if(k == i+1)
i = k;
}
/* compute pat.dg[jj,a] */
for(jj = 0; jj < m; jj++){
for(i = 0; i < 128; i++)
pat.dg[jj][i] = m-1-jj+rmin[jj];
}
for(k = m-2; k >= 0; k--){
for(i = k, jj = m-1; i >= 0 && pat.pat[i] == pat.pat[jj]; i--, jj--)
;
if((i >= 0) && (pat.dg[jj][pat.pat[i]]>=m))
pat.dg[jj][pat.pat[i]] = m-1-i;
}
}
template <typename RandomAccessIterator>
RandomAccessIterator gdexec(RandomAccessIterator base, int n)
{
RandomAccessIterator e, s, q;
Tab *d0 = pat.delta;
pat_iterator p;
pat_iterator prev = pat.pat.begin()+pat.patlen-1;
int kg;
s = base+pat.patlen-1;
e = base+n;
while(s < e){
int k = 0;
while( (k = d0[static_cast<char unsigned>(*(s += k))]) != 0 && (s < e));
if(s >= e)
break;
for(p = prev, q = s; p > pat.pat.begin(); ){
if(*--q != *--p)
goto mismatch;
}
return q;
mismatch:
if(p < pat.pat.begin())
kg = pat.patlen+1;
else
kg = pat.dg[p-pat.pat.begin()][static_cast<char unsigned>(*q)];
s = q+kg;
}
return e;
}
template <typename RandomAccessIterator>
RandomAccessIterator gdexec_cnt(RandomAccessIterator base, int n)
{
RandomAccessIterator e, s;
Tab *d0 = pat.delta;
RandomAccessIterator p, q;
RandomAccessIterator prev = pat.pat.begin()+pat.patlen-1;
int kg;
s = base+pat.patlen-1;
e = base+n; pat.accs = pat.cmps = 0;
while(s < e){
int k = 0;
while( (++pat.accs,(k = d0[*(s += k)])) != 0 && (s < e));
if(s >= e)
break;
for(p = prev, q = s; p > pat.pat.begin(); ){
if(++pat.cmps,(*--q != *--p))
goto mismatch;
}
return q;
mismatch:
if(p < pat.pat.begin())
kg = pat.patlen+1;
else
{kg = pat.dg[p-pat.pat.begin()][*q]; ++pat.accs;}
s = q+kg;
}
return e;
}
template <typename RandomAccessIterator1, typename RandomAccessIterator2>
RandomAccessIterator1 gdbm(RandomAccessIterator1 text, RandomAccessIterator1 textEnd, RandomAccessIterator2 pat, RandomAccessIterator2 patEnd)
{
gdprep(pat, patEnd - pat);
return gdexec(text, textEnd - text);
}
/*
template <class RandomAccessIterator1, class RandomAccessIterator2>
RandomAccessIterator1 gdbm(
RandomAccessIterator1 txt, RandomAccessIterator1 txtEnd,
RandomAccessIterator2 pt, RandomAccessIterator2 ptEnd)
{
#ifdef __GNUC__
CHARTYPE* pat = (CHARTYPE*)pt;
CHARTYPE* text = (CHARTYPE*)txt;
#else
CHARTYPE* pat = (CHARTYPE*)pt.base();
CHARTYPE* text = (CHARTYPE*)txt.base();
#endif
gdprep(pat, ptEnd - pt);
CHARTYPE* result = gdexec_cnt(text, txtEnd - txt);
data::accesses = ::pat.accs;
data::equal_comparisons = ::pat.cmps;
#ifdef __GNUC__
return (RandomAccessIterator1)result;
#else
return (RandomAccessIterator1)(data*)result;
#endif
}
*/
|
#pragma once
#include <ge.hpp>
namespace doodle {
class Platform : public ge::Object {
public:
Platform(SDL_Texture *gamesheet, SDL_Rect &platformBounds, int x, int y, int scale);
~Platform();
void update();
void render();
bool moving;
ge::Sprite *operator->() {
return platform;
}
private:
ge::Sprite *platform;
};
}
|
#include <iostream>
#include "circ_arr_queue.h"
void PrintFront(CircArrQueue* queue) {
try {
int front = queue->Front();
std::cout<< "Front: " << front << std::endl;
} catch (QueueEmpty) {
std::cout << "Error: Queue is empty" << std::endl;
}
}
void PrintSize(CircArrQueue* queue) {
std::cout<< "Size: " << queue->Size() << std::endl;
}
int main() {
CircArrQueue* queue = new CircArrQueue();
for (int i = 1 ; i <= 3; i++) {
queue->Enqueue(i);
PrintFront(queue);
PrintSize(queue);
}
while(!queue->IsEmpty()) {
queue->Dequeue();
PrintFront(queue);
PrintSize(queue);
}
delete queue;
}
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "generators/include/python_CEGUI.h"
#include "TextureTarget.pypp.hpp"
namespace bp = boost::python;
struct TextureTarget_wrapper : CEGUI::TextureTarget, bp::wrapper< CEGUI::TextureTarget > {
TextureTarget_wrapper()
: CEGUI::TextureTarget()
, bp::wrapper< CEGUI::TextureTarget >(){
// null constructor
}
virtual void clear( ){
bp::override func_clear = this->get_override( "clear" );
func_clear( );
}
virtual void declareRenderSize( ::CEGUI::Sizef const & sz ){
bp::override func_declareRenderSize = this->get_override( "declareRenderSize" );
func_declareRenderSize( boost::ref(sz) );
}
virtual ::CEGUI::Texture & getTexture( ) const {
throw std::logic_error("warning W1049: This method could not be overriden in Python - method returns reference to local variable!");
}
virtual bool isRenderingInverted( ) const {
bp::override func_isRenderingInverted = this->get_override( "isRenderingInverted" );
return func_isRenderingInverted( );
}
virtual void activate( ){
bp::override func_activate = this->get_override( "activate" );
func_activate( );
}
virtual void deactivate( ){
bp::override func_deactivate = this->get_override( "deactivate" );
func_deactivate( );
}
virtual void draw( ::CEGUI::GeometryBuffer const & buffer ){
bp::override func_draw = this->get_override( "draw" );
func_draw( boost::ref(buffer) );
}
virtual void draw( ::CEGUI::RenderQueue const & queue ){
bp::override func_draw = this->get_override( "draw" );
func_draw( boost::ref(queue) );
}
virtual void fireEvent( ::CEGUI::String const & name, ::CEGUI::EventArgs & args, ::CEGUI::String const & eventNamespace="" ) {
if( bp::override func_fireEvent = this->get_override( "fireEvent" ) )
func_fireEvent( boost::ref(name), boost::ref(args), boost::ref(eventNamespace) );
else{
this->CEGUI::EventSet::fireEvent( boost::ref(name), boost::ref(args), boost::ref(eventNamespace) );
}
}
void default_fireEvent( ::CEGUI::String const & name, ::CEGUI::EventArgs & args, ::CEGUI::String const & eventNamespace="" ) {
CEGUI::EventSet::fireEvent( boost::ref(name), boost::ref(args), boost::ref(eventNamespace) );
}
void fireEvent_impl( ::CEGUI::String const & name, ::CEGUI::EventArgs & args ){
CEGUI::EventSet::fireEvent_impl( boost::ref(name), boost::ref(args) );
}
virtual ::CEGUI::Rectf const & getArea( ) const {
throw std::logic_error("warning W1049: This method could not be overriden in Python - method returns reference to local variable!");
}
::CEGUI::ScriptModule * getScriptModule( ) const {
return CEGUI::EventSet::getScriptModule( );
}
virtual bool isImageryCache( ) const {
bp::override func_isImageryCache = this->get_override( "isImageryCache" );
return func_isImageryCache( );
}
virtual void setArea( ::CEGUI::Rectf const & area ){
bp::override func_setArea = this->get_override( "setArea" );
func_setArea( boost::ref(area) );
}
virtual ::CEGUI::RefCounted< CEGUI::BoundSlot > subscribeScriptedEvent( ::CEGUI::String const & name, ::CEGUI::String const & subscriber_name ) {
if( bp::override func_subscribeScriptedEvent = this->get_override( "subscribeScriptedEvent" ) )
return func_subscribeScriptedEvent( boost::ref(name), boost::ref(subscriber_name) );
else{
return this->CEGUI::EventSet::subscribeScriptedEvent( boost::ref(name), boost::ref(subscriber_name) );
}
}
::CEGUI::RefCounted< CEGUI::BoundSlot > default_subscribeScriptedEvent( ::CEGUI::String const & name, ::CEGUI::String const & subscriber_name ) {
return CEGUI::EventSet::subscribeScriptedEvent( boost::ref(name), boost::ref(subscriber_name) );
}
virtual ::CEGUI::RefCounted< CEGUI::BoundSlot > subscribeScriptedEvent( ::CEGUI::String const & name, unsigned int group, ::CEGUI::String const & subscriber_name ) {
if( bp::override func_subscribeScriptedEvent = this->get_override( "subscribeScriptedEvent" ) )
return func_subscribeScriptedEvent( boost::ref(name), group, boost::ref(subscriber_name) );
else{
return this->CEGUI::EventSet::subscribeScriptedEvent( boost::ref(name), group, boost::ref(subscriber_name) );
}
}
::CEGUI::RefCounted< CEGUI::BoundSlot > default_subscribeScriptedEvent( ::CEGUI::String const & name, unsigned int group, ::CEGUI::String const & subscriber_name ) {
return CEGUI::EventSet::subscribeScriptedEvent( boost::ref(name), group, boost::ref(subscriber_name) );
}
virtual void unprojectPoint( ::CEGUI::GeometryBuffer const & buff, ::CEGUI::Vector2f const & p_in, ::CEGUI::Vector2f & p_out ) const {
bp::override func_unprojectPoint = this->get_override( "unprojectPoint" );
func_unprojectPoint( boost::ref(buff), boost::ref(p_in), boost::ref(p_out) );
}
};
void register_TextureTarget_class(){
{ //::CEGUI::TextureTarget
typedef bp::class_< TextureTarget_wrapper, bp::bases< CEGUI::RenderTarget >, boost::noncopyable > TextureTarget_exposer_t;
TextureTarget_exposer_t TextureTarget_exposer = TextureTarget_exposer_t( "TextureTarget", "*!\n\
\n\
Specialisation of RenderTarget interface that should be used as the base\n\
class for RenderTargets that are implemented using textures.\n\
*\n" );
bp::scope TextureTarget_scope( TextureTarget_exposer );
{ //::CEGUI::TextureTarget::clear
typedef void ( ::CEGUI::TextureTarget::*clear_function_type )( ) ;
TextureTarget_exposer.def(
"clear"
, bp::pure_virtual( clear_function_type(&::CEGUI::TextureTarget::clear) )
, "*!\n\
\n\
Clear the surface of the underlying texture.\n\
*\n" );
}
{ //::CEGUI::TextureTarget::declareRenderSize
typedef void ( ::CEGUI::TextureTarget::*declareRenderSize_function_type )( ::CEGUI::Sizef const & ) ;
TextureTarget_exposer.def(
"declareRenderSize"
, bp::pure_virtual( declareRenderSize_function_type(&::CEGUI::TextureTarget::declareRenderSize) )
, ( bp::arg("sz") )
, "*!\n\
\n\
Used to declare to the TextureTarget the largest size, in pixels, of the\n\
next set of incoming rendering operations.\n\
\n\
\note\n\
The main purpose of this is to allow for the implemenatation to resize\n\
the underlying texture so that it can hold the imagery that will be\n\
drawn.\n\
\n\
@param sz\n\
Size object describing the largest area that will be rendererd in the\n\
next batch of rendering operations.\n\
\n\
@exception InvalidRequestException\n\
May be thrown if the TextureTarget would not be able to handle the\n\
operations rendering content of the given size.\n\
*\n" );
}
{ //::CEGUI::TextureTarget::getTexture
typedef ::CEGUI::Texture & ( ::CEGUI::TextureTarget::*getTexture_function_type )( ) const;
TextureTarget_exposer.def(
"getTexture"
, bp::pure_virtual( getTexture_function_type(&::CEGUI::TextureTarget::getTexture) )
, bp::return_value_policy< bp::reference_existing_object >()
, "*!\n\
\n\
Return a pointer to the CEGUI.Texture that the TextureTarget is using.\n\
\n\
@return\n\
Texture object that the TextureTarget uses when rendering imagery.\n\
*\n" );
}
{ //::CEGUI::TextureTarget::isRenderingInverted
typedef bool ( ::CEGUI::TextureTarget::*isRenderingInverted_function_type )( ) const;
TextureTarget_exposer.def(
"isRenderingInverted"
, bp::pure_virtual( isRenderingInverted_function_type(&::CEGUI::TextureTarget::isRenderingInverted) )
, "*!\n\
\n\
Return whether rendering done on the target texture is inverted in\n\
relation to regular textures.\n\
\n\
This is intended to be used when generating geometry for rendering the\n\
TextureTarget onto another surface.\n\
\n\
@return\n\
- true if the texture content should be considered as inverted\n\
vertically in comparison with other regular textures.\n\
- false if the texture content has the same orientation as regular\n\
textures.\n\
*\n" );
}
{ //::CEGUI::RenderTarget::activate
typedef void ( ::CEGUI::RenderTarget::*activate_function_type )( ) ;
TextureTarget_exposer.def(
"activate"
, bp::pure_virtual( activate_function_type(&::CEGUI::RenderTarget::activate) )
, "*!\n\
\n\
Activate the render target and put it in a state ready to be drawn to.\n\
\n\
\note\n\
You MUST call this before doing any rendering - if you do not call this,\n\
in the unlikely event that your application actually works, it will\n\
likely stop working in some future version.\n\
*\n" );
}
{ //::CEGUI::RenderTarget::deactivate
typedef void ( ::CEGUI::RenderTarget::*deactivate_function_type )( ) ;
TextureTarget_exposer.def(
"deactivate"
, bp::pure_virtual( deactivate_function_type(&::CEGUI::RenderTarget::deactivate) )
, "*!\n\
\n\
Deactivate the render target after having completed rendering.\n\
\n\
\note\n\
You MUST call this after you finish rendering to the target - if you do\n\
not call this, in the unlikely event that your application actually\n\
works, it will likely stop working in some future version.\n\
*\n" );
}
{ //::CEGUI::RenderTarget::draw
typedef void ( ::CEGUI::RenderTarget::*draw_function_type )( ::CEGUI::GeometryBuffer const & ) ;
TextureTarget_exposer.def(
"draw"
, bp::pure_virtual( draw_function_type(&::CEGUI::RenderTarget::draw) )
, ( bp::arg("buffer") )
, "*!\n\
\n\
Draw geometry from the given GeometryBuffer onto the surface that\n\
this RenderTarget represents.\n\
\n\
@param buffer\n\
GeometryBuffer object holding the geometry that should be drawn to the\n\
RenderTarget.\n\
*\n" );
}
{ //::CEGUI::RenderTarget::draw
typedef void ( ::CEGUI::RenderTarget::*draw_function_type )( ::CEGUI::RenderQueue const & ) ;
TextureTarget_exposer.def(
"draw"
, bp::pure_virtual( draw_function_type(&::CEGUI::RenderTarget::draw) )
, ( bp::arg("queue") )
, "*!\n\
\n\
Draw geometry from the given RenderQueue onto the surface that\n\
this RenderTarget represents.\n\
\n\
@param queue\n\
RenderQueue object holding the geometry that should be drawn to the\n\
RenderTarget.\n\
*\n" );
}
{ //::CEGUI::EventSet::fireEvent
typedef void ( ::CEGUI::EventSet::*fireEvent_function_type )( ::CEGUI::String const &,::CEGUI::EventArgs &,::CEGUI::String const & ) ;
typedef void ( TextureTarget_wrapper::*default_fireEvent_function_type )( ::CEGUI::String const &,::CEGUI::EventArgs &,::CEGUI::String const & ) ;
TextureTarget_exposer.def(
"fireEvent"
, fireEvent_function_type(&::CEGUI::EventSet::fireEvent)
, default_fireEvent_function_type(&TextureTarget_wrapper::default_fireEvent)
, ( bp::arg("name"), bp::arg("args"), bp::arg("eventNamespace")="" ) );
}
{ //::CEGUI::EventSet::fireEvent_impl
typedef void ( TextureTarget_wrapper::*fireEvent_impl_function_type )( ::CEGUI::String const &,::CEGUI::EventArgs & ) ;
TextureTarget_exposer.def(
"fireEvent_impl"
, fireEvent_impl_function_type( &TextureTarget_wrapper::fireEvent_impl )
, ( bp::arg("name"), bp::arg("args") )
, "! Implementation event firing member\n" );
}
{ //::CEGUI::RenderTarget::getArea
typedef ::CEGUI::Rectf const & ( ::CEGUI::RenderTarget::*getArea_function_type )( ) const;
TextureTarget_exposer.def(
"getArea"
, bp::pure_virtual( getArea_function_type(&::CEGUI::RenderTarget::getArea) )
, bp::return_value_policy< bp::copy_const_reference >()
, "*!\n\
\n\
Return the area defined for this RenderTarget.\n\
\n\
@return\n\
Rect object describing the currently defined area for this RenderTarget.\n\
*\n" );
}
{ //::CEGUI::EventSet::getScriptModule
typedef ::CEGUI::ScriptModule * ( TextureTarget_wrapper::*getScriptModule_function_type )( ) const;
TextureTarget_exposer.def(
"getScriptModule"
, getScriptModule_function_type( &TextureTarget_wrapper::getScriptModule )
, bp::return_value_policy< bp::reference_existing_object >()
, "! Implementation event firing member\n\
! Helper to return the script module pointer or throw.\n" );
}
{ //::CEGUI::RenderTarget::isImageryCache
typedef bool ( ::CEGUI::RenderTarget::*isImageryCache_function_type )( ) const;
TextureTarget_exposer.def(
"isImageryCache"
, bp::pure_virtual( isImageryCache_function_type(&::CEGUI::RenderTarget::isImageryCache) )
, "*!\n\
\n\
Return whether the RenderTarget is an implementation that caches\n\
actual rendered imagery.\n\
\n\
Typically it is expected that texture based RenderTargets would return\n\
true in response to this call. Other types of RenderTarget, like\n\
view port based targets, will more likely return false.\n\
\n\
@return\n\
- true if the RenderTarget does cache rendered imagery.\n\
- false if the RenderTarget does not cache rendered imagery.\n\
*\n" );
}
{ //::CEGUI::RenderTarget::setArea
typedef void ( ::CEGUI::RenderTarget::*setArea_function_type )( ::CEGUI::Rectf const & ) ;
TextureTarget_exposer.def(
"setArea"
, bp::pure_virtual( setArea_function_type(&::CEGUI::RenderTarget::setArea) )
, ( bp::arg("area") )
, "*!\n\
\n\
Set the area for this RenderTarget. The exact action this function\n\
will take depends upon what the concrete class is representing. For\n\
example, with a 'view port' style RenderTarget, this should set the area\n\
that the view port occupies on the display (or rendering window).\n\
\n\
@param area\n\
Rect object describing the new area to be assigned to the RenderTarget.\n\
\n\
\note\n\
When implementing this function, you should be sure to fire the event\n\
RenderTarget.EventAreaChanged so that interested parties can know that\n\
the change has occurred.\n\
\n\
@exception InvalidRequestException\n\
May be thrown if the RenderTarget does not support setting or changing\n\
its area, or if the area change can not be satisfied for some reason.\n\
*\n" );
}
{ //::CEGUI::EventSet::subscribeScriptedEvent
typedef ::CEGUI::RefCounted< CEGUI::BoundSlot > ( ::CEGUI::EventSet::*subscribeScriptedEvent_function_type )( ::CEGUI::String const &,::CEGUI::String const & ) ;
typedef ::CEGUI::RefCounted< CEGUI::BoundSlot > ( TextureTarget_wrapper::*default_subscribeScriptedEvent_function_type )( ::CEGUI::String const &,::CEGUI::String const & ) ;
TextureTarget_exposer.def(
"subscribeScriptedEvent"
, subscribeScriptedEvent_function_type(&::CEGUI::EventSet::subscribeScriptedEvent)
, default_subscribeScriptedEvent_function_type(&TextureTarget_wrapper::default_subscribeScriptedEvent)
, ( bp::arg("name"), bp::arg("subscriber_name") ) );
}
{ //::CEGUI::EventSet::subscribeScriptedEvent
typedef ::CEGUI::RefCounted< CEGUI::BoundSlot > ( ::CEGUI::EventSet::*subscribeScriptedEvent_function_type )( ::CEGUI::String const &,unsigned int,::CEGUI::String const & ) ;
typedef ::CEGUI::RefCounted< CEGUI::BoundSlot > ( TextureTarget_wrapper::*default_subscribeScriptedEvent_function_type )( ::CEGUI::String const &,unsigned int,::CEGUI::String const & ) ;
TextureTarget_exposer.def(
"subscribeScriptedEvent"
, subscribeScriptedEvent_function_type(&::CEGUI::EventSet::subscribeScriptedEvent)
, default_subscribeScriptedEvent_function_type(&TextureTarget_wrapper::default_subscribeScriptedEvent)
, ( bp::arg("name"), bp::arg("group"), bp::arg("subscriber_name") ) );
}
{ //::CEGUI::RenderTarget::unprojectPoint
typedef void ( ::CEGUI::RenderTarget::*unprojectPoint_function_type )( ::CEGUI::GeometryBuffer const &,::CEGUI::Vector2f const &,::CEGUI::Vector2f & ) const;
TextureTarget_exposer.def(
"unprojectPoint"
, bp::pure_virtual( unprojectPoint_function_type(&::CEGUI::RenderTarget::unprojectPoint) )
, ( bp::arg("buff"), bp::arg("p_in"), bp::arg("p_out") )
, "*!\n\
\n\
Take point p_in unproject it and put the result in p_out.\n\
Resulting point is local to GeometryBuffer buff.\n\
*\n" );
}
}
}
|
class Solution {
public:
// bool isUgly(int num) {
// if (num<=0) return false;
// while (num%30==0) num = num/30;
// while (num%15==0) num = num/15;
// while (num%10==0) num = num/10;
// while (num%6==0) num = num/6;
// while (num%5==0) num = num/5;
// while (num%3==0) num = num/3;
// while (num%2==0) num = num/2;
// return num==1;
// }
int nthUglyNumber(int n) {
// int result = 1;
// for (int i = 0; i<n;i++) {
// while (!isUgly(result++)) {
// }
// }
// return result-1;
vector<int> result = {1};
int temp2,temp3,temp5,tempmin;
int p2 = 0,p3 = 0,p5 = 0;
while (result.size()!=n) {
temp2 = result[p2]<<1;
temp3 = result[p3]*3;
temp5 = result[p5]*5;
tempmin = min(min(temp2,temp3),temp5);
if(tempmin == temp2)
p2++;
if(tempmin == temp3)
p3++;
if(tempmin == temp5)
p5++;
result.push_back(tempmin);
}
return result.back();
}
};
|
#include "personpage.h"
#include "ui_personpage.h"
#include <QDebug>
#include <QDialog>
#include<QSqlQueryModel>
personpage::personpage(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::personpage)
{
ui->setupUi(this);
}
personpage::~personpage()
{
delete ui;
}
void personpage::on_pushButton_mycon_clicked()
{
QDialog dlg;
dlg.resize(300,300);
dlg.exec();
}
void personpage::init()
{
qDebug()<<pgname;
QString sql2;
sql2="select username from user where username='"+pgname+"'";
QSqlQueryModel *model2=new QSqlQueryModel;
model2->setQuery(sql2);
ui->tableView_2->setModel(model2);
QString sql;
sql="select username as 用户名 ,title as 帖子名,content as 帖子 from content_ where username='"+pgname+"'";
QSqlQueryModel *model=new QSqlQueryModel;
model->setQuery(sql);
ui->tableView->setModel(model);
}
|
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <pHash.h>
using namespace std;
using namespace cv;
int SimpleHashSim(Mat matSrc1, Mat matSrc2)
{
CV_Assert(matSrc1.channels() == 3);
CV_Assert(matSrc2.channels() == 3);
cv::Mat matDst1, matDst2;
cv::resize(matSrc1, matDst1, cv::Size(8, 8), 0, 0, cv::INTER_CUBIC);
cv::resize(matSrc2, matDst2, cv::Size(8, 8), 0, 0, cv::INTER_CUBIC);
cv::cvtColor(matDst1, matDst1, CV_BGR2GRAY);
cv::cvtColor(matDst2, matDst2, CV_BGR2GRAY);
int iAvg1 = 0, iAvg2 = 0;
int arr1[64], arr2[64];
for (int i = 0; i < 8; i++)
{
uchar* data1 = matDst1.ptr<uchar>(i);
uchar* data2 = matDst2.ptr<uchar>(i);
int tmp = i * 8;
for (int j = 0; j < 8; j++)
{
int tmp1 = tmp + j;
arr1[tmp1] = data1[j] / 4 * 4;
arr2[tmp1] = data2[j] / 4 * 4;
iAvg1 += arr1[tmp1];
iAvg2 += arr2[tmp1];
}
}
iAvg1 /= 64;
iAvg2 /= 64;
for (int i = 0; i < 64; i++)
{
arr1[i] = (arr1[i] >= iAvg1) ? 1 : 0;
arr2[i] = (arr2[i] >= iAvg2) ? 1 : 0;
}
int iDiffNum = 0;
for (int i = 0; i < 64; i++)
if (arr1[i] != arr2[i])
++iDiffNum;
return iDiffNum;
}
void sort_names(char **names, int L1)
{
for (int i=0; i < L1; i++)
{
int min = i;
for (int j = i+1; j < L1; j++)
{
if (strcmp(names[j], names[min]) <= 0)
min = j;
}
if (i != min)
{
char *swap = names[i];
names[i] = names[min];
names[min] = swap;
}
}
}
string pHashString(uint8_t *hash, int len)
{
string hashstr;
for (int i = 0; i < len; i++)
{
char s[2] = "";
snprintf(s, sizeof(s), "%X", hash[i]);
hashstr.append(s);
}
return hashstr;
}
void picture_upload_choose(std::vector<string> &filelist, std::vector<uint8_t*> &hashlist, int hashlen)
{
int filecount = filelist.size();
//cout << "file list size " << filecount << endl;
for (int i = 0; i < filecount-1; i++)
{
for (int j = i+1;j < filecount; j++)
{
double dist = ph_hammingdistance2(hashlist[i], hashlen, hashlist[j], hashlen);
double imgdist = exp(dist*10);
printf("[%02d] and [%02d] hamming distance %.2f.\n", i, j, imgdist);
if(exp(dist*10) <= 20.0)/* Default 5.0 */
{
filelist[j].clear();
}
}
}
std::vector<string>::iterator fileit;
std::vector<uint8_t*>::iterator hashit;
for(fileit = filelist.begin(), hashit = hashlist.begin();
fileit != filelist.end(), hashit != hashlist.end();)
{
if((*fileit).size() == 0)
{
fileit = filelist.erase(fileit);
free(*hashit);
hashit = hashlist.erase(hashit);
}
else
{
++fileit;
++hashit;
}
}
}
int main(int argc, char* argv[])
{
string strSrcImageName;
string strTgtImageName;
string strDirpath;
if(argc == 3)
{
strSrcImageName = argv[1];
strTgtImageName = argv[2];
// Load source image and target image
cv::Mat matSrc = cv::imread(strSrcImageName, CV_LOAD_IMAGE_COLOR);
cv::Mat matTgt = cv::imread(strTgtImageName, CV_LOAD_IMAGE_COLOR);
// Simple hash compare
{
int diff_macro = SimpleHashSim(matSrc, matTgt);
cout << "Macro block diff: " << diff_macro;
if (diff_macro <= 5)
cout<<"--two images are very similar!"<<endl;
else if (diff_macro > 10)
cout<<"--they are two different images!"<<endl;
else
cout<<"--two image are somewhat similar!"<<endl;
}
// pHash compare
{
double pcc = 0.0;
int ret = ph_compare_images(strSrcImageName.c_str(), strTgtImageName.c_str(), pcc);
cout << "pHash compare ret " << ret << " pcc=" << pcc;
if(ret == 1)
cout << "--two images are similar." << endl;
else if(ret == 0)
cout << "--two images are different." << endl;
}
}
else if(argc == 2)
{
strDirpath = argv[1];
int filecount;
char **files = ph_readfilenames(strDirpath.c_str(), filecount);
std::vector<string> filelist;
std::vector<uint8_t*> hashlist;
int alpha = 2.0;
int level = 1.0;
int hashlen = 0;
for(int i = 0; i < filecount; ++i)
{
filelist.push_back(files[i]);
uint8_t *hash = ph_mh_imagehash(files[i], hashlen, alpha, level);
hashlist.push_back(hash);
//cout << "File " << filelist[i].c_str() << " Hash: " << pHashString(hash, hashlen) << endl;
free(files[i]);
}
free(files);
// First sift
picture_upload_choose(filelist, hashlist, hashlen);
// Second sift
picture_upload_choose(filelist, hashlist, hashlen);
cout << "Total upload size " << filelist.size() << endl;
for(auto it = filelist.begin(); it != filelist.end(); it++)
{
cout << *it << endl;
}
for(auto it = hashlist.begin(); it != hashlist.end(); it++)
{
free(*it);
}
}
else
{
std::cout << "Usage: " << argv[0] << " [src image path] [target image path]" << std::endl;
std::cout << "Usage: " << argv[0] << " [src image dirpath]" << std::endl;
exit(0);
}
getchar();
return 0;
}
|
/***************************************************
Materia: Gráficas Computacionales
Tarea: 9 Texturas
Fecha: 3 de abril de 2011
Autor 1: 1162205 Diego Alfonso Garcia Mendiburu
***************************************************/
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#define MINTRIANGULOS 10
#define MAXTRIANGULOS 100
#define IMAGESIZE 512
float MAXALTURA = .2;
char textura[] ="Madera.ppm";
char altura[] = "espiral.ppm";
float rotationX=0.0;
float rotationY=0.0;
float prevX=0.0;
float prevY=0.0;
bool mouseDown=false;
float viewer[]= {0.0, 0.0, 1.0};
GLuint texName=0;
unsigned char woodtexture[IMAGESIZE][IMAGESIZE][3];
unsigned char woodHeight[IMAGESIZE][IMAGESIZE][3];
int numFilas = 100;
int heightSize;
void calcAltura(){
int w, h, d;
char *c;
FILE *fp;
int i, j, k;
fp = fopen(altura,"rb");
fscanf(fp,"%s ", &c);
fscanf(fp,"%d %d %d ", &w, &h, &d) ;
//heightSize = w;
for (i = 0 ; i < w ; i++)
for (j = 0 ; j < h ; j++)
for (k = 0 ; k < 3 ; k++)
fscanf(fp,"%c",&(woodHeight[i][j][k])) ;
fclose(fp);
}
float getAltura(int v){
if(v == 255)
return (GLfloat) MAXALTURA;
else
return (GLfloat)(v * MAXALTURA) / 255.0;
}
void initTexture(){
/* First, read this simple ppm file in */
int w, h, d;
char *c;
FILE *fp;
int i, j, k;
fp = fopen(textura,"rb");
fscanf(fp,"%s ", &c);
fscanf(fp,"%d %d %d ", &w, &h, &d) ;
for (i = 0 ; i < w ; i++)
for (j = 0 ; j < h ; j++)
for (k = 0 ; k < 3 ; k++)
fscanf(fp,"%c",&(woodtexture[i][j][k])) ;
fclose(fp) ;
/* Now, set up all the stuff for texturing, per page 368 */
glGenTextures(1, &texName) ;
//glBindTexture(GL_TEXTURE_2D, texName) ;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) ;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) ;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) ;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) ;
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB, IMAGESIZE, IMAGESIZE, 0, GL_RGB,
GL_UNSIGNED_BYTE, woodtexture);
}
void specialKey(int c, int x, int y){
if(c == GLUT_KEY_UP) {
if(MAXALTURA < 1)
MAXALTURA += 0.02;
}
if(c == GLUT_KEY_DOWN) {
if(MAXALTURA > 0)
MAXALTURA -= 0.02;
}
glutPostRedisplay();
}
void key(unsigned char key, int x, int y)
{
if(key == '+' && numFilas < MAXTRIANGULOS) {
numFilas += 1;
//numFilas *= 2;
printf("Numero de filas %d \n", numFilas);
}
if(key == '-' && numFilas > MINTRIANGULOS) {
numFilas -= 1;
//numFilas /= 2;
printf("Numero de filas %d \n", numFilas);
}
if(key == 'x') viewer[0]-= 0.1;
if(key == 'X') viewer[0]+= 0.1;
if(key == 'y') viewer[1]-= 0.1;
if(key == 'Y') viewer[1]+= 0.1;
if(key == 'z') viewer[2]-= 0.1;
if(key == 'Z') viewer[2]+= 0.1;
glutPostRedisplay();
}
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor3f(1,1,1);
gluLookAt(viewer[0],viewer[1],viewer[2],0,0,0,0,1,0);
glRotatef(rotationX,1,0,0);
glRotatef(rotationY,0,1,0);
//glTranslatef(1.0,1.0,0);
//glRotatef(90,0,0,1);
//glTranslatef(.5,.5,0);
float posActualX, posActualY, posActualZ;
posActualX = posActualY = posActualZ = 0.0;
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
for(int i = 0; i < numFilas; i++){
for(int j = 0; j < numFilas; j++){
//glBegin(GL_POLYGON);
glBegin(GL_TRIANGLES);
//Vertice 1
glTexCoord2f(posActualX, posActualY);
int im = IMAGESIZE / numFilas;
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * i][im * j][0]));
//printf("[%d,%d,%d]\n", i, j, im * i);
posActualX += 1/(GLfloat)numFilas;
//Vertice 2
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * i][im * (j+1)][0]));
posActualY += 1/(GLfloat)numFilas;
//Vertice 3
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * (i+1)][im * (j+1)][0]));
//Vertice 4
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * (i+1)][im * (j+1)][0]));
posActualX -= 1/(GLfloat)numFilas;
//Vertice 5
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * (i+1)][im * j][0]));
posActualY -= 1/(GLfloat)numFilas;
//Vertice 6
glTexCoord2f(posActualX, posActualY);
glVertex3f(posActualX, posActualY, getAltura(woodHeight[im * i][im * j][0]));
posActualX += 1/(GLfloat)numFilas;
glEnd();
}
posActualY += 1/(GLfloat)numFilas;
posActualX = 0;
}
//
glutSwapBuffers();
}
void initializeGL(void)
{
glEnable(GL_DEPTH_TEST);
glClearColor(0,0,0,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-0.5, 1.5, -0.5, 1.5, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D) ;
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) ;
glBindTexture(GL_TEXTURE_2D, texName) ;
initTexture();
calcAltura();
}
void mouse(int button, int state, int x, int y){
printf("pica\n");
if(button == GLUT_LEFT_BUTTON && state==GLUT_DOWN){
mouseDown = true;
prevX = x - rotationY;
prevY = y - rotationX;
}else{
mouseDown = false;
}
}
void mouseMotion(int x, int y){
printf("moviendo\n");
if(mouseDown){
rotationX = y - prevY;
rotationY = x - prevX;
glutPostRedisplay();
}
}
main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(500,500);
glutInitWindowPosition(100, 150);
glutCreateWindow("Usando una imagen como textura");
glutKeyboardFunc(key);
glutSpecialFunc(specialKey);
glutDisplayFunc(myDisplay);
glutMouseFunc(mouse);
glutMotionFunc(mouseMotion);
initializeGL();
glutMainLoop();
}
|
#ifndef CELDA_H
#define CELDA_H
#include "../interfaces/espaciable.h"
#include "celda_base.h"
namespace App_Niveles
{
class Celda:
public Celda_base,
public App_Interfaces::Espaciable
{
//////////
//Definiciones...
public:
enum class tipo_celda {solida};
///////////
// Interface pública
public:
Celda(App_Definiciones::t_dim px, App_Definiciones::t_dim py, tipo_celda pt);
//////////////////////////////
//Implementación de Espaciable
public:
virtual Espaciable::t_caja copia_caja() const;
//Ninguna de estas funciones hace nada porque la celda es inamovible.
virtual void mut_x_caja(float) {}
virtual void mut_y_caja(float) {}
virtual void desplazar_caja(float, float) {}
virtual void mut_w_caja(unsigned int) {}
virtual void mut_h_caja(unsigned int) {}
//////////
// Propiedades
private:
tipo_celda tipo;
};
}
#endif
|
#include "Command.hpp"
#include "CmdQueue.hpp"
#include "SException.hpp"
namespace rustling
{
CmdQueue::CmdQueue():
queue(0x0)
{}
CmdQueue::CmdQueue(
Context &ctx,
Device &dev,
cl_command_queue_properties properties)
{
ret_code ret;
auto context_ = ctx.getContext();
auto device_ = dev.getID();
queue = clCreateCommandQueue(ctx.getContext(), dev.getID(), properties, &ret);
if (ret != CL_SUCCESS)
throw(SException(ret));
}
CmdQueue::CmdQueue(const CmdQueue &other):
queue(other.queue)
{
auto ret = clRetainCommandQueue(queue);
if(ret!=CL_SUCCESS)
throw(SException(ret));
}
CmdQueue &CmdQueue::operator=(const CmdQueue &other)
{
this->queue=other.queue;
auto ret = clRetainCommandQueue(queue);
if(ret!=CL_SUCCESS)
throw(SException(ret));
}
CmdQueue::~CmdQueue()
{
clReleaseCommandQueue(queue);
}
cl_command_queue CmdQueue::getQueue()
{
return queue;
}
CmdQueue& CmdQueue::operator <<(BasicCommand& cmd)
{
try {
cmd.execute(*this);
return *this;
} catch (SException &e) {
throw (e);
}
}
CmdQueue& CmdQueue::operator <<(EventCommand& cmd)
{
try {
cmd.execute(*this);
cmd.unsetEvent();
return *this;
} catch (SException &e) {
throw (e);
}
}
}
|
#include<stdio.h>
int h[101],n;//设置数组存放完全二叉树,n为堆中元素个数
void swap(int x,int y);//结点x与结点y进行交换
void siftdown(int i);//从结点i开始向下调整
void creat();//建立堆的函数
void heapsort();//堆排序函数
int main()
{
int num,i;
//读取堆中元素个数
scanf("%d",&num);
//读入堆中元素
for(i=1;i<=num;i++)
scanf("%d",&h[i]);
n=num;//元素的个数会后面操作改变,num当作循环变量用
creat();//创建堆
//堆排序
heapsort();
//输出排序后的值
for(i=1;i<=num;i++)
printf("%d ",h[i]);
return 0;
}
void swap(int x,int y)
{
int temp;
temp=h[x];
h[x]=h[y];
h[y]=temp;
}
void siftdown(int i)//此处的向下调整函数是为了建立最大堆
{
int t,flag=0;//t用来确定是否需要交换,flag用来标记是否处于合适的根结点处
while(i*2<=n && 0==flag)
{
t=i;//初始赋值相同的编号
//能进入循环说明左儿子一定存在,先于左儿子比较
if(h[i]<h[2*i])
{
t=2*i;//待交换的结点编号
}
//判断是否有右儿子
if(2*i+1<=n)
{
//与右儿子进行比较
if(h[t]<h[i*2+1])
{
t=i*2+1;//待交换的结点编号
}
}
if(t!=i)//不相等说明需要交换
{
swap(i,t);//交换两节点
i=t;//交换后,向下调整的元素的编号也变了
}
else
flag=1;//不需要交换则说明该元素已经处于合适的根结点处
}
return ;
}
void heapsort()
{
//堆排序,每次将堆顶与最后一个数交换,再向下调整
while(n>1)//注意此处,剩余最后一个数放到堆顶自动是最小的,循环条件为只剩一个元素
{
swap(1,n);
n--;
siftdown(1);
}
return ;
}
void creat()
{
//建立堆的函数,每个子树满足最大堆,从而整棵树也满足
int i;
for(i=n/2;i>=1;i--)
{
siftdown(i);
}
return ;
}
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int opening_bracket = 0;
int closing_bracket = 0;
int simb = 0;
int str_s = 0;
int rec(string& str, ofstream& output)
{
while (str.size())
{
//output << str << endl;
cout << str << endl;
cout << opening_bracket << endl;
cout << closing_bracket << endl;
if (((str[0] >= 97 && str[0] <= 122) || (str[0] >= 65 && str[0] <= 90)) && (str.size() == 1))
return 0;
if (str[0] == '(')
{
opening_bracket++;
str = str.substr(1, str.size() - 1);
int k = rec(str, output);
str = str.substr(k, str.size() - k);
if (str[0] == ')')
continue;
if (str[0] == '\0')
return 0;
if ((str[0] == '-' || str[0] == '*' || str[0] == '+') && ((str[1] >= 97 && str[1] <= 122) || str[1] == '(' || (str[0] >= 65 && str[0] <= 90)))
{
if (str[1] == '(') {
opening_bracket++;
simb++;
}
if (str[1] != '(') {
simb+=2;
}
str = str.substr(2, str.size() - 2);
continue;
}
if (str[0] != '*' && str[0] != '+' && str[0] != '-')
{
output << "Error1" << endl;
cout << "Error1" << endl;
exit(0);
}
}
else
{
if (str[0] == ')')
{
if (str[1] >= 97 && str[1])
{
output << "Error2" << endl;
cout << "Error2" << endl;
exit(0);
}
closing_bracket++;
str = str.substr(1, str.size() - 1);
if ((str[0] == '-' || str[0] == '*' || str[0] == '+') && ((str[1] >= 97 && str[1] <= 122) || str[1] == '(' || (str[0] >= 65 && str[0] <= 90)))
{
if (str[1] == '(') {
opening_bracket++;
simb++;
}
if (str[1] != '(') {
simb+=2;
}
str = str.substr(2, str.size() - 2);
continue;
}
continue;
}
if ((str[0] >= 97 && str[0] <= 122) || (str[0] >= 65 && str[0] <= 90)) {
if (str[1] == '*' || str[1] == '+' || str[1] == '-') {
if ((str[2] >= 97 && str[2] <= 122) || (str[2] >= 65 && str[2] <= 90)) {
simb += 3;
return 3;
}
else {
str = str.substr(2, str.size() - 2);
simb += 2;
continue;
}
}
else {
simb++;
return 1;
}
}
output << "Error3" << endl;
cout << "Error3" << endl;
//output << str << endl;
cout << str << endl;
exit(0);
}
}
return 0;
}
int main() {
{
ofstream output("/Users/Elizaveta/source/repos/lr1/output.txt");
string com, str;
cout << R"(Would u like to get input from "input.txt"? Y/N)" << endl;
cin >> com;
if (com[0] == 'Y') {
cout << R"(Searching for it...)" << endl;
ifstream input("input.txt", ifstream::in);
if (input.fail()) {
cout << "File is not certain." << endl;
return 0;
}
getline(input, str);
}
else if (com[0] == 'N') {
cout << R"(Then type the string!)" << endl;
cin >> str;
}
else {
cout << "Try once again..." << endl;
return 0;
}
output << str << endl;
cout << str << endl;
str_s = str.size();
rec(str, output);
if (opening_bracket == closing_bracket) {
if (simb >= (2 * opening_bracket + 1)) {
output << "Correct" << endl;
cout << "Correct" << endl;
}
else {
output << "Ooops" << endl;
cout << "Ooops" << endl;
}
}
else {
output << "Invalid brackets" << endl;
cout << "Invalid brackets" << endl;
}
return 0;
}
}
|
// Copyright 2017 The Ray Authors.
//
// 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 "ray/core_worker/store_provider/memory_store/memory_store.h"
#include "gtest/gtest.h"
#include "ray/common/test_util.h"
namespace ray {
TEST(TestMemoryStore, TestReportUnhandledErrors) {
std::vector<std::shared_ptr<RayObject>> results;
WorkerContext context(WorkerType::WORKER, WorkerID::FromRandom(), JobID::FromInt(0));
int unhandled_count = 0;
std::shared_ptr<CoreWorkerMemoryStore> provider =
std::make_shared<CoreWorkerMemoryStore>(
nullptr, nullptr, nullptr, nullptr,
[&](const RayObject &obj) { unhandled_count++; });
RayObject obj1(rpc::ErrorType::TASK_EXECUTION_EXCEPTION);
RayObject obj2(rpc::ErrorType::TASK_EXECUTION_EXCEPTION);
auto id1 = ObjectID::FromRandom();
auto id2 = ObjectID::FromRandom();
// Check delete without get.
RAY_CHECK(provider->Put(obj1, id1));
RAY_CHECK(provider->Put(obj2, id2));
ASSERT_EQ(unhandled_count, 0);
provider->Delete({id1, id2});
ASSERT_EQ(unhandled_count, 2);
unhandled_count = 0;
// Check delete after get.
RAY_CHECK(provider->Put(obj1, id1));
RAY_CHECK(provider->Put(obj1, id2));
provider->Get({id1}, 1, 100, context, false, &results);
provider->GetOrPromoteToPlasma(id2);
provider->Delete({id1, id2});
ASSERT_EQ(unhandled_count, 0);
// Check delete after async get.
provider->GetAsync({id2}, [](std::shared_ptr<RayObject> obj) {});
RAY_CHECK(provider->Put(obj1, id1));
RAY_CHECK(provider->Put(obj2, id2));
provider->GetAsync({id1}, [](std::shared_ptr<RayObject> obj) {});
provider->Delete({id1, id2});
ASSERT_EQ(unhandled_count, 0);
}
} // namespace ray
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
class Solution {
public:
bool isSafe(int board[][10],int i,int j,int n){
for(int row=0;row<i;row++){
if(board[row][j]==1){
return false;
}
}
int x = i;
int y = j;
while(x>=0 && y>=0){
if(board[x][y]==1){
return false;
}
x--;
y--;
}
x = i;
y = j;
while(x>=0 && y<=n){
if(board[x][y]==1){
return false;
}
x--;
y++;
}
return true;
}
bool solve(int board[][10],int i,int n,vector<vector<string>> &v){
if(i == n){
vector<string> S;
for(int i=0;i<n;i++){
string s="";
for(int j=0;j<n;j++){
if(board[i][j] == 1){
s += "Q";
}
else
s += ".";
}
S.push_back(s);
}
v.push_back(S);
return false;
}
for(int j=0;j<n;j++){
if(isSafe(board,i,j,n)){
board[i][j] = 1;
bool QueenRakhPaye = solve(board,i+1,n,v);
if(QueenRakhPaye)
return true;
board[i][j] = 0;
}
}
return false;
}
vector<vector<string>> solveNQueens(int n) {
int board[10][10] = {0};
vector<vector<string>> v;
solve(board,0,n,v);
return v;
}
};
|
#ifndef MEMORY_H
#define MEMORY_H
#include <iostream>
#include <bitset>
#define MEMORY_SIZE 4096
#define BIT_DEPTH 32
class Memory
{
private:
int8_t mem[MEMORY_SIZE];
public:
Memory(){};
//~Memory();
void init_mem();
int store(int addr, int8_t data);
int8_t load(int addr);
};
#endif
|
///////////////////////////////////////////////////////
//
// Copyright � 1994 Jens Gebhard
//
// DATEI: GREEN.H
//
// ZWECK: Deklaration der Klasse GreenAlgorithmus
//
///////////////////////////////////////////////////////
#if !defined(__GREEN_H)
#define __GREEN_H
#include <iostream>
#include "pitman.h"
//////////////////////////////////////////////////////
//
// Klasse: GreenAlgorithmus
// Basisklasse: PermutationTest
//
// Zweck: Implementierung des Green-
// algorithmus
//
class GreenAlgorithmus: public PermutationTest
{
public:
GreenAlgorithmus():
PermutationTest()
{
NoOptimization=FALSE;
}
protected:
virtual BOOL CanDo();
double ExecPermutation();
void Rek(int);
void RekNoOptimization(int);
virtual BOOL DoYouKnowTheseOptions(char*);
virtual void SetOptions(char*);
virtual void PreProcessMessage() const;
virtual void PostProcessMessage() const;
private:
unsigned long FoundLowerValue;
unsigned long Summe;
int Level;
BOOL NoOptimization;
};
#endif //__GREEN_H
|
#include <cstdio>
// 二分查找框架, 特定值
int binary_search(int arr[], int len, int x) {
int low = 0,
high = len - 1;
int mid;
while(low <= high) {
mid = (low + high)/2;
if(arr[mid] == x) {
return mid;
} else if(arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {0, 1, 11, 22, 23, 27, 33, 35, 45, 49, 57, 60, 68, 73, 73, 74, 74, 80, 85, 90};
int len = sizeof(arr) / sizeof(arr[0]);
int x;
scanf("%d", &x);
printf("Position Index: %d", binary_search(arr, len, x));
return 0;
}
|
#ifndef IMPRIMIR_H
#define IMPRIMIR_H
class Imprimir
{
public:
Imprimir();
virtual ~Imprimir();
protected:
private:
};
#endif // IMPRIMIR_H
|
#include "stdafx.h"
#include <stdlib.h>
#include <string>
#include <iostream>
#include <stdio.h>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <set>
#include <unordered_set>
#include <direct.h>
#include <assert.h>
#include <fstream>
using namespace std;
string exec(const char* cmd) {
FILE* pipe = _popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[300];
string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 300, pipe) != NULL)
result += buffer;
}
_pclose(pipe);
return result;
}
void custom_replace(string& text, const string searchString, const string replaceString)
{
assert( searchString != replaceString );
string::size_type pos = 0;
while ( (pos = text.find(searchString, pos)) != string::npos )
{
text.replace( pos, searchString.size(), replaceString );
pos++;
}
}
const char* node_types[] =
{
"null", "document", "element", "pcdata", "cdata", "comment", "pi", "declaration"
};
struct simple_walker: pugi::xml_tree_walker
{
simple_walker(string node,string value,bool append) : _node(node), _value(value), _append(append)
{
}
virtual bool for_each(pugi::xml_node& node)
{
if (string(node.name()) == _node)
{
pugi::xml_node child = node.first_child();
string new_value="";
if (_append)
new_value = child.value() + _value;
else new_value = _value;
child.set_value(new_value.c_str());
}
return true; // continue traversal
}
string _node;
string _value;
bool _append;
};
struct simple_walker_add: pugi::xml_tree_walker
{
simple_walker_add(string node,string new_node_name,string new_node_value) : _node(node), _new_node_name(new_node_name), _new_node_value(new_node_value)
{
}
virtual bool for_each(pugi::xml_node& node)
{
if (string(node.name()) == _node)
{
pugi::xml_node param = node.append_child(_new_node_name.c_str());
param.append_child(pugi::node_pcdata).set_value(_new_node_value.c_str());
}
return true; // continue traversal
}
string _node;
string _new_node_name;
string _new_node_value;
};
struct replace_value_walker: pugi::xml_tree_walker
{
string _node;
string _search_value;
string _new_value;
replace_value_walker(string node,string search_value,string new_value) : _node(node), _search_value(search_value), _new_value(new_value)
{
}
virtual bool for_each(pugi::xml_node& node)
{
if (string(node.name()) == _node)
{
pugi::xml_node child = node.first_child();
string v = string(child.value());
custom_replace(v,_search_value,_new_value);
child.set_value(v.c_str());
}
return true; // continue traversal
}
};
string get_project_name_noextension(const string full_path)
{
int n = full_path.find_last_of("/");
string executable;
executable.assign(full_path,n+1,full_path.size()-n);
custom_replace(executable,".vcxproj","");
return executable;
}
bool compare_string_case_insesnsitive(string s1,string s2)
{
std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower);
std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower);
return s1.compare(s2) == 0;
}
string get_global_openvibe_includes(string openvibe_base,const string full_path)
{
string project_shortname= get_project_name_noextension(full_path);
string result="";
//global
result+=openvibe_base+"/openvibe/trunc/include;";
result+=openvibe_base+"/openvibe-toolkit/trunc/src;";
result+=openvibe_base+"/cmake-modules;";
result+=openvibe_base+"/openvibe-modules/ebml/trunc/include;";
result+=openvibe_base+"/openvibe-toolkit/trunc/include/openvibe-toolkit/tools;";
result+=openvibe_base+"/openvibe-modules/system/trunc/include;";
result+=openvibe_base+"/openvibe-modules/xml/trunc/include;";
result+=openvibe_base+"/openvibe-modules/fs/trunc/include;";
result+=openvibe_base+"/openvibe-modules/automaton/trunc/include;";
result+=openvibe_base+"/openvibe-modules/socket/trunc/include;";
result+=openvibe_base+"/openvibe-modules/stream/trunc/include;";
result+=openvibe_base+"/dependencies/boost/include;";
result+=openvibe_base+"/dependencies/openal/include;";
result+=openvibe_base+"/openvibe/trunc/include/openvibe;";
result+=openvibe_base+"/openvibe-toolkit/trunc/include/openvibe-toolkit;";
result+=openvibe_base+"/dependencies/vrpn/include;";
//new in OpenVibe ver 0.14
if (compare_string_case_insesnsitive(project_shortname,string("OpenViBE-acquisition-server-dynamic")))
{
result+=openvibe_base+"/dependencies/pthreads/include;";
}
//per project
if (compare_string_case_insesnsitive(project_shortname,string("OpenViBE-plugins-stimulation-dynamic")))
{
result+=openvibe_base+"/dependencies/libvorbis/include;";
result+=openvibe_base+"/dependencies/freealut/include;";
result+=openvibe_base+"/dependencies/lua/include;";
result+=openvibe_base+"/dependencies/openal/include;";
result+=openvibe_base+"/dependencies/libogg/include;";
}
if (compare_string_case_insesnsitive(project_shortname,string("OpenViBE-kernel-dynamic")))
{
result+=openvibe_base+"/dependencies/ogre/include/OGRE;";
}
return result;
}
string get_libs(string openvibe_base,const string full_path)
{
string project_shortname= get_project_name_noextension(full_path);
string result=";";
//global
result+=openvibe_base+"/dependencies/boost/lib;";
//per project
//new in OpenVibe ver 0.14
if (compare_string_case_insesnsitive(project_shortname,string("OpenViBE-acquisition-server-dynamic")))
{
result+=openvibe_base+"/dependencies/pthreads/lib;";
}
if (compare_string_case_insesnsitive(project_shortname,string("OpenViBE-plugins-stimulation-dynamic")))
{
result+=openvibe_base+"/dependencies/freealut/lib;";
result+=openvibe_base+"/dependencies/libvorbis/lib;";
result+=openvibe_base+"/dependencies/openal/libs;";
result+=openvibe_base+"/dependencies/lua/lib;";
result+=openvibe_base+"/dependencies/libogg/win32/lib;";
}
return result;
}
string get_openvibe_executable(const string full_path)
{
int n = full_path.find_last_of("/");
string executable;
executable.assign(full_path,n+1,full_path.size()-n);
custom_replace(executable,".vcxproj","");
return executable + ".exe";
}
string get_openvibe_base_folder(const string full_path)
{
int n = full_path.find_last_of("/");
string folder;
folder.assign(full_path,0,n+1);
folder = folder+"../../..";
return folder;
}
bool file_exists(const char *filename)
{
ifstream ifile(filename);
return ifile;
}
void create_vs_user_file(const string path)
{
cout<<"Creating a new file:"+path<<endl;
ofstream myfile;
myfile.open (path.c_str());
myfile << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n";
myfile << "<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n";
myfile << "</Project>\r\n";
myfile.close();
}
int _tmain(int argc, TCHAR* argv[])
{
//std::cin.get();
cout<<"Prerequisites:"<<endl;
cout<<"1) You must have dependencies installed"<<endl;
cout<<"2) OpenVibe compiled using provided in \\scripts bat file"<<endl;
cout<<"3) You must have VS projects generated using bat file from \\scripts"<<endl<<endl;
cout<<"Please close ALL instances of Visual Studio!"<<endl<<endl;
string project = "";
if (argc>1) project = string(argv[1]);
else
{
cout<<"Usage:"<<endl<<"AdjustOpenVibe.exe \"D:\\Data\\current_work\\OpenVibe_src\\local-tmp\\visual\\trunc\\OpenViBE-acquisition-server-dynamic.vcxproj\""<<endl;
return 0;
}
if(!file_exists(project.c_str()))
{
cout<<"File not found! Aborting...";
return 0;
}
custom_replace(project,"\\","/");
cout<<project<<endl;
string openvibe_base = get_openvibe_base_folder(project);
string executable = get_openvibe_executable(project);//needed only for designer and acquisition server, but it is also set on other projects (even if not needed)
cout<<"Executable="<<executable<<endl;
//1. Set Additional Include folders
cout<<"1. Setting Additional Include Folders"<<endl;
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(project.c_str());
cout<<result.description()<<endl;
string includes = ";"+get_global_openvibe_includes(openvibe_base,project);
simple_walker walker("AdditionalIncludeDirectories",includes,true);
doc.traverse(walker);
//2. Setting Additional Libraries Folders
cout<<"2. Setting Additional Libraries Folders"<<endl;
string libs = get_libs(openvibe_base,project);
walker = simple_walker("AdditionalLibraryDirectories",libs,true);
doc.traverse(walker);
//3. Setting Multiprocessor compilation
cout<<"3. Setting Multiprocessor compilation"<<endl;
simple_walker_add walker_add("ClCompile","MultiProcessorCompilation","true");
doc.traverse(walker_add);
//remove TARGET_HAS_ThirdPartyEmotivAPI
cout<<"Emotiv driver disabled!"<<endl;
replace_value_walker replace_walker = replace_value_walker("PreprocessorDefinitions","TARGET_HAS_ThirdPartyEmotivAPI;","");
doc.traverse(replace_walker);
doc.save_file(project.c_str());
cout<<"Done."<<endl;
//4. Change output directory
cout<<"4. Set output folder to dist folder"<<endl;
walker = simple_walker("OutDir","..\\..\\..\\dist\\bin",false);
doc.traverse(walker);
doc.save_file(project.c_str());
cout<<"Done."<<endl;
//5. Open .user file and set variables
cout<<"5. Set environment variables."<<endl;
string project_user = project + string(".user");
if (!file_exists(project_user.c_str()))
{
create_vs_user_file(project_user);
}
result = doc.load_file(project_user.c_str());
cout<<result.description()<<endl;
//check if it is exe
pugi::xml_node node = doc.child("Project");
string dir = openvibe_base + string("/scripts");
_chdir(dir.c_str());
string s = openvibe_base + string("/scripts/win32-init_env_command.cmd>NUL & set");
string with_openvibe_vars=exec(s.c_str());
pugi::xml_node property_group1 = node.append_child("PropertyGroup");
pugi::xml_node env = property_group1.append_child("LocalDebuggerEnvironment");
env.append_child(pugi::node_pcdata).set_value(with_openvibe_vars.c_str());
pugi::xml_node property_group2 = node.append_child("PropertyGroup");
pugi::xml_node cmd = property_group2.append_child("LocalDebuggerCommand");
cmd.append_child(pugi::node_pcdata).set_value((openvibe_base+"/dist/bin/"+executable).c_str());
pugi::xml_node property_group3 = node.append_child("PropertyGroup");
pugi::xml_node folder = property_group3.append_child("LocalDebuggerWorkingDirectory");
folder.append_child(pugi::node_pcdata).set_value((openvibe_base+"/dist/bin/").c_str());
doc.save_file(project_user.c_str());
cout<<"Done."<<endl;
cout<<"TODO:"<<endl;
cout<<"1) You need to disable the projects you do not need to rebuild in VS->Solution or Project properties->Confugration Manager"<<endl;
cout<<"2) Set-up your start-up project"<<endl;
return 0;
}
|
/*
netlibrary网络库给用户提供了两个主要的类
TcpServer : 用于编写服务器程序的
TcpClient : 用于编写客户端程序的
epoll + 线程池
好处:能够把网络I/O的代码和业务代码区分开
用户的连接和断开 用户的可读写事件
*/
#include <netlibrary/TcpServer.h>
#include <netlibrary/EventLoop.h>
#include <iostream>
#include <functional>
#include <string>
using namespace std;
using namespace placeholders;
/*基于netlibrary网络库开发服务器程序
1.组合TcpServer对象
2.创建EventLoop事件循环对象的指针
3.明确TcpServer构造函数需要什么参数,输出ChatServer的构造函数
4.在当前服务器类的构造函数当中,注册处理连接的回调函数和处理读写时间的回调函数
5.设置合适的服务端线程数量,netlibrary库会自己分配I/O线程和worker线程
*/
class ChatServer
{
public:
ChatServer(EventLoop *loop, // 事件循环
const InetAddress &listenAddr, // IP+Port
const string &nameArg)
: _server(loop, listenAddr, nameArg), _loop(loop)
{
// 给服务器注册用户连接的创建和断开回调
_server.setConnectionCallback(std::bind(&ChatServer::onConnection, this, _1));
// 给服务器注册用户读写事件回调
_server.setMessageCallback(std::bind(&ChatServer::onMessage, this, _1, _2, _3));
// 设置服务器端的线程数量 1个I/O线程 3个worker线程
_server.setThreadNum(4);
}
void start()
{
_server.start();
}
private:
// 专门处理用户的连接创建和断开 epoll listenfd accept
void onConnection(const TcpConnectionPtr &conn)
{
if (conn->connected())
{
cout << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << " state:online" << endl;
}
else
{
cout << conn->peerAddress().toIpPort() << " -> " << conn->localAddress().toIpPort() << " state:offline" << endl;
conn->shutdown(); // close(fd)
// _loop->quit();
}
}
// 专门处理用户的读写事件
void onMessage(const TcpConnectionPtr &conn, // 连接
Buffer *buffer, // 缓冲区
Timestamp time) // 接收到数据的时间信息
{
string buf = buffer->retrieveAllAsString();
cout << "recv data:" << buf << " time:" << time.toFormattedString() << endl;
conn->send(buf);
}
TcpServer _server; // #1
EventLoop *_loop; // #2 epoll
};
int main()
{
EventLoop loop; // epoll
InetAddress addr("127.0.0.1", 6000);
ChatServer server(&loop, addr, "ChatServer");
server.start(); // listenfd epoll_ctl=>epoll
loop.loop(); // epoll_wait以阻塞方式等待新用户连接,已连接用户的读写事件等
}
|
#if defined(_WIN64) || defined(_WIN32)
// cv-test.cpp : Defines the entry point for the console application.
//
#include <opencv2\core.hpp>
#include <opencv2\imgproc.hpp>
#include <opencv2\highgui.hpp>
#include <opencv2\calib3d.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
int x = 20, y = 20;
int sigmaIndex = 15, thetaIndex = 90, lambdIndex = 45, gammaIndex = 15, psiIndex = 1;
double sigmaMax = 5.0, thetaMax = 2.0*CV_PI, lambdMax = 1.0, gammaMax = 3.0, psiMax=2.0*CV_PI;
Mat input, output, kernel;
int tminIndex = 0;
int tmaxIndex = 100;
int t1i, t2i;
double t1m = 200, t2m = 600;
double tminMax = 255.0;
double tmaxMax = 255.0;
void on_trackbar(int, void *data)
{
Mat filtered, sx, sy;
Canny(input, filtered, (double(t1i) / 100.0 * t1m), (double(t2i) / 100.0 * t2m), 3);
imshow("canny", filtered);
kernel = getGaborKernel(Size(x, y),
(double(sigmaIndex) / 100.0 * sigmaMax),
(double(thetaIndex) / 360.0 * thetaMax),
(double(lambdIndex) / 100.0 * lambdMax),
(double(gammaIndex) / 100.0 * gammaMax),
(double(psiIndex) / 360.0 * psiMax));
filter2D(filtered, filtered, CV_8UC3, kernel);
imshow("kernel", kernel);
imshow("gabor", filtered);/*
imshow("input", input);
Sobel(input, sx, CV_8UC1, 1, 0);
Sobel(input, sy, CV_8UC1, 0, 1);
filtered = sx + sy;
imshow("filtered", filtered);
threshold(filtered, filtered, (double(tminIndex) / 100.0 * tminMax), (double(tmaxIndex) / 100.0 * tmaxMax), CV_THRESH_BINARY);
imshow("filtered", filtered);*/
}
int main()
{
input = imread("images/realtest1.jpg", CV_LOAD_IMAGE_GRAYSCALE);
resize(input, input, Size(640, 360));
namedWindow("gabor controls", CV_WINDOW_NORMAL);
resizeWindow("gabor controls", 800, 600);
namedWindow("kernel", CV_WINDOW_NORMAL);
resizeWindow("kernel", 400, 400);
createTrackbar("x", "gabor controls", &x, 100, on_trackbar);
createTrackbar("y", "gabor controls", &y, 100, on_trackbar);
createTrackbar("sigma", "gabor controls", &sigmaIndex, 100, on_trackbar);
createTrackbar("theta", "gabor controls", &thetaIndex, 360, on_trackbar);
createTrackbar("lambd", "gabor controls", &lambdIndex, 100, on_trackbar);
createTrackbar("gamma", "gabor controls", &gammaIndex, 100, on_trackbar);
createTrackbar("psi", "gabor controls", &psiIndex, 360, on_trackbar);
createTrackbar("tmin", "gabor controls", &tminIndex, 100, on_trackbar);
createTrackbar("tmax", "gabor controls", &tmaxIndex, 100, on_trackbar);
createTrackbar("t1i", "gabor controls", &t1i, 100, on_trackbar);
createTrackbar("t2i", "gabor controls", &t2i, 100, on_trackbar);
on_trackbar(0, 0);
waitKey();
return 0;
}
#endif
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "./UI_Interaction.h"
#include "Components/Image.h"
#include "Materials/MaterialInstanceDynamic.h"
void UUI_Interaction::NativeConstruct()
{
Super::NativeConstruct();
SetInteractionProgress(0);
}
void UUI_Interaction::SetInteractionProgress(const float Amount) const
{
auto ringMaterial = InteractionRing->GetDynamicMaterial();
if (Amount <= 0 || Amount >= 1)
{
ringMaterial->SetScalarParameterValue(AlphaScalarName, 0);
return;
}
ringMaterial->SetScalarParameterValue(AlphaScalarName, Amount);
}
|
/*
* Screen.h
*
* Created on: 10 сент. 2017 г.
* Author: Соня
*/
#ifndef SCREEN_H_
#define SCREEN_H_
#include "Common.h"
#include "Singleton.h"
typedef struct {
int width;
int height;
} ScreenSize;
class Screen: public Singleton<Screen> {
public:
static Screen* GetSingletonPtr(void);
static Screen& GetSingleton(void);
void SetSize(int width, int height);
ScreenSize GetSize();
private:
int _width;
int _height;
};
#endif /* SCREEN_H_ */
|
/*
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2020, Savely Pototsky (SavaLione)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/**
* @file
* @brief Web page
* @author SavaLione
* @date 22 Nov 2020
*/
#ifndef WEB_PAGE_H
#define WEB_PAGE_H
#include <string>
#include <fcgi_config.h>
#include <fcgiapp.h>
// enum site_pages
// {
// _unknown_page = -1,
// _index = 1,
// _login = 2
// };
// enum method
// {
// _unknown_method = -1,
// _GET = 1,
// _POST = 2
// };
// class page
// {
// public:
// page(FCGX_Request &request) : _request(request) { _init(); };
// ~page();
// void show();
// private:
// FCGX_Request &_request;
// void _init();
// void _debug();
// site_pages const _get_site_page();
// site_pages _site_page = _unknown_page;
// method const _get_method();
// method _method = _unknown_method;
// std::string _request_method = FCGX_GetParam("REQUEST_METHOD", _request.envp);
// std::string _content_length = FCGX_GetParam("CONTENT_LENGTH", _request.envp);
// std::string _remote_addr = FCGX_GetParam("REMOTE_ADDR", _request.envp);
// std::string _request_uri = FCGX_GetParam("REQUEST_URI", _request.envp);
// std::string _query_string = FCGX_GetParam("QUERY_STRING", _request.envp);
// std::string _document_uri = FCGX_GetParam("DOCUMENT_URI", _request.envp);
// std::string _document_root = FCGX_GetParam("DOCUMENT_ROOT", _request.envp);
// std::string _http_host = FCGX_GetParam("HTTP_HOST", _request.envp);
// std::string _http_cookie;
// bool _cookie = false;
// void _web_header();
// /* method */
// void _method_get();
// void _method_post();
// /* pages */
// void _page_unknown();
// void _page_index();
// void _page_login();
// };
// enum method
// {
// _unknown_method = -1,
// _GET = 1,
// _POST = 2
// };
// class page
// {
// public:
// page();
// ~page();
// protected:
// std::string _request_method = FCGX_GetParam("REQUEST_METHOD", _request.envp);
// std::string _content_length = FCGX_GetParam("CONTENT_LENGTH", _request.envp);
// std::string _remote_addr = FCGX_GetParam("REMOTE_ADDR", _request.envp);
// std::string _request_uri = FCGX_GetParam("REQUEST_URI", _request.envp);
// std::string _query_string = FCGX_GetParam("QUERY_STRING", _request.envp);
// std::string _document_uri = FCGX_GetParam("DOCUMENT_URI", _request.envp);
// std::string _document_root = FCGX_GetParam("DOCUMENT_ROOT", _request.envp);
// std::string _http_host = FCGX_GetParam("HTTP_HOST", _request.envp);
// std::string _http_cookie;
// bool _cookie = false;
// private:
// /* data */
// };
// page::page(/* args */)
// {
// }
// page::~page()
// {
// }
#endif // WEB_PAGE_H
|
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define ok() puts(ok?"Yes":"No");
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef set<int> si;
typedef map<string, int> msi;
typedef greater<int> gt;
typedef priority_queue<int, vector<int>, gt> minq;
typedef long long ll;
typedef pair<ll,ll> pll;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
//clang++ -std=c++11 -stdlib=libc++
int main() {
int n,m,x; cin >> n >> m>>x;
vi cost(n);
vvi a(n, vi(m,0));
rep(i, n) {
cin >> cost[i];
rep(j, m) {
cin >> a[i][j];
}
}
int ans = INF;
auto f = [&](vi u) {
for(int num : u) {
if (num<x) return false;
}
return true;
};
for (int i=0; i<(1<<n); i++) {
int price = 0;
vi understanding(m,0);
for (int j=0; j<n; j++) {
if ((i>>j)&1) {
price+=cost[j];
rep(k,m) {
understanding[k] += a[j][k];
}
}
}
if (f(understanding)) ans = min(ans, price);
}
if (ans == INF) ans = -1;
cout << ans << endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.